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/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/SaveAndRestore.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include <algorithm>
91 #include <bitset>
92 #include <cassert>
93 #include <cstddef>
94 #include <cstdint>
95 #include <functional>
96 #include <limits>
97 #include <string>
98 #include <tuple>
99 #include <utility>
100 
101 using namespace clang;
102 using namespace sema;
103 
104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
105                                                     unsigned ByteNo) const {
106   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
107                                Context.getTargetInfo());
108 }
109 
110 /// Checks that a call expression's argument count is the desired number.
111 /// This is useful when doing custom type-checking.  Returns true on error.
112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
113   unsigned argCount = call->getNumArgs();
114   if (argCount == desiredArgCount) return false;
115 
116   if (argCount < desiredArgCount)
117     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
118            << 0 /*function call*/ << desiredArgCount << argCount
119            << call->getSourceRange();
120 
121   // Highlight all the excess arguments.
122   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
123                     call->getArg(argCount - 1)->getEndLoc());
124 
125   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
126     << 0 /*function call*/ << desiredArgCount << argCount
127     << call->getArg(1)->getSourceRange();
128 }
129 
130 /// Check that the first argument to __builtin_annotation is an integer
131 /// and the second argument is a non-wide string literal.
132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
133   if (checkArgCount(S, TheCall, 2))
134     return true;
135 
136   // First argument should be an integer.
137   Expr *ValArg = TheCall->getArg(0);
138   QualType Ty = ValArg->getType();
139   if (!Ty->isIntegerType()) {
140     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
141         << ValArg->getSourceRange();
142     return true;
143   }
144 
145   // Second argument should be a constant string.
146   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
147   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
148   if (!Literal || !Literal->isAscii()) {
149     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
150         << StrArg->getSourceRange();
151     return true;
152   }
153 
154   TheCall->setType(Ty);
155   return false;
156 }
157 
158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
159   // We need at least one argument.
160   if (TheCall->getNumArgs() < 1) {
161     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
162         << 0 << 1 << TheCall->getNumArgs()
163         << TheCall->getCallee()->getSourceRange();
164     return true;
165   }
166 
167   // All arguments should be wide string literals.
168   for (Expr *Arg : TheCall->arguments()) {
169     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
170     if (!Literal || !Literal->isWide()) {
171       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
172           << Arg->getSourceRange();
173       return true;
174     }
175   }
176 
177   return false;
178 }
179 
180 /// Check that the argument to __builtin_addressof is a glvalue, and set the
181 /// result type to the corresponding pointer type.
182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
183   if (checkArgCount(S, TheCall, 1))
184     return true;
185 
186   ExprResult Arg(TheCall->getArg(0));
187   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
188   if (ResultType.isNull())
189     return true;
190 
191   TheCall->setArg(0, Arg.get());
192   TheCall->setType(ResultType);
193   return false;
194 }
195 
196 /// Check the number of arguments and set the result type to
197 /// the argument type.
198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
199   if (checkArgCount(S, TheCall, 1))
200     return true;
201 
202   TheCall->setType(TheCall->getArg(0)->getType());
203   return false;
204 }
205 
206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
208 /// type (but not a function pointer) and that the alignment is a power-of-two.
209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
210   if (checkArgCount(S, TheCall, 2))
211     return true;
212 
213   clang::Expr *Source = TheCall->getArg(0);
214   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
215 
216   auto IsValidIntegerType = [](QualType Ty) {
217     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
218   };
219   QualType SrcTy = Source->getType();
220   // We should also be able to use it with arrays (but not functions!).
221   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
222     SrcTy = S.Context.getDecayedType(SrcTy);
223   }
224   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
225       SrcTy->isFunctionPointerType()) {
226     // FIXME: this is not quite the right error message since we don't allow
227     // floating point types, or member pointers.
228     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
229         << SrcTy;
230     return true;
231   }
232 
233   clang::Expr *AlignOp = TheCall->getArg(1);
234   if (!IsValidIntegerType(AlignOp->getType())) {
235     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
236         << AlignOp->getType();
237     return true;
238   }
239   Expr::EvalResult AlignResult;
240   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
241   // We can't check validity of alignment if it is value dependent.
242   if (!AlignOp->isValueDependent() &&
243       AlignOp->EvaluateAsInt(AlignResult, S.Context,
244                              Expr::SE_AllowSideEffects)) {
245     llvm::APSInt AlignValue = AlignResult.Val.getInt();
246     llvm::APSInt MaxValue(
247         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
248     if (AlignValue < 1) {
249       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
250       return true;
251     }
252     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
253       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
254           << MaxValue.toString(10);
255       return true;
256     }
257     if (!AlignValue.isPowerOf2()) {
258       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
259       return true;
260     }
261     if (AlignValue == 1) {
262       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
263           << IsBooleanAlignBuiltin;
264     }
265   }
266 
267   ExprResult SrcArg = S.PerformCopyInitialization(
268       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
269       SourceLocation(), Source);
270   if (SrcArg.isInvalid())
271     return true;
272   TheCall->setArg(0, SrcArg.get());
273   ExprResult AlignArg =
274       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
275                                       S.Context, AlignOp->getType(), false),
276                                   SourceLocation(), AlignOp);
277   if (AlignArg.isInvalid())
278     return true;
279   TheCall->setArg(1, AlignArg.get());
280   // For align_up/align_down, the return type is the same as the (potentially
281   // decayed) argument type including qualifiers. For is_aligned(), the result
282   // is always bool.
283   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
284   return false;
285 }
286 
287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
288                                 unsigned BuiltinID) {
289   if (checkArgCount(S, TheCall, 3))
290     return true;
291 
292   // First two arguments should be integers.
293   for (unsigned I = 0; I < 2; ++I) {
294     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
295     if (Arg.isInvalid()) return true;
296     TheCall->setArg(I, Arg.get());
297 
298     QualType Ty = Arg.get()->getType();
299     if (!Ty->isIntegerType()) {
300       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
301           << Ty << Arg.get()->getSourceRange();
302       return true;
303     }
304   }
305 
306   // Third argument should be a pointer to a non-const integer.
307   // IRGen correctly handles volatile, restrict, and address spaces, and
308   // the other qualifiers aren't possible.
309   {
310     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
311     if (Arg.isInvalid()) return true;
312     TheCall->setArg(2, Arg.get());
313 
314     QualType Ty = Arg.get()->getType();
315     const auto *PtrTy = Ty->getAs<PointerType>();
316     if (!PtrTy ||
317         !PtrTy->getPointeeType()->isIntegerType() ||
318         PtrTy->getPointeeType().isConstQualified()) {
319       S.Diag(Arg.get()->getBeginLoc(),
320              diag::err_overflow_builtin_must_be_ptr_int)
321         << Ty << Arg.get()->getSourceRange();
322       return true;
323     }
324   }
325 
326   // Disallow signed ExtIntType args larger than 128 bits to mul function until
327   // we improve backend support.
328   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
329     for (unsigned I = 0; I < 3; ++I) {
330       const auto Arg = TheCall->getArg(I);
331       // Third argument will be a pointer.
332       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
333       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
334           S.getASTContext().getIntWidth(Ty) > 128)
335         return S.Diag(Arg->getBeginLoc(),
336                       diag::err_overflow_builtin_ext_int_max_size)
337                << 128;
338     }
339   }
340 
341   return false;
342 }
343 
344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
345   if (checkArgCount(S, BuiltinCall, 2))
346     return true;
347 
348   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
349   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
350   Expr *Call = BuiltinCall->getArg(0);
351   Expr *Chain = BuiltinCall->getArg(1);
352 
353   if (Call->getStmtClass() != Stmt::CallExprClass) {
354     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
355         << Call->getSourceRange();
356     return true;
357   }
358 
359   auto CE = cast<CallExpr>(Call);
360   if (CE->getCallee()->getType()->isBlockPointerType()) {
361     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
362         << Call->getSourceRange();
363     return true;
364   }
365 
366   const Decl *TargetDecl = CE->getCalleeDecl();
367   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
368     if (FD->getBuiltinID()) {
369       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
370           << Call->getSourceRange();
371       return true;
372     }
373 
374   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
375     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
376         << Call->getSourceRange();
377     return true;
378   }
379 
380   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
381   if (ChainResult.isInvalid())
382     return true;
383   if (!ChainResult.get()->getType()->isPointerType()) {
384     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
385         << Chain->getSourceRange();
386     return true;
387   }
388 
389   QualType ReturnTy = CE->getCallReturnType(S.Context);
390   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
391   QualType BuiltinTy = S.Context.getFunctionType(
392       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
393   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
394 
395   Builtin =
396       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
397 
398   BuiltinCall->setType(CE->getType());
399   BuiltinCall->setValueKind(CE->getValueKind());
400   BuiltinCall->setObjectKind(CE->getObjectKind());
401   BuiltinCall->setCallee(Builtin);
402   BuiltinCall->setArg(1, ChainResult.get());
403 
404   return false;
405 }
406 
407 namespace {
408 
409 class EstimateSizeFormatHandler
410     : public analyze_format_string::FormatStringHandler {
411   size_t Size;
412 
413 public:
414   EstimateSizeFormatHandler(StringRef Format)
415       : Size(std::min(Format.find(0), Format.size()) +
416              1 /* null byte always written by sprintf */) {}
417 
418   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
419                              const char *, unsigned SpecifierLen) override {
420 
421     const size_t FieldWidth = computeFieldWidth(FS);
422     const size_t Precision = computePrecision(FS);
423 
424     // The actual format.
425     switch (FS.getConversionSpecifier().getKind()) {
426     // Just a char.
427     case analyze_format_string::ConversionSpecifier::cArg:
428     case analyze_format_string::ConversionSpecifier::CArg:
429       Size += std::max(FieldWidth, (size_t)1);
430       break;
431     // Just an integer.
432     case analyze_format_string::ConversionSpecifier::dArg:
433     case analyze_format_string::ConversionSpecifier::DArg:
434     case analyze_format_string::ConversionSpecifier::iArg:
435     case analyze_format_string::ConversionSpecifier::oArg:
436     case analyze_format_string::ConversionSpecifier::OArg:
437     case analyze_format_string::ConversionSpecifier::uArg:
438     case analyze_format_string::ConversionSpecifier::UArg:
439     case analyze_format_string::ConversionSpecifier::xArg:
440     case analyze_format_string::ConversionSpecifier::XArg:
441       Size += std::max(FieldWidth, Precision);
442       break;
443 
444     // %g style conversion switches between %f or %e style dynamically.
445     // %f always takes less space, so default to it.
446     case analyze_format_string::ConversionSpecifier::gArg:
447     case analyze_format_string::ConversionSpecifier::GArg:
448 
449     // Floating point number in the form '[+]ddd.ddd'.
450     case analyze_format_string::ConversionSpecifier::fArg:
451     case analyze_format_string::ConversionSpecifier::FArg:
452       Size += std::max(FieldWidth, 1 /* integer part */ +
453                                        (Precision ? 1 + Precision
454                                                   : 0) /* period + decimal */);
455       break;
456 
457     // Floating point number in the form '[-]d.ddde[+-]dd'.
458     case analyze_format_string::ConversionSpecifier::eArg:
459     case analyze_format_string::ConversionSpecifier::EArg:
460       Size +=
461           std::max(FieldWidth,
462                    1 /* integer part */ +
463                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
464                        1 /* e or E letter */ + 2 /* exponent */);
465       break;
466 
467     // Floating point number in the form '[-]0xh.hhhhp±dd'.
468     case analyze_format_string::ConversionSpecifier::aArg:
469     case analyze_format_string::ConversionSpecifier::AArg:
470       Size +=
471           std::max(FieldWidth,
472                    2 /* 0x */ + 1 /* integer part */ +
473                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
474                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
475       break;
476 
477     // Just a string.
478     case analyze_format_string::ConversionSpecifier::sArg:
479     case analyze_format_string::ConversionSpecifier::SArg:
480       Size += FieldWidth;
481       break;
482 
483     // Just a pointer in the form '0xddd'.
484     case analyze_format_string::ConversionSpecifier::pArg:
485       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
486       break;
487 
488     // A plain percent.
489     case analyze_format_string::ConversionSpecifier::PercentArg:
490       Size += 1;
491       break;
492 
493     default:
494       break;
495     }
496 
497     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
498 
499     if (FS.hasAlternativeForm()) {
500       switch (FS.getConversionSpecifier().getKind()) {
501       default:
502         break;
503       // Force a leading '0'.
504       case analyze_format_string::ConversionSpecifier::oArg:
505         Size += 1;
506         break;
507       // Force a leading '0x'.
508       case analyze_format_string::ConversionSpecifier::xArg:
509       case analyze_format_string::ConversionSpecifier::XArg:
510         Size += 2;
511         break;
512       // Force a period '.' before decimal, even if precision is 0.
513       case analyze_format_string::ConversionSpecifier::aArg:
514       case analyze_format_string::ConversionSpecifier::AArg:
515       case analyze_format_string::ConversionSpecifier::eArg:
516       case analyze_format_string::ConversionSpecifier::EArg:
517       case analyze_format_string::ConversionSpecifier::fArg:
518       case analyze_format_string::ConversionSpecifier::FArg:
519       case analyze_format_string::ConversionSpecifier::gArg:
520       case analyze_format_string::ConversionSpecifier::GArg:
521         Size += (Precision ? 0 : 1);
522         break;
523       }
524     }
525     assert(SpecifierLen <= Size && "no underflow");
526     Size -= SpecifierLen;
527     return true;
528   }
529 
530   size_t getSizeLowerBound() const { return Size; }
531 
532 private:
533   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
534     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
535     size_t FieldWidth = 0;
536     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
537       FieldWidth = FW.getConstantAmount();
538     return FieldWidth;
539   }
540 
541   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
542     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
543     size_t Precision = 0;
544 
545     // See man 3 printf for default precision value based on the specifier.
546     switch (FW.getHowSpecified()) {
547     case analyze_format_string::OptionalAmount::NotSpecified:
548       switch (FS.getConversionSpecifier().getKind()) {
549       default:
550         break;
551       case analyze_format_string::ConversionSpecifier::dArg: // %d
552       case analyze_format_string::ConversionSpecifier::DArg: // %D
553       case analyze_format_string::ConversionSpecifier::iArg: // %i
554         Precision = 1;
555         break;
556       case analyze_format_string::ConversionSpecifier::oArg: // %d
557       case analyze_format_string::ConversionSpecifier::OArg: // %D
558       case analyze_format_string::ConversionSpecifier::uArg: // %d
559       case analyze_format_string::ConversionSpecifier::UArg: // %D
560       case analyze_format_string::ConversionSpecifier::xArg: // %d
561       case analyze_format_string::ConversionSpecifier::XArg: // %D
562         Precision = 1;
563         break;
564       case analyze_format_string::ConversionSpecifier::fArg: // %f
565       case analyze_format_string::ConversionSpecifier::FArg: // %F
566       case analyze_format_string::ConversionSpecifier::eArg: // %e
567       case analyze_format_string::ConversionSpecifier::EArg: // %E
568       case analyze_format_string::ConversionSpecifier::gArg: // %g
569       case analyze_format_string::ConversionSpecifier::GArg: // %G
570         Precision = 6;
571         break;
572       case analyze_format_string::ConversionSpecifier::pArg: // %d
573         Precision = 1;
574         break;
575       }
576       break;
577     case analyze_format_string::OptionalAmount::Constant:
578       Precision = FW.getConstantAmount();
579       break;
580     default:
581       break;
582     }
583     return Precision;
584   }
585 };
586 
587 } // namespace
588 
589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
590 /// __builtin_*_chk function, then use the object size argument specified in the
591 /// source. Otherwise, infer the object size using __builtin_object_size.
592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
593                                                CallExpr *TheCall) {
594   // FIXME: There are some more useful checks we could be doing here:
595   //  - Evaluate strlen of strcpy arguments, use as object size.
596 
597   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
598       isConstantEvaluated())
599     return;
600 
601   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
602   if (!BuiltinID)
603     return;
604 
605   const TargetInfo &TI = getASTContext().getTargetInfo();
606   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
607 
608   unsigned DiagID = 0;
609   bool IsChkVariant = false;
610   Optional<llvm::APSInt> UsedSize;
611   unsigned SizeIndex, ObjectIndex;
612   switch (BuiltinID) {
613   default:
614     return;
615   case Builtin::BIsprintf:
616   case Builtin::BI__builtin___sprintf_chk: {
617     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
618     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
619 
620     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
621 
622       if (!Format->isAscii() && !Format->isUTF8())
623         return;
624 
625       StringRef FormatStrRef = Format->getString();
626       EstimateSizeFormatHandler H(FormatStrRef);
627       const char *FormatBytes = FormatStrRef.data();
628       const ConstantArrayType *T =
629           Context.getAsConstantArrayType(Format->getType());
630       assert(T && "String literal not of constant array type!");
631       size_t TypeSize = T->getSize().getZExtValue();
632 
633       // In case there's a null byte somewhere.
634       size_t StrLen =
635           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
636       if (!analyze_format_string::ParsePrintfString(
637               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
638               Context.getTargetInfo(), false)) {
639         DiagID = diag::warn_fortify_source_format_overflow;
640         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
641                        .extOrTrunc(SizeTypeWidth);
642         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
643           IsChkVariant = true;
644           ObjectIndex = 2;
645         } else {
646           IsChkVariant = false;
647           ObjectIndex = 0;
648         }
649         break;
650       }
651     }
652     return;
653   }
654   case Builtin::BI__builtin___memcpy_chk:
655   case Builtin::BI__builtin___memmove_chk:
656   case Builtin::BI__builtin___memset_chk:
657   case Builtin::BI__builtin___strlcat_chk:
658   case Builtin::BI__builtin___strlcpy_chk:
659   case Builtin::BI__builtin___strncat_chk:
660   case Builtin::BI__builtin___strncpy_chk:
661   case Builtin::BI__builtin___stpncpy_chk:
662   case Builtin::BI__builtin___memccpy_chk:
663   case Builtin::BI__builtin___mempcpy_chk: {
664     DiagID = diag::warn_builtin_chk_overflow;
665     IsChkVariant = true;
666     SizeIndex = TheCall->getNumArgs() - 2;
667     ObjectIndex = TheCall->getNumArgs() - 1;
668     break;
669   }
670 
671   case Builtin::BI__builtin___snprintf_chk:
672   case Builtin::BI__builtin___vsnprintf_chk: {
673     DiagID = diag::warn_builtin_chk_overflow;
674     IsChkVariant = true;
675     SizeIndex = 1;
676     ObjectIndex = 3;
677     break;
678   }
679 
680   case Builtin::BIstrncat:
681   case Builtin::BI__builtin_strncat:
682   case Builtin::BIstrncpy:
683   case Builtin::BI__builtin_strncpy:
684   case Builtin::BIstpncpy:
685   case Builtin::BI__builtin_stpncpy: {
686     // Whether these functions overflow depends on the runtime strlen of the
687     // string, not just the buffer size, so emitting the "always overflow"
688     // diagnostic isn't quite right. We should still diagnose passing a buffer
689     // size larger than the destination buffer though; this is a runtime abort
690     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
691     DiagID = diag::warn_fortify_source_size_mismatch;
692     SizeIndex = TheCall->getNumArgs() - 1;
693     ObjectIndex = 0;
694     break;
695   }
696 
697   case Builtin::BImemcpy:
698   case Builtin::BI__builtin_memcpy:
699   case Builtin::BImemmove:
700   case Builtin::BI__builtin_memmove:
701   case Builtin::BImemset:
702   case Builtin::BI__builtin_memset:
703   case Builtin::BImempcpy:
704   case Builtin::BI__builtin_mempcpy: {
705     DiagID = diag::warn_fortify_source_overflow;
706     SizeIndex = TheCall->getNumArgs() - 1;
707     ObjectIndex = 0;
708     break;
709   }
710   case Builtin::BIsnprintf:
711   case Builtin::BI__builtin_snprintf:
712   case Builtin::BIvsnprintf:
713   case Builtin::BI__builtin_vsnprintf: {
714     DiagID = diag::warn_fortify_source_size_mismatch;
715     SizeIndex = 1;
716     ObjectIndex = 0;
717     break;
718   }
719   }
720 
721   llvm::APSInt ObjectSize;
722   // For __builtin___*_chk, the object size is explicitly provided by the caller
723   // (usually using __builtin_object_size). Use that value to check this call.
724   if (IsChkVariant) {
725     Expr::EvalResult Result;
726     Expr *SizeArg = TheCall->getArg(ObjectIndex);
727     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
728       return;
729     ObjectSize = Result.Val.getInt();
730 
731   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
732   } else {
733     // If the parameter has a pass_object_size attribute, then we should use its
734     // (potentially) more strict checking mode. Otherwise, conservatively assume
735     // type 0.
736     int BOSType = 0;
737     if (const auto *POS =
738             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
739       BOSType = POS->getType();
740 
741     Expr *ObjArg = TheCall->getArg(ObjectIndex);
742     uint64_t Result;
743     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
744       return;
745     // Get the object size in the target's size_t width.
746     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
747   }
748 
749   // Evaluate the number of bytes of the object that this call will use.
750   if (!UsedSize) {
751     Expr::EvalResult Result;
752     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
753     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
754       return;
755     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
756   }
757 
758   if (UsedSize.getValue().ule(ObjectSize))
759     return;
760 
761   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
762   // Skim off the details of whichever builtin was called to produce a better
763   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
764   if (IsChkVariant) {
765     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
766     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
767   } else if (FunctionName.startswith("__builtin_")) {
768     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
769   }
770 
771   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
772                       PDiag(DiagID)
773                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
774                           << UsedSize.getValue().toString(/*Radix=*/10));
775 }
776 
777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
778                                      Scope::ScopeFlags NeededScopeFlags,
779                                      unsigned DiagID) {
780   // Scopes aren't available during instantiation. Fortunately, builtin
781   // functions cannot be template args so they cannot be formed through template
782   // instantiation. Therefore checking once during the parse is sufficient.
783   if (SemaRef.inTemplateInstantiation())
784     return false;
785 
786   Scope *S = SemaRef.getCurScope();
787   while (S && !S->isSEHExceptScope())
788     S = S->getParent();
789   if (!S || !(S->getFlags() & NeededScopeFlags)) {
790     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
791     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
792         << DRE->getDecl()->getIdentifier();
793     return true;
794   }
795 
796   return false;
797 }
798 
799 static inline bool isBlockPointer(Expr *Arg) {
800   return Arg->getType()->isBlockPointerType();
801 }
802 
803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
804 /// void*, which is a requirement of device side enqueue.
805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
806   const BlockPointerType *BPT =
807       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
808   ArrayRef<QualType> Params =
809       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
810   unsigned ArgCounter = 0;
811   bool IllegalParams = false;
812   // Iterate through the block parameters until either one is found that is not
813   // a local void*, or the block is valid.
814   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
815        I != E; ++I, ++ArgCounter) {
816     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
817         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
818             LangAS::opencl_local) {
819       // Get the location of the error. If a block literal has been passed
820       // (BlockExpr) then we can point straight to the offending argument,
821       // else we just point to the variable reference.
822       SourceLocation ErrorLoc;
823       if (isa<BlockExpr>(BlockArg)) {
824         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
825         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
826       } else if (isa<DeclRefExpr>(BlockArg)) {
827         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
828       }
829       S.Diag(ErrorLoc,
830              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
831       IllegalParams = true;
832     }
833   }
834 
835   return IllegalParams;
836 }
837 
838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
839   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
840     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
841         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
842     return true;
843   }
844   return false;
845 }
846 
847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
848   if (checkArgCount(S, TheCall, 2))
849     return true;
850 
851   if (checkOpenCLSubgroupExt(S, TheCall))
852     return true;
853 
854   // First argument is an ndrange_t type.
855   Expr *NDRangeArg = TheCall->getArg(0);
856   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
857     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
858         << TheCall->getDirectCallee() << "'ndrange_t'";
859     return true;
860   }
861 
862   Expr *BlockArg = TheCall->getArg(1);
863   if (!isBlockPointer(BlockArg)) {
864     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
865         << TheCall->getDirectCallee() << "block";
866     return true;
867   }
868   return checkOpenCLBlockArgs(S, BlockArg);
869 }
870 
871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
872 /// get_kernel_work_group_size
873 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
875   if (checkArgCount(S, TheCall, 1))
876     return true;
877 
878   Expr *BlockArg = TheCall->getArg(0);
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 /// Diagnose integer type and any valid implicit conversion to it.
888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
889                                       const QualType &IntType);
890 
891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
892                                             unsigned Start, unsigned End) {
893   bool IllegalParams = false;
894   for (unsigned I = Start; I <= End; ++I)
895     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
896                                               S.Context.getSizeType());
897   return IllegalParams;
898 }
899 
900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
901 /// 'local void*' parameter of passed block.
902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
903                                            Expr *BlockArg,
904                                            unsigned NumNonVarArgs) {
905   const BlockPointerType *BPT =
906       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
907   unsigned NumBlockParams =
908       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
909   unsigned TotalNumArgs = TheCall->getNumArgs();
910 
911   // For each argument passed to the block, a corresponding uint needs to
912   // be passed to describe the size of the local memory.
913   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
914     S.Diag(TheCall->getBeginLoc(),
915            diag::err_opencl_enqueue_kernel_local_size_args);
916     return true;
917   }
918 
919   // Check that the sizes of the local memory are specified by integers.
920   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
921                                          TotalNumArgs - 1);
922 }
923 
924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
925 /// overload formats specified in Table 6.13.17.1.
926 /// int enqueue_kernel(queue_t queue,
927 ///                    kernel_enqueue_flags_t flags,
928 ///                    const ndrange_t ndrange,
929 ///                    void (^block)(void))
930 /// int enqueue_kernel(queue_t queue,
931 ///                    kernel_enqueue_flags_t flags,
932 ///                    const ndrange_t ndrange,
933 ///                    uint num_events_in_wait_list,
934 ///                    clk_event_t *event_wait_list,
935 ///                    clk_event_t *event_ret,
936 ///                    void (^block)(void))
937 /// int enqueue_kernel(queue_t queue,
938 ///                    kernel_enqueue_flags_t flags,
939 ///                    const ndrange_t ndrange,
940 ///                    void (^block)(local void*, ...),
941 ///                    uint size0, ...)
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    uint num_events_in_wait_list,
946 ///                    clk_event_t *event_wait_list,
947 ///                    clk_event_t *event_ret,
948 ///                    void (^block)(local void*, ...),
949 ///                    uint size0, ...)
950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
951   unsigned NumArgs = TheCall->getNumArgs();
952 
953   if (NumArgs < 4) {
954     S.Diag(TheCall->getBeginLoc(),
955            diag::err_typecheck_call_too_few_args_at_least)
956         << 0 << 4 << NumArgs;
957     return true;
958   }
959 
960   Expr *Arg0 = TheCall->getArg(0);
961   Expr *Arg1 = TheCall->getArg(1);
962   Expr *Arg2 = TheCall->getArg(2);
963   Expr *Arg3 = TheCall->getArg(3);
964 
965   // First argument always needs to be a queue_t type.
966   if (!Arg0->getType()->isQueueT()) {
967     S.Diag(TheCall->getArg(0)->getBeginLoc(),
968            diag::err_opencl_builtin_expected_type)
969         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
970     return true;
971   }
972 
973   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
974   if (!Arg1->getType()->isIntegerType()) {
975     S.Diag(TheCall->getArg(1)->getBeginLoc(),
976            diag::err_opencl_builtin_expected_type)
977         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
978     return true;
979   }
980 
981   // Third argument is always an ndrange_t type.
982   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
983     S.Diag(TheCall->getArg(2)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << "'ndrange_t'";
986     return true;
987   }
988 
989   // With four arguments, there is only one form that the function could be
990   // called in: no events and no variable arguments.
991   if (NumArgs == 4) {
992     // check that the last argument is the right block type.
993     if (!isBlockPointer(Arg3)) {
994       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
995           << TheCall->getDirectCallee() << "block";
996       return true;
997     }
998     // we have a block type, check the prototype
999     const BlockPointerType *BPT =
1000         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1001     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1002       S.Diag(Arg3->getBeginLoc(),
1003              diag::err_opencl_enqueue_kernel_blocks_no_args);
1004       return true;
1005     }
1006     return false;
1007   }
1008   // we can have block + varargs.
1009   if (isBlockPointer(Arg3))
1010     return (checkOpenCLBlockArgs(S, Arg3) ||
1011             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1012   // last two cases with either exactly 7 args or 7 args and varargs.
1013   if (NumArgs >= 7) {
1014     // check common block argument.
1015     Expr *Arg6 = TheCall->getArg(6);
1016     if (!isBlockPointer(Arg6)) {
1017       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1018           << TheCall->getDirectCallee() << "block";
1019       return true;
1020     }
1021     if (checkOpenCLBlockArgs(S, Arg6))
1022       return true;
1023 
1024     // Forth argument has to be any integer type.
1025     if (!Arg3->getType()->isIntegerType()) {
1026       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1027              diag::err_opencl_builtin_expected_type)
1028           << TheCall->getDirectCallee() << "integer";
1029       return true;
1030     }
1031     // check remaining common arguments.
1032     Expr *Arg4 = TheCall->getArg(4);
1033     Expr *Arg5 = TheCall->getArg(5);
1034 
1035     // Fifth argument is always passed as a pointer to clk_event_t.
1036     if (!Arg4->isNullPointerConstant(S.Context,
1037                                      Expr::NPC_ValueDependentIsNotNull) &&
1038         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1039       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1040              diag::err_opencl_builtin_expected_type)
1041           << TheCall->getDirectCallee()
1042           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1043       return true;
1044     }
1045 
1046     // Sixth argument is always passed as a pointer to clk_event_t.
1047     if (!Arg5->isNullPointerConstant(S.Context,
1048                                      Expr::NPC_ValueDependentIsNotNull) &&
1049         !(Arg5->getType()->isPointerType() &&
1050           Arg5->getType()->getPointeeType()->isClkEventT())) {
1051       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1052              diag::err_opencl_builtin_expected_type)
1053           << TheCall->getDirectCallee()
1054           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1055       return true;
1056     }
1057 
1058     if (NumArgs == 7)
1059       return false;
1060 
1061     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1062   }
1063 
1064   // None of the specific case has been detected, give generic error
1065   S.Diag(TheCall->getBeginLoc(),
1066          diag::err_opencl_enqueue_kernel_incorrect_args);
1067   return true;
1068 }
1069 
1070 /// Returns OpenCL access qual.
1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1072     return D->getAttr<OpenCLAccessAttr>();
1073 }
1074 
1075 /// Returns true if pipe element type is different from the pointer.
1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1077   const Expr *Arg0 = Call->getArg(0);
1078   // First argument type should always be pipe.
1079   if (!Arg0->getType()->isPipeType()) {
1080     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1081         << Call->getDirectCallee() << Arg0->getSourceRange();
1082     return true;
1083   }
1084   OpenCLAccessAttr *AccessQual =
1085       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1086   // Validates the access qualifier is compatible with the call.
1087   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1088   // read_only and write_only, and assumed to be read_only if no qualifier is
1089   // specified.
1090   switch (Call->getDirectCallee()->getBuiltinID()) {
1091   case Builtin::BIread_pipe:
1092   case Builtin::BIreserve_read_pipe:
1093   case Builtin::BIcommit_read_pipe:
1094   case Builtin::BIwork_group_reserve_read_pipe:
1095   case Builtin::BIsub_group_reserve_read_pipe:
1096   case Builtin::BIwork_group_commit_read_pipe:
1097   case Builtin::BIsub_group_commit_read_pipe:
1098     if (!(!AccessQual || AccessQual->isReadOnly())) {
1099       S.Diag(Arg0->getBeginLoc(),
1100              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101           << "read_only" << Arg0->getSourceRange();
1102       return true;
1103     }
1104     break;
1105   case Builtin::BIwrite_pipe:
1106   case Builtin::BIreserve_write_pipe:
1107   case Builtin::BIcommit_write_pipe:
1108   case Builtin::BIwork_group_reserve_write_pipe:
1109   case Builtin::BIsub_group_reserve_write_pipe:
1110   case Builtin::BIwork_group_commit_write_pipe:
1111   case Builtin::BIsub_group_commit_write_pipe:
1112     if (!(AccessQual && AccessQual->isWriteOnly())) {
1113       S.Diag(Arg0->getBeginLoc(),
1114              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1115           << "write_only" << Arg0->getSourceRange();
1116       return true;
1117     }
1118     break;
1119   default:
1120     break;
1121   }
1122   return false;
1123 }
1124 
1125 /// Returns true if pipe element type is different from the pointer.
1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1127   const Expr *Arg0 = Call->getArg(0);
1128   const Expr *ArgIdx = Call->getArg(Idx);
1129   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1130   const QualType EltTy = PipeTy->getElementType();
1131   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1132   // The Idx argument should be a pointer and the type of the pointer and
1133   // the type of pipe element should also be the same.
1134   if (!ArgTy ||
1135       !S.Context.hasSameType(
1136           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1137     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1138         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1139         << ArgIdx->getType() << ArgIdx->getSourceRange();
1140     return true;
1141   }
1142   return false;
1143 }
1144 
1145 // Performs semantic analysis for the read/write_pipe call.
1146 // \param S Reference to the semantic analyzer.
1147 // \param Call A pointer to the builtin call.
1148 // \return True if a semantic error has been found, false otherwise.
1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1150   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1151   // functions have two forms.
1152   switch (Call->getNumArgs()) {
1153   case 2:
1154     if (checkOpenCLPipeArg(S, Call))
1155       return true;
1156     // The call with 2 arguments should be
1157     // read/write_pipe(pipe T, T*).
1158     // Check packet type T.
1159     if (checkOpenCLPipePacketType(S, Call, 1))
1160       return true;
1161     break;
1162 
1163   case 4: {
1164     if (checkOpenCLPipeArg(S, Call))
1165       return true;
1166     // The call with 4 arguments should be
1167     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1168     // Check reserve_id_t.
1169     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1170       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1171           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1172           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1173       return true;
1174     }
1175 
1176     // Check the index.
1177     const Expr *Arg2 = Call->getArg(2);
1178     if (!Arg2->getType()->isIntegerType() &&
1179         !Arg2->getType()->isUnsignedIntegerType()) {
1180       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1181           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1182           << Arg2->getType() << Arg2->getSourceRange();
1183       return true;
1184     }
1185 
1186     // Check packet type T.
1187     if (checkOpenCLPipePacketType(S, Call, 3))
1188       return true;
1189   } break;
1190   default:
1191     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1192         << Call->getDirectCallee() << Call->getSourceRange();
1193     return true;
1194   }
1195 
1196   return false;
1197 }
1198 
1199 // Performs a semantic analysis on the {work_group_/sub_group_
1200 //        /_}reserve_{read/write}_pipe
1201 // \param S Reference to the semantic analyzer.
1202 // \param Call The call to the builtin function to be analyzed.
1203 // \return True if a semantic error was found, false otherwise.
1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1205   if (checkArgCount(S, Call, 2))
1206     return true;
1207 
1208   if (checkOpenCLPipeArg(S, Call))
1209     return true;
1210 
1211   // Check the reserve size.
1212   if (!Call->getArg(1)->getType()->isIntegerType() &&
1213       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1214     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1215         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1216         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1217     return true;
1218   }
1219 
1220   // Since return type of reserve_read/write_pipe built-in function is
1221   // reserve_id_t, which is not defined in the builtin def file , we used int
1222   // as return type and need to override the return type of these functions.
1223   Call->setType(S.Context.OCLReserveIDTy);
1224 
1225   return false;
1226 }
1227 
1228 // Performs a semantic analysis on {work_group_/sub_group_
1229 //        /_}commit_{read/write}_pipe
1230 // \param S Reference to the semantic analyzer.
1231 // \param Call The call to the builtin function to be analyzed.
1232 // \return True if a semantic error was found, false otherwise.
1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1234   if (checkArgCount(S, Call, 2))
1235     return true;
1236 
1237   if (checkOpenCLPipeArg(S, Call))
1238     return true;
1239 
1240   // Check reserve_id_t.
1241   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1242     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1243         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1244         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1245     return true;
1246   }
1247 
1248   return false;
1249 }
1250 
1251 // Performs a semantic analysis on the call to built-in Pipe
1252 //        Query Functions.
1253 // \param S Reference to the semantic analyzer.
1254 // \param Call The call to the builtin function to be analyzed.
1255 // \return True if a semantic error was found, false otherwise.
1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1257   if (checkArgCount(S, Call, 1))
1258     return true;
1259 
1260   if (!Call->getArg(0)->getType()->isPipeType()) {
1261     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1262         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1263     return true;
1264   }
1265 
1266   return false;
1267 }
1268 
1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1270 // Performs semantic analysis for the to_global/local/private call.
1271 // \param S Reference to the semantic analyzer.
1272 // \param BuiltinID ID of the builtin function.
1273 // \param Call A pointer to the builtin call.
1274 // \return True if a semantic error has been found, false otherwise.
1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1276                                     CallExpr *Call) {
1277   if (checkArgCount(S, Call, 1))
1278     return true;
1279 
1280   auto RT = Call->getArg(0)->getType();
1281   if (!RT->isPointerType() || RT->getPointeeType()
1282       .getAddressSpace() == LangAS::opencl_constant) {
1283     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1284         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1285     return true;
1286   }
1287 
1288   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1289     S.Diag(Call->getArg(0)->getBeginLoc(),
1290            diag::warn_opencl_generic_address_space_arg)
1291         << Call->getDirectCallee()->getNameInfo().getAsString()
1292         << Call->getArg(0)->getSourceRange();
1293   }
1294 
1295   RT = RT->getPointeeType();
1296   auto Qual = RT.getQualifiers();
1297   switch (BuiltinID) {
1298   case Builtin::BIto_global:
1299     Qual.setAddressSpace(LangAS::opencl_global);
1300     break;
1301   case Builtin::BIto_local:
1302     Qual.setAddressSpace(LangAS::opencl_local);
1303     break;
1304   case Builtin::BIto_private:
1305     Qual.setAddressSpace(LangAS::opencl_private);
1306     break;
1307   default:
1308     llvm_unreachable("Invalid builtin function");
1309   }
1310   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1311       RT.getUnqualifiedType(), Qual)));
1312 
1313   return false;
1314 }
1315 
1316 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1317   if (checkArgCount(S, TheCall, 1))
1318     return ExprError();
1319 
1320   // Compute __builtin_launder's parameter type from the argument.
1321   // The parameter type is:
1322   //  * The type of the argument if it's not an array or function type,
1323   //  Otherwise,
1324   //  * The decayed argument type.
1325   QualType ParamTy = [&]() {
1326     QualType ArgTy = TheCall->getArg(0)->getType();
1327     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1328       return S.Context.getPointerType(Ty->getElementType());
1329     if (ArgTy->isFunctionType()) {
1330       return S.Context.getPointerType(ArgTy);
1331     }
1332     return ArgTy;
1333   }();
1334 
1335   TheCall->setType(ParamTy);
1336 
1337   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1338     if (!ParamTy->isPointerType())
1339       return 0;
1340     if (ParamTy->isFunctionPointerType())
1341       return 1;
1342     if (ParamTy->isVoidPointerType())
1343       return 2;
1344     return llvm::Optional<unsigned>{};
1345   }();
1346   if (DiagSelect.hasValue()) {
1347     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1348         << DiagSelect.getValue() << TheCall->getSourceRange();
1349     return ExprError();
1350   }
1351 
1352   // We either have an incomplete class type, or we have a class template
1353   // whose instantiation has not been forced. Example:
1354   //
1355   //   template <class T> struct Foo { T value; };
1356   //   Foo<int> *p = nullptr;
1357   //   auto *d = __builtin_launder(p);
1358   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1359                             diag::err_incomplete_type))
1360     return ExprError();
1361 
1362   assert(ParamTy->getPointeeType()->isObjectType() &&
1363          "Unhandled non-object pointer case");
1364 
1365   InitializedEntity Entity =
1366       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1367   ExprResult Arg =
1368       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1369   if (Arg.isInvalid())
1370     return ExprError();
1371   TheCall->setArg(0, Arg.get());
1372 
1373   return TheCall;
1374 }
1375 
1376 // Emit an error and return true if the current architecture is not in the list
1377 // of supported architectures.
1378 static bool
1379 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1380                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1381   llvm::Triple::ArchType CurArch =
1382       S.getASTContext().getTargetInfo().getTriple().getArch();
1383   if (llvm::is_contained(SupportedArchs, CurArch))
1384     return false;
1385   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1386       << TheCall->getSourceRange();
1387   return true;
1388 }
1389 
1390 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1391                                  SourceLocation CallSiteLoc);
1392 
1393 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1394                                       CallExpr *TheCall) {
1395   switch (TI.getTriple().getArch()) {
1396   default:
1397     // Some builtins don't require additional checking, so just consider these
1398     // acceptable.
1399     return false;
1400   case llvm::Triple::arm:
1401   case llvm::Triple::armeb:
1402   case llvm::Triple::thumb:
1403   case llvm::Triple::thumbeb:
1404     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1405   case llvm::Triple::aarch64:
1406   case llvm::Triple::aarch64_32:
1407   case llvm::Triple::aarch64_be:
1408     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1409   case llvm::Triple::bpfeb:
1410   case llvm::Triple::bpfel:
1411     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1412   case llvm::Triple::hexagon:
1413     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::mips:
1415   case llvm::Triple::mipsel:
1416   case llvm::Triple::mips64:
1417   case llvm::Triple::mips64el:
1418     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1419   case llvm::Triple::systemz:
1420     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1421   case llvm::Triple::x86:
1422   case llvm::Triple::x86_64:
1423     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1424   case llvm::Triple::ppc:
1425   case llvm::Triple::ppc64:
1426   case llvm::Triple::ppc64le:
1427     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1428   case llvm::Triple::amdgcn:
1429     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1430   }
1431 }
1432 
1433 ExprResult
1434 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1435                                CallExpr *TheCall) {
1436   ExprResult TheCallResult(TheCall);
1437 
1438   // Find out if any arguments are required to be integer constant expressions.
1439   unsigned ICEArguments = 0;
1440   ASTContext::GetBuiltinTypeError Error;
1441   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1442   if (Error != ASTContext::GE_None)
1443     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1444 
1445   // If any arguments are required to be ICE's, check and diagnose.
1446   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1447     // Skip arguments not required to be ICE's.
1448     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1449 
1450     llvm::APSInt Result;
1451     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1452       return true;
1453     ICEArguments &= ~(1 << ArgNo);
1454   }
1455 
1456   switch (BuiltinID) {
1457   case Builtin::BI__builtin___CFStringMakeConstantString:
1458     assert(TheCall->getNumArgs() == 1 &&
1459            "Wrong # arguments to builtin CFStringMakeConstantString");
1460     if (CheckObjCString(TheCall->getArg(0)))
1461       return ExprError();
1462     break;
1463   case Builtin::BI__builtin_ms_va_start:
1464   case Builtin::BI__builtin_stdarg_start:
1465   case Builtin::BI__builtin_va_start:
1466     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__va_start: {
1470     switch (Context.getTargetInfo().getTriple().getArch()) {
1471     case llvm::Triple::aarch64:
1472     case llvm::Triple::arm:
1473     case llvm::Triple::thumb:
1474       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1475         return ExprError();
1476       break;
1477     default:
1478       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1479         return ExprError();
1480       break;
1481     }
1482     break;
1483   }
1484 
1485   // The acquire, release, and no fence variants are ARM and AArch64 only.
1486   case Builtin::BI_interlockedbittestandset_acq:
1487   case Builtin::BI_interlockedbittestandset_rel:
1488   case Builtin::BI_interlockedbittestandset_nf:
1489   case Builtin::BI_interlockedbittestandreset_acq:
1490   case Builtin::BI_interlockedbittestandreset_rel:
1491   case Builtin::BI_interlockedbittestandreset_nf:
1492     if (CheckBuiltinTargetSupport(
1493             *this, BuiltinID, TheCall,
1494             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1495       return ExprError();
1496     break;
1497 
1498   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1499   case Builtin::BI_bittest64:
1500   case Builtin::BI_bittestandcomplement64:
1501   case Builtin::BI_bittestandreset64:
1502   case Builtin::BI_bittestandset64:
1503   case Builtin::BI_interlockedbittestandreset64:
1504   case Builtin::BI_interlockedbittestandset64:
1505     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1506                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1507                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1508       return ExprError();
1509     break;
1510 
1511   case Builtin::BI__builtin_isgreater:
1512   case Builtin::BI__builtin_isgreaterequal:
1513   case Builtin::BI__builtin_isless:
1514   case Builtin::BI__builtin_islessequal:
1515   case Builtin::BI__builtin_islessgreater:
1516   case Builtin::BI__builtin_isunordered:
1517     if (SemaBuiltinUnorderedCompare(TheCall))
1518       return ExprError();
1519     break;
1520   case Builtin::BI__builtin_fpclassify:
1521     if (SemaBuiltinFPClassification(TheCall, 6))
1522       return ExprError();
1523     break;
1524   case Builtin::BI__builtin_isfinite:
1525   case Builtin::BI__builtin_isinf:
1526   case Builtin::BI__builtin_isinf_sign:
1527   case Builtin::BI__builtin_isnan:
1528   case Builtin::BI__builtin_isnormal:
1529   case Builtin::BI__builtin_signbit:
1530   case Builtin::BI__builtin_signbitf:
1531   case Builtin::BI__builtin_signbitl:
1532     if (SemaBuiltinFPClassification(TheCall, 1))
1533       return ExprError();
1534     break;
1535   case Builtin::BI__builtin_shufflevector:
1536     return SemaBuiltinShuffleVector(TheCall);
1537     // TheCall will be freed by the smart pointer here, but that's fine, since
1538     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1539   case Builtin::BI__builtin_prefetch:
1540     if (SemaBuiltinPrefetch(TheCall))
1541       return ExprError();
1542     break;
1543   case Builtin::BI__builtin_alloca_with_align:
1544     if (SemaBuiltinAllocaWithAlign(TheCall))
1545       return ExprError();
1546     LLVM_FALLTHROUGH;
1547   case Builtin::BI__builtin_alloca:
1548     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1549         << TheCall->getDirectCallee();
1550     break;
1551   case Builtin::BI__assume:
1552   case Builtin::BI__builtin_assume:
1553     if (SemaBuiltinAssume(TheCall))
1554       return ExprError();
1555     break;
1556   case Builtin::BI__builtin_assume_aligned:
1557     if (SemaBuiltinAssumeAligned(TheCall))
1558       return ExprError();
1559     break;
1560   case Builtin::BI__builtin_dynamic_object_size:
1561   case Builtin::BI__builtin_object_size:
1562     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1563       return ExprError();
1564     break;
1565   case Builtin::BI__builtin_longjmp:
1566     if (SemaBuiltinLongjmp(TheCall))
1567       return ExprError();
1568     break;
1569   case Builtin::BI__builtin_setjmp:
1570     if (SemaBuiltinSetjmp(TheCall))
1571       return ExprError();
1572     break;
1573   case Builtin::BI__builtin_classify_type:
1574     if (checkArgCount(*this, TheCall, 1)) return true;
1575     TheCall->setType(Context.IntTy);
1576     break;
1577   case Builtin::BI__builtin_complex:
1578     if (SemaBuiltinComplex(TheCall))
1579       return ExprError();
1580     break;
1581   case Builtin::BI__builtin_constant_p: {
1582     if (checkArgCount(*this, TheCall, 1)) return true;
1583     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1584     if (Arg.isInvalid()) return true;
1585     TheCall->setArg(0, Arg.get());
1586     TheCall->setType(Context.IntTy);
1587     break;
1588   }
1589   case Builtin::BI__builtin_launder:
1590     return SemaBuiltinLaunder(*this, TheCall);
1591   case Builtin::BI__sync_fetch_and_add:
1592   case Builtin::BI__sync_fetch_and_add_1:
1593   case Builtin::BI__sync_fetch_and_add_2:
1594   case Builtin::BI__sync_fetch_and_add_4:
1595   case Builtin::BI__sync_fetch_and_add_8:
1596   case Builtin::BI__sync_fetch_and_add_16:
1597   case Builtin::BI__sync_fetch_and_sub:
1598   case Builtin::BI__sync_fetch_and_sub_1:
1599   case Builtin::BI__sync_fetch_and_sub_2:
1600   case Builtin::BI__sync_fetch_and_sub_4:
1601   case Builtin::BI__sync_fetch_and_sub_8:
1602   case Builtin::BI__sync_fetch_and_sub_16:
1603   case Builtin::BI__sync_fetch_and_or:
1604   case Builtin::BI__sync_fetch_and_or_1:
1605   case Builtin::BI__sync_fetch_and_or_2:
1606   case Builtin::BI__sync_fetch_and_or_4:
1607   case Builtin::BI__sync_fetch_and_or_8:
1608   case Builtin::BI__sync_fetch_and_or_16:
1609   case Builtin::BI__sync_fetch_and_and:
1610   case Builtin::BI__sync_fetch_and_and_1:
1611   case Builtin::BI__sync_fetch_and_and_2:
1612   case Builtin::BI__sync_fetch_and_and_4:
1613   case Builtin::BI__sync_fetch_and_and_8:
1614   case Builtin::BI__sync_fetch_and_and_16:
1615   case Builtin::BI__sync_fetch_and_xor:
1616   case Builtin::BI__sync_fetch_and_xor_1:
1617   case Builtin::BI__sync_fetch_and_xor_2:
1618   case Builtin::BI__sync_fetch_and_xor_4:
1619   case Builtin::BI__sync_fetch_and_xor_8:
1620   case Builtin::BI__sync_fetch_and_xor_16:
1621   case Builtin::BI__sync_fetch_and_nand:
1622   case Builtin::BI__sync_fetch_and_nand_1:
1623   case Builtin::BI__sync_fetch_and_nand_2:
1624   case Builtin::BI__sync_fetch_and_nand_4:
1625   case Builtin::BI__sync_fetch_and_nand_8:
1626   case Builtin::BI__sync_fetch_and_nand_16:
1627   case Builtin::BI__sync_add_and_fetch:
1628   case Builtin::BI__sync_add_and_fetch_1:
1629   case Builtin::BI__sync_add_and_fetch_2:
1630   case Builtin::BI__sync_add_and_fetch_4:
1631   case Builtin::BI__sync_add_and_fetch_8:
1632   case Builtin::BI__sync_add_and_fetch_16:
1633   case Builtin::BI__sync_sub_and_fetch:
1634   case Builtin::BI__sync_sub_and_fetch_1:
1635   case Builtin::BI__sync_sub_and_fetch_2:
1636   case Builtin::BI__sync_sub_and_fetch_4:
1637   case Builtin::BI__sync_sub_and_fetch_8:
1638   case Builtin::BI__sync_sub_and_fetch_16:
1639   case Builtin::BI__sync_and_and_fetch:
1640   case Builtin::BI__sync_and_and_fetch_1:
1641   case Builtin::BI__sync_and_and_fetch_2:
1642   case Builtin::BI__sync_and_and_fetch_4:
1643   case Builtin::BI__sync_and_and_fetch_8:
1644   case Builtin::BI__sync_and_and_fetch_16:
1645   case Builtin::BI__sync_or_and_fetch:
1646   case Builtin::BI__sync_or_and_fetch_1:
1647   case Builtin::BI__sync_or_and_fetch_2:
1648   case Builtin::BI__sync_or_and_fetch_4:
1649   case Builtin::BI__sync_or_and_fetch_8:
1650   case Builtin::BI__sync_or_and_fetch_16:
1651   case Builtin::BI__sync_xor_and_fetch:
1652   case Builtin::BI__sync_xor_and_fetch_1:
1653   case Builtin::BI__sync_xor_and_fetch_2:
1654   case Builtin::BI__sync_xor_and_fetch_4:
1655   case Builtin::BI__sync_xor_and_fetch_8:
1656   case Builtin::BI__sync_xor_and_fetch_16:
1657   case Builtin::BI__sync_nand_and_fetch:
1658   case Builtin::BI__sync_nand_and_fetch_1:
1659   case Builtin::BI__sync_nand_and_fetch_2:
1660   case Builtin::BI__sync_nand_and_fetch_4:
1661   case Builtin::BI__sync_nand_and_fetch_8:
1662   case Builtin::BI__sync_nand_and_fetch_16:
1663   case Builtin::BI__sync_val_compare_and_swap:
1664   case Builtin::BI__sync_val_compare_and_swap_1:
1665   case Builtin::BI__sync_val_compare_and_swap_2:
1666   case Builtin::BI__sync_val_compare_and_swap_4:
1667   case Builtin::BI__sync_val_compare_and_swap_8:
1668   case Builtin::BI__sync_val_compare_and_swap_16:
1669   case Builtin::BI__sync_bool_compare_and_swap:
1670   case Builtin::BI__sync_bool_compare_and_swap_1:
1671   case Builtin::BI__sync_bool_compare_and_swap_2:
1672   case Builtin::BI__sync_bool_compare_and_swap_4:
1673   case Builtin::BI__sync_bool_compare_and_swap_8:
1674   case Builtin::BI__sync_bool_compare_and_swap_16:
1675   case Builtin::BI__sync_lock_test_and_set:
1676   case Builtin::BI__sync_lock_test_and_set_1:
1677   case Builtin::BI__sync_lock_test_and_set_2:
1678   case Builtin::BI__sync_lock_test_and_set_4:
1679   case Builtin::BI__sync_lock_test_and_set_8:
1680   case Builtin::BI__sync_lock_test_and_set_16:
1681   case Builtin::BI__sync_lock_release:
1682   case Builtin::BI__sync_lock_release_1:
1683   case Builtin::BI__sync_lock_release_2:
1684   case Builtin::BI__sync_lock_release_4:
1685   case Builtin::BI__sync_lock_release_8:
1686   case Builtin::BI__sync_lock_release_16:
1687   case Builtin::BI__sync_swap:
1688   case Builtin::BI__sync_swap_1:
1689   case Builtin::BI__sync_swap_2:
1690   case Builtin::BI__sync_swap_4:
1691   case Builtin::BI__sync_swap_8:
1692   case Builtin::BI__sync_swap_16:
1693     return SemaBuiltinAtomicOverloaded(TheCallResult);
1694   case Builtin::BI__sync_synchronize:
1695     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1696         << TheCall->getCallee()->getSourceRange();
1697     break;
1698   case Builtin::BI__builtin_nontemporal_load:
1699   case Builtin::BI__builtin_nontemporal_store:
1700     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1701   case Builtin::BI__builtin_memcpy_inline: {
1702     clang::Expr *SizeOp = TheCall->getArg(2);
1703     // We warn about copying to or from `nullptr` pointers when `size` is
1704     // greater than 0. When `size` is value dependent we cannot evaluate its
1705     // value so we bail out.
1706     if (SizeOp->isValueDependent())
1707       break;
1708     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1709       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1710       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1711     }
1712     break;
1713   }
1714 #define BUILTIN(ID, TYPE, ATTRS)
1715 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1716   case Builtin::BI##ID: \
1717     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1718 #include "clang/Basic/Builtins.def"
1719   case Builtin::BI__annotation:
1720     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1721       return ExprError();
1722     break;
1723   case Builtin::BI__builtin_annotation:
1724     if (SemaBuiltinAnnotation(*this, TheCall))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_addressof:
1728     if (SemaBuiltinAddressof(*this, TheCall))
1729       return ExprError();
1730     break;
1731   case Builtin::BI__builtin_is_aligned:
1732   case Builtin::BI__builtin_align_up:
1733   case Builtin::BI__builtin_align_down:
1734     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_add_overflow:
1738   case Builtin::BI__builtin_sub_overflow:
1739   case Builtin::BI__builtin_mul_overflow:
1740     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1741       return ExprError();
1742     break;
1743   case Builtin::BI__builtin_operator_new:
1744   case Builtin::BI__builtin_operator_delete: {
1745     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1746     ExprResult Res =
1747         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1748     if (Res.isInvalid())
1749       CorrectDelayedTyposInExpr(TheCallResult.get());
1750     return Res;
1751   }
1752   case Builtin::BI__builtin_dump_struct: {
1753     // We first want to ensure we are called with 2 arguments
1754     if (checkArgCount(*this, TheCall, 2))
1755       return ExprError();
1756     // Ensure that the first argument is of type 'struct XX *'
1757     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1758     const QualType PtrArgType = PtrArg->getType();
1759     if (!PtrArgType->isPointerType() ||
1760         !PtrArgType->getPointeeType()->isRecordType()) {
1761       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1762           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1763           << "structure pointer";
1764       return ExprError();
1765     }
1766 
1767     // Ensure that the second argument is of type 'FunctionType'
1768     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1769     const QualType FnPtrArgType = FnPtrArg->getType();
1770     if (!FnPtrArgType->isPointerType()) {
1771       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1773           << FnPtrArgType << "'int (*)(const char *, ...)'";
1774       return ExprError();
1775     }
1776 
1777     const auto *FuncType =
1778         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1779 
1780     if (!FuncType) {
1781       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1782           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1783           << FnPtrArgType << "'int (*)(const char *, ...)'";
1784       return ExprError();
1785     }
1786 
1787     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1788       if (!FT->getNumParams()) {
1789         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1790             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1791             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1792         return ExprError();
1793       }
1794       QualType PT = FT->getParamType(0);
1795       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1796           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1797           !PT->getPointeeType().isConstQualified()) {
1798         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1799             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1800             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1801         return ExprError();
1802       }
1803     }
1804 
1805     TheCall->setType(Context.IntTy);
1806     break;
1807   }
1808   case Builtin::BI__builtin_expect_with_probability: {
1809     // We first want to ensure we are called with 3 arguments
1810     if (checkArgCount(*this, TheCall, 3))
1811       return ExprError();
1812     // then check probability is constant float in range [0.0, 1.0]
1813     const Expr *ProbArg = TheCall->getArg(2);
1814     SmallVector<PartialDiagnosticAt, 8> Notes;
1815     Expr::EvalResult Eval;
1816     Eval.Diag = &Notes;
1817     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1818         !Eval.Val.isFloat()) {
1819       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1820           << ProbArg->getSourceRange();
1821       for (const PartialDiagnosticAt &PDiag : Notes)
1822         Diag(PDiag.first, PDiag.second);
1823       return ExprError();
1824     }
1825     llvm::APFloat Probability = Eval.Val.getFloat();
1826     bool LoseInfo = false;
1827     Probability.convert(llvm::APFloat::IEEEdouble(),
1828                         llvm::RoundingMode::Dynamic, &LoseInfo);
1829     if (!(Probability >= llvm::APFloat(0.0) &&
1830           Probability <= llvm::APFloat(1.0))) {
1831       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1832           << ProbArg->getSourceRange();
1833       return ExprError();
1834     }
1835     break;
1836   }
1837   case Builtin::BI__builtin_preserve_access_index:
1838     if (SemaBuiltinPreserveAI(*this, TheCall))
1839       return ExprError();
1840     break;
1841   case Builtin::BI__builtin_call_with_static_chain:
1842     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1843       return ExprError();
1844     break;
1845   case Builtin::BI__exception_code:
1846   case Builtin::BI_exception_code:
1847     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1848                                  diag::err_seh___except_block))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__exception_info:
1852   case Builtin::BI_exception_info:
1853     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1854                                  diag::err_seh___except_filter))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__GetExceptionInfo:
1858     if (checkArgCount(*this, TheCall, 1))
1859       return ExprError();
1860 
1861     if (CheckCXXThrowOperand(
1862             TheCall->getBeginLoc(),
1863             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1864             TheCall))
1865       return ExprError();
1866 
1867     TheCall->setType(Context.VoidPtrTy);
1868     break;
1869   // OpenCL v2.0, s6.13.16 - Pipe functions
1870   case Builtin::BIread_pipe:
1871   case Builtin::BIwrite_pipe:
1872     // Since those two functions are declared with var args, we need a semantic
1873     // check for the argument.
1874     if (SemaBuiltinRWPipe(*this, TheCall))
1875       return ExprError();
1876     break;
1877   case Builtin::BIreserve_read_pipe:
1878   case Builtin::BIreserve_write_pipe:
1879   case Builtin::BIwork_group_reserve_read_pipe:
1880   case Builtin::BIwork_group_reserve_write_pipe:
1881     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1882       return ExprError();
1883     break;
1884   case Builtin::BIsub_group_reserve_read_pipe:
1885   case Builtin::BIsub_group_reserve_write_pipe:
1886     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1887         SemaBuiltinReserveRWPipe(*this, TheCall))
1888       return ExprError();
1889     break;
1890   case Builtin::BIcommit_read_pipe:
1891   case Builtin::BIcommit_write_pipe:
1892   case Builtin::BIwork_group_commit_read_pipe:
1893   case Builtin::BIwork_group_commit_write_pipe:
1894     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1895       return ExprError();
1896     break;
1897   case Builtin::BIsub_group_commit_read_pipe:
1898   case Builtin::BIsub_group_commit_write_pipe:
1899     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1900         SemaBuiltinCommitRWPipe(*this, TheCall))
1901       return ExprError();
1902     break;
1903   case Builtin::BIget_pipe_num_packets:
1904   case Builtin::BIget_pipe_max_packets:
1905     if (SemaBuiltinPipePackets(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIto_global:
1909   case Builtin::BIto_local:
1910   case Builtin::BIto_private:
1911     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1912       return ExprError();
1913     break;
1914   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1915   case Builtin::BIenqueue_kernel:
1916     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1917       return ExprError();
1918     break;
1919   case Builtin::BIget_kernel_work_group_size:
1920   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1921     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1925   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1926     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BI__builtin_os_log_format:
1930     Cleanup.setExprNeedsCleanups(true);
1931     LLVM_FALLTHROUGH;
1932   case Builtin::BI__builtin_os_log_format_buffer_size:
1933     if (SemaBuiltinOSLogFormat(TheCall))
1934       return ExprError();
1935     break;
1936   case Builtin::BI__builtin_frame_address:
1937   case Builtin::BI__builtin_return_address: {
1938     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1939       return ExprError();
1940 
1941     // -Wframe-address warning if non-zero passed to builtin
1942     // return/frame address.
1943     Expr::EvalResult Result;
1944     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1945         Result.Val.getInt() != 0)
1946       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1947           << ((BuiltinID == Builtin::BI__builtin_return_address)
1948                   ? "__builtin_return_address"
1949                   : "__builtin_frame_address")
1950           << TheCall->getSourceRange();
1951     break;
1952   }
1953 
1954   case Builtin::BI__builtin_matrix_transpose:
1955     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1956 
1957   case Builtin::BI__builtin_matrix_column_major_load:
1958     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1959 
1960   case Builtin::BI__builtin_matrix_column_major_store:
1961     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1962   }
1963 
1964   // Since the target specific builtins for each arch overlap, only check those
1965   // of the arch we are compiling for.
1966   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1967     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1968       assert(Context.getAuxTargetInfo() &&
1969              "Aux Target Builtin, but not an aux target?");
1970 
1971       if (CheckTSBuiltinFunctionCall(
1972               *Context.getAuxTargetInfo(),
1973               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1974         return ExprError();
1975     } else {
1976       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1977                                      TheCall))
1978         return ExprError();
1979     }
1980   }
1981 
1982   return TheCallResult;
1983 }
1984 
1985 // Get the valid immediate range for the specified NEON type code.
1986 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1987   NeonTypeFlags Type(t);
1988   int IsQuad = ForceQuad ? true : Type.isQuad();
1989   switch (Type.getEltType()) {
1990   case NeonTypeFlags::Int8:
1991   case NeonTypeFlags::Poly8:
1992     return shift ? 7 : (8 << IsQuad) - 1;
1993   case NeonTypeFlags::Int16:
1994   case NeonTypeFlags::Poly16:
1995     return shift ? 15 : (4 << IsQuad) - 1;
1996   case NeonTypeFlags::Int32:
1997     return shift ? 31 : (2 << IsQuad) - 1;
1998   case NeonTypeFlags::Int64:
1999   case NeonTypeFlags::Poly64:
2000     return shift ? 63 : (1 << IsQuad) - 1;
2001   case NeonTypeFlags::Poly128:
2002     return shift ? 127 : (1 << IsQuad) - 1;
2003   case NeonTypeFlags::Float16:
2004     assert(!shift && "cannot shift float types!");
2005     return (4 << IsQuad) - 1;
2006   case NeonTypeFlags::Float32:
2007     assert(!shift && "cannot shift float types!");
2008     return (2 << IsQuad) - 1;
2009   case NeonTypeFlags::Float64:
2010     assert(!shift && "cannot shift float types!");
2011     return (1 << IsQuad) - 1;
2012   case NeonTypeFlags::BFloat16:
2013     assert(!shift && "cannot shift float types!");
2014     return (4 << IsQuad) - 1;
2015   }
2016   llvm_unreachable("Invalid NeonTypeFlag!");
2017 }
2018 
2019 /// getNeonEltType - Return the QualType corresponding to the elements of
2020 /// the vector type specified by the NeonTypeFlags.  This is used to check
2021 /// the pointer arguments for Neon load/store intrinsics.
2022 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2023                                bool IsPolyUnsigned, bool IsInt64Long) {
2024   switch (Flags.getEltType()) {
2025   case NeonTypeFlags::Int8:
2026     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2027   case NeonTypeFlags::Int16:
2028     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2029   case NeonTypeFlags::Int32:
2030     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2031   case NeonTypeFlags::Int64:
2032     if (IsInt64Long)
2033       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2034     else
2035       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2036                                 : Context.LongLongTy;
2037   case NeonTypeFlags::Poly8:
2038     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2039   case NeonTypeFlags::Poly16:
2040     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2041   case NeonTypeFlags::Poly64:
2042     if (IsInt64Long)
2043       return Context.UnsignedLongTy;
2044     else
2045       return Context.UnsignedLongLongTy;
2046   case NeonTypeFlags::Poly128:
2047     break;
2048   case NeonTypeFlags::Float16:
2049     return Context.HalfTy;
2050   case NeonTypeFlags::Float32:
2051     return Context.FloatTy;
2052   case NeonTypeFlags::Float64:
2053     return Context.DoubleTy;
2054   case NeonTypeFlags::BFloat16:
2055     return Context.BFloat16Ty;
2056   }
2057   llvm_unreachable("Invalid NeonTypeFlag!");
2058 }
2059 
2060 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2061   // Range check SVE intrinsics that take immediate values.
2062   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2063 
2064   switch (BuiltinID) {
2065   default:
2066     return false;
2067 #define GET_SVE_IMMEDIATE_CHECK
2068 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2069 #undef GET_SVE_IMMEDIATE_CHECK
2070   }
2071 
2072   // Perform all the immediate checks for this builtin call.
2073   bool HasError = false;
2074   for (auto &I : ImmChecks) {
2075     int ArgNum, CheckTy, ElementSizeInBits;
2076     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2077 
2078     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2079 
2080     // Function that checks whether the operand (ArgNum) is an immediate
2081     // that is one of the predefined values.
2082     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2083                                    int ErrDiag) -> bool {
2084       // We can't check the value of a dependent argument.
2085       Expr *Arg = TheCall->getArg(ArgNum);
2086       if (Arg->isTypeDependent() || Arg->isValueDependent())
2087         return false;
2088 
2089       // Check constant-ness first.
2090       llvm::APSInt Imm;
2091       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2092         return true;
2093 
2094       if (!CheckImm(Imm.getSExtValue()))
2095         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2096       return false;
2097     };
2098 
2099     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2100     case SVETypeFlags::ImmCheck0_31:
2101       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2102         HasError = true;
2103       break;
2104     case SVETypeFlags::ImmCheck0_13:
2105       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2106         HasError = true;
2107       break;
2108     case SVETypeFlags::ImmCheck1_16:
2109       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2110         HasError = true;
2111       break;
2112     case SVETypeFlags::ImmCheck0_7:
2113       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2114         HasError = true;
2115       break;
2116     case SVETypeFlags::ImmCheckExtract:
2117       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2118                                       (2048 / ElementSizeInBits) - 1))
2119         HasError = true;
2120       break;
2121     case SVETypeFlags::ImmCheckShiftRight:
2122       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2123         HasError = true;
2124       break;
2125     case SVETypeFlags::ImmCheckShiftRightNarrow:
2126       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2127                                       ElementSizeInBits / 2))
2128         HasError = true;
2129       break;
2130     case SVETypeFlags::ImmCheckShiftLeft:
2131       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2132                                       ElementSizeInBits - 1))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheckLaneIndex:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2137                                       (128 / (1 * ElementSizeInBits)) - 1))
2138         HasError = true;
2139       break;
2140     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2141       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2142                                       (128 / (2 * ElementSizeInBits)) - 1))
2143         HasError = true;
2144       break;
2145     case SVETypeFlags::ImmCheckLaneIndexDot:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2147                                       (128 / (4 * ElementSizeInBits)) - 1))
2148         HasError = true;
2149       break;
2150     case SVETypeFlags::ImmCheckComplexRot90_270:
2151       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2152                               diag::err_rotation_argument_to_cadd))
2153         HasError = true;
2154       break;
2155     case SVETypeFlags::ImmCheckComplexRotAll90:
2156       if (CheckImmediateInSet(
2157               [](int64_t V) {
2158                 return V == 0 || V == 90 || V == 180 || V == 270;
2159               },
2160               diag::err_rotation_argument_to_cmla))
2161         HasError = true;
2162       break;
2163     case SVETypeFlags::ImmCheck0_1:
2164       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheck0_2:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheck0_3:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2173         HasError = true;
2174       break;
2175     }
2176   }
2177 
2178   return HasError;
2179 }
2180 
2181 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2182                                         unsigned BuiltinID, CallExpr *TheCall) {
2183   llvm::APSInt Result;
2184   uint64_t mask = 0;
2185   unsigned TV = 0;
2186   int PtrArgNum = -1;
2187   bool HasConstPtr = false;
2188   switch (BuiltinID) {
2189 #define GET_NEON_OVERLOAD_CHECK
2190 #include "clang/Basic/arm_neon.inc"
2191 #include "clang/Basic/arm_fp16.inc"
2192 #undef GET_NEON_OVERLOAD_CHECK
2193   }
2194 
2195   // For NEON intrinsics which are overloaded on vector element type, validate
2196   // the immediate which specifies which variant to emit.
2197   unsigned ImmArg = TheCall->getNumArgs()-1;
2198   if (mask) {
2199     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2200       return true;
2201 
2202     TV = Result.getLimitedValue(64);
2203     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2204       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2205              << TheCall->getArg(ImmArg)->getSourceRange();
2206   }
2207 
2208   if (PtrArgNum >= 0) {
2209     // Check that pointer arguments have the specified type.
2210     Expr *Arg = TheCall->getArg(PtrArgNum);
2211     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2212       Arg = ICE->getSubExpr();
2213     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2214     QualType RHSTy = RHS.get()->getType();
2215 
2216     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2217     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2218                           Arch == llvm::Triple::aarch64_32 ||
2219                           Arch == llvm::Triple::aarch64_be;
2220     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2221     QualType EltTy =
2222         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2223     if (HasConstPtr)
2224       EltTy = EltTy.withConst();
2225     QualType LHSTy = Context.getPointerType(EltTy);
2226     AssignConvertType ConvTy;
2227     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2228     if (RHS.isInvalid())
2229       return true;
2230     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2231                                  RHS.get(), AA_Assigning))
2232       return true;
2233   }
2234 
2235   // For NEON intrinsics which take an immediate value as part of the
2236   // instruction, range check them here.
2237   unsigned i = 0, l = 0, u = 0;
2238   switch (BuiltinID) {
2239   default:
2240     return false;
2241   #define GET_NEON_IMMEDIATE_CHECK
2242   #include "clang/Basic/arm_neon.inc"
2243   #include "clang/Basic/arm_fp16.inc"
2244   #undef GET_NEON_IMMEDIATE_CHECK
2245   }
2246 
2247   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2248 }
2249 
2250 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2251   switch (BuiltinID) {
2252   default:
2253     return false;
2254   #include "clang/Basic/arm_mve_builtin_sema.inc"
2255   }
2256 }
2257 
2258 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2259                                        CallExpr *TheCall) {
2260   bool Err = false;
2261   switch (BuiltinID) {
2262   default:
2263     return false;
2264 #include "clang/Basic/arm_cde_builtin_sema.inc"
2265   }
2266 
2267   if (Err)
2268     return true;
2269 
2270   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2271 }
2272 
2273 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2274                                         const Expr *CoprocArg, bool WantCDE) {
2275   if (isConstantEvaluated())
2276     return false;
2277 
2278   // We can't check the value of a dependent argument.
2279   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2280     return false;
2281 
2282   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2283   int64_t CoprocNo = CoprocNoAP.getExtValue();
2284   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2285 
2286   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2287   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2288 
2289   if (IsCDECoproc != WantCDE)
2290     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2291            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2292 
2293   return false;
2294 }
2295 
2296 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2297                                         unsigned MaxWidth) {
2298   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2299           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2300           BuiltinID == ARM::BI__builtin_arm_strex ||
2301           BuiltinID == ARM::BI__builtin_arm_stlex ||
2302           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2303           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2304           BuiltinID == AArch64::BI__builtin_arm_strex ||
2305           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2306          "unexpected ARM builtin");
2307   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2308                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2309                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2310                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2311 
2312   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2313 
2314   // Ensure that we have the proper number of arguments.
2315   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2316     return true;
2317 
2318   // Inspect the pointer argument of the atomic builtin.  This should always be
2319   // a pointer type, whose element is an integral scalar or pointer type.
2320   // Because it is a pointer type, we don't have to worry about any implicit
2321   // casts here.
2322   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2323   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2324   if (PointerArgRes.isInvalid())
2325     return true;
2326   PointerArg = PointerArgRes.get();
2327 
2328   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2329   if (!pointerType) {
2330     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2331         << PointerArg->getType() << PointerArg->getSourceRange();
2332     return true;
2333   }
2334 
2335   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2336   // task is to insert the appropriate casts into the AST. First work out just
2337   // what the appropriate type is.
2338   QualType ValType = pointerType->getPointeeType();
2339   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2340   if (IsLdrex)
2341     AddrType.addConst();
2342 
2343   // Issue a warning if the cast is dodgy.
2344   CastKind CastNeeded = CK_NoOp;
2345   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2346     CastNeeded = CK_BitCast;
2347     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2348         << PointerArg->getType() << Context.getPointerType(AddrType)
2349         << AA_Passing << PointerArg->getSourceRange();
2350   }
2351 
2352   // Finally, do the cast and replace the argument with the corrected version.
2353   AddrType = Context.getPointerType(AddrType);
2354   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2355   if (PointerArgRes.isInvalid())
2356     return true;
2357   PointerArg = PointerArgRes.get();
2358 
2359   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2360 
2361   // In general, we allow ints, floats and pointers to be loaded and stored.
2362   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2363       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2364     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2365         << PointerArg->getType() << PointerArg->getSourceRange();
2366     return true;
2367   }
2368 
2369   // But ARM doesn't have instructions to deal with 128-bit versions.
2370   if (Context.getTypeSize(ValType) > MaxWidth) {
2371     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2372     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2373         << PointerArg->getType() << PointerArg->getSourceRange();
2374     return true;
2375   }
2376 
2377   switch (ValType.getObjCLifetime()) {
2378   case Qualifiers::OCL_None:
2379   case Qualifiers::OCL_ExplicitNone:
2380     // okay
2381     break;
2382 
2383   case Qualifiers::OCL_Weak:
2384   case Qualifiers::OCL_Strong:
2385   case Qualifiers::OCL_Autoreleasing:
2386     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2387         << ValType << PointerArg->getSourceRange();
2388     return true;
2389   }
2390 
2391   if (IsLdrex) {
2392     TheCall->setType(ValType);
2393     return false;
2394   }
2395 
2396   // Initialize the argument to be stored.
2397   ExprResult ValArg = TheCall->getArg(0);
2398   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2399       Context, ValType, /*consume*/ false);
2400   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2401   if (ValArg.isInvalid())
2402     return true;
2403   TheCall->setArg(0, ValArg.get());
2404 
2405   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2406   // but the custom checker bypasses all default analysis.
2407   TheCall->setType(Context.IntTy);
2408   return false;
2409 }
2410 
2411 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2412                                        CallExpr *TheCall) {
2413   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2414       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2415       BuiltinID == ARM::BI__builtin_arm_strex ||
2416       BuiltinID == ARM::BI__builtin_arm_stlex) {
2417     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2418   }
2419 
2420   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2421     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2422       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2423   }
2424 
2425   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2426       BuiltinID == ARM::BI__builtin_arm_wsr64)
2427     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2428 
2429   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2430       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2431       BuiltinID == ARM::BI__builtin_arm_wsr ||
2432       BuiltinID == ARM::BI__builtin_arm_wsrp)
2433     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2434 
2435   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2436     return true;
2437   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2438     return true;
2439   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2440     return true;
2441 
2442   // For intrinsics which take an immediate value as part of the instruction,
2443   // range check them here.
2444   // FIXME: VFP Intrinsics should error if VFP not present.
2445   switch (BuiltinID) {
2446   default: return false;
2447   case ARM::BI__builtin_arm_ssat:
2448     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2449   case ARM::BI__builtin_arm_usat:
2450     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2451   case ARM::BI__builtin_arm_ssat16:
2452     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2453   case ARM::BI__builtin_arm_usat16:
2454     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2455   case ARM::BI__builtin_arm_vcvtr_f:
2456   case ARM::BI__builtin_arm_vcvtr_d:
2457     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2458   case ARM::BI__builtin_arm_dmb:
2459   case ARM::BI__builtin_arm_dsb:
2460   case ARM::BI__builtin_arm_isb:
2461   case ARM::BI__builtin_arm_dbg:
2462     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2463   case ARM::BI__builtin_arm_cdp:
2464   case ARM::BI__builtin_arm_cdp2:
2465   case ARM::BI__builtin_arm_mcr:
2466   case ARM::BI__builtin_arm_mcr2:
2467   case ARM::BI__builtin_arm_mrc:
2468   case ARM::BI__builtin_arm_mrc2:
2469   case ARM::BI__builtin_arm_mcrr:
2470   case ARM::BI__builtin_arm_mcrr2:
2471   case ARM::BI__builtin_arm_mrrc:
2472   case ARM::BI__builtin_arm_mrrc2:
2473   case ARM::BI__builtin_arm_ldc:
2474   case ARM::BI__builtin_arm_ldcl:
2475   case ARM::BI__builtin_arm_ldc2:
2476   case ARM::BI__builtin_arm_ldc2l:
2477   case ARM::BI__builtin_arm_stc:
2478   case ARM::BI__builtin_arm_stcl:
2479   case ARM::BI__builtin_arm_stc2:
2480   case ARM::BI__builtin_arm_stc2l:
2481     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2482            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2483                                         /*WantCDE*/ false);
2484   }
2485 }
2486 
2487 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2488                                            unsigned BuiltinID,
2489                                            CallExpr *TheCall) {
2490   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2491       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2492       BuiltinID == AArch64::BI__builtin_arm_strex ||
2493       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2494     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2495   }
2496 
2497   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2498     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2499       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2500       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2501       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2502   }
2503 
2504   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2505       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2506     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2507 
2508   // Memory Tagging Extensions (MTE) Intrinsics
2509   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2510       BuiltinID == AArch64::BI__builtin_arm_addg ||
2511       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2512       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2513       BuiltinID == AArch64::BI__builtin_arm_stg ||
2514       BuiltinID == AArch64::BI__builtin_arm_subp) {
2515     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2516   }
2517 
2518   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2519       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2520       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2521       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2522     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2523 
2524   // Only check the valid encoding range. Any constant in this range would be
2525   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2526   // an exception for incorrect registers. This matches MSVC behavior.
2527   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2528       BuiltinID == AArch64::BI_WriteStatusReg)
2529     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2530 
2531   if (BuiltinID == AArch64::BI__getReg)
2532     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2533 
2534   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2535     return true;
2536 
2537   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2538     return true;
2539 
2540   // For intrinsics which take an immediate value as part of the instruction,
2541   // range check them here.
2542   unsigned i = 0, l = 0, u = 0;
2543   switch (BuiltinID) {
2544   default: return false;
2545   case AArch64::BI__builtin_arm_dmb:
2546   case AArch64::BI__builtin_arm_dsb:
2547   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2548   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2549   }
2550 
2551   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2552 }
2553 
2554 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2555   if (Arg->getType()->getAsPlaceholderType())
2556     return false;
2557 
2558   // The first argument needs to be a record field access.
2559   // If it is an array element access, we delay decision
2560   // to BPF backend to check whether the access is a
2561   // field access or not.
2562   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2563           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2564           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2565 }
2566 
2567 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2568                             QualType VectorTy, QualType EltTy) {
2569   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2570   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2571     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2572         << Call->getSourceRange() << VectorEltTy << EltTy;
2573     return false;
2574   }
2575   return true;
2576 }
2577 
2578 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2579   QualType ArgType = Arg->getType();
2580   if (ArgType->getAsPlaceholderType())
2581     return false;
2582 
2583   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2584   // format:
2585   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2586   //   2. <type> var;
2587   //      __builtin_preserve_type_info(var, flag);
2588   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2589       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2590     return false;
2591 
2592   // Typedef type.
2593   if (ArgType->getAs<TypedefType>())
2594     return true;
2595 
2596   // Record type or Enum type.
2597   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2598   if (const auto *RT = Ty->getAs<RecordType>()) {
2599     if (!RT->getDecl()->getDeclName().isEmpty())
2600       return true;
2601   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2602     if (!ET->getDecl()->getDeclName().isEmpty())
2603       return true;
2604   }
2605 
2606   return false;
2607 }
2608 
2609 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2610   QualType ArgType = Arg->getType();
2611   if (ArgType->getAsPlaceholderType())
2612     return false;
2613 
2614   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2615   // format:
2616   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2617   //                                 flag);
2618   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2619   if (!UO)
2620     return false;
2621 
2622   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2623   if (!CE || CE->getCastKind() != CK_IntegralToPointer)
2624     return false;
2625 
2626   // The integer must be from an EnumConstantDecl.
2627   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2628   if (!DR)
2629     return false;
2630 
2631   const EnumConstantDecl *Enumerator =
2632       dyn_cast<EnumConstantDecl>(DR->getDecl());
2633   if (!Enumerator)
2634     return false;
2635 
2636   // The type must be EnumType.
2637   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2638   const auto *ET = Ty->getAs<EnumType>();
2639   if (!ET)
2640     return false;
2641 
2642   // The enum value must be supported.
2643   for (auto *EDI : ET->getDecl()->enumerators()) {
2644     if (EDI == Enumerator)
2645       return true;
2646   }
2647 
2648   return false;
2649 }
2650 
2651 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2652                                        CallExpr *TheCall) {
2653   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2654           BuiltinID == BPF::BI__builtin_btf_type_id ||
2655           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2656           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2657          "unexpected BPF builtin");
2658 
2659   if (checkArgCount(*this, TheCall, 2))
2660     return true;
2661 
2662   // The second argument needs to be a constant int
2663   Expr *Arg = TheCall->getArg(1);
2664   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2665   diag::kind kind;
2666   if (!Value) {
2667     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2668       kind = diag::err_preserve_field_info_not_const;
2669     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2670       kind = diag::err_btf_type_id_not_const;
2671     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2672       kind = diag::err_preserve_type_info_not_const;
2673     else
2674       kind = diag::err_preserve_enum_value_not_const;
2675     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2676     return true;
2677   }
2678 
2679   // The first argument
2680   Arg = TheCall->getArg(0);
2681   bool InvalidArg = false;
2682   bool ReturnUnsignedInt = true;
2683   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2684     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2685       InvalidArg = true;
2686       kind = diag::err_preserve_field_info_not_field;
2687     }
2688   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2689     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2690       InvalidArg = true;
2691       kind = diag::err_preserve_type_info_invalid;
2692     }
2693   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2694     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2695       InvalidArg = true;
2696       kind = diag::err_preserve_enum_value_invalid;
2697     }
2698     ReturnUnsignedInt = false;
2699   }
2700 
2701   if (InvalidArg) {
2702     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2703     return true;
2704   }
2705 
2706   if (ReturnUnsignedInt)
2707     TheCall->setType(Context.UnsignedIntTy);
2708   else
2709     TheCall->setType(Context.UnsignedLongTy);
2710   return false;
2711 }
2712 
2713 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2714   struct ArgInfo {
2715     uint8_t OpNum;
2716     bool IsSigned;
2717     uint8_t BitWidth;
2718     uint8_t Align;
2719   };
2720   struct BuiltinInfo {
2721     unsigned BuiltinID;
2722     ArgInfo Infos[2];
2723   };
2724 
2725   static BuiltinInfo Infos[] = {
2726     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2727     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2728     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2729     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2730     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2731     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2732     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2733     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2734     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2735     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2736     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2737 
2738     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2741     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2742     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2743     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2744     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2746     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2747     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2749 
2750     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2802                                                       {{ 1, false, 6,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2810                                                       {{ 1, false, 5,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2817                                                        { 2, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2819                                                        { 2, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2821                                                        { 3, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2823                                                        { 3, false, 6,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2840                                                       {{ 2, false, 4,  0 },
2841                                                        { 3, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2843                                                       {{ 2, false, 4,  0 },
2844                                                        { 3, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2846                                                       {{ 2, false, 4,  0 },
2847                                                        { 3, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2849                                                       {{ 2, false, 4,  0 },
2850                                                        { 3, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2862                                                        { 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2864                                                        { 2, false, 6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2874                                                       {{ 1, false, 4,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2877                                                       {{ 1, false, 4,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2898                                                       {{ 3, false, 1,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2903                                                       {{ 3, false, 1,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2908                                                       {{ 3, false, 1,  0 }} },
2909   };
2910 
2911   // Use a dynamically initialized static to sort the table exactly once on
2912   // first run.
2913   static const bool SortOnce =
2914       (llvm::sort(Infos,
2915                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2916                    return LHS.BuiltinID < RHS.BuiltinID;
2917                  }),
2918        true);
2919   (void)SortOnce;
2920 
2921   const BuiltinInfo *F = llvm::partition_point(
2922       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2923   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2924     return false;
2925 
2926   bool Error = false;
2927 
2928   for (const ArgInfo &A : F->Infos) {
2929     // Ignore empty ArgInfo elements.
2930     if (A.BitWidth == 0)
2931       continue;
2932 
2933     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2934     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2935     if (!A.Align) {
2936       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2937     } else {
2938       unsigned M = 1 << A.Align;
2939       Min *= M;
2940       Max *= M;
2941       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2942                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2943     }
2944   }
2945   return Error;
2946 }
2947 
2948 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2949                                            CallExpr *TheCall) {
2950   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2951 }
2952 
2953 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2954                                         unsigned BuiltinID, CallExpr *TheCall) {
2955   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2956          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2957 }
2958 
2959 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2960                                CallExpr *TheCall) {
2961 
2962   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2963       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2964     if (!TI.hasFeature("dsp"))
2965       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2966   }
2967 
2968   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2969       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2970     if (!TI.hasFeature("dspr2"))
2971       return Diag(TheCall->getBeginLoc(),
2972                   diag::err_mips_builtin_requires_dspr2);
2973   }
2974 
2975   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2976       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2977     if (!TI.hasFeature("msa"))
2978       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2979   }
2980 
2981   return false;
2982 }
2983 
2984 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2985 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2986 // ordering for DSP is unspecified. MSA is ordered by the data format used
2987 // by the underlying instruction i.e., df/m, df/n and then by size.
2988 //
2989 // FIXME: The size tests here should instead be tablegen'd along with the
2990 //        definitions from include/clang/Basic/BuiltinsMips.def.
2991 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2992 //        be too.
2993 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2994   unsigned i = 0, l = 0, u = 0, m = 0;
2995   switch (BuiltinID) {
2996   default: return false;
2997   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2998   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2999   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3000   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3001   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3002   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3003   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3004   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3005   // df/m field.
3006   // These intrinsics take an unsigned 3 bit immediate.
3007   case Mips::BI__builtin_msa_bclri_b:
3008   case Mips::BI__builtin_msa_bnegi_b:
3009   case Mips::BI__builtin_msa_bseti_b:
3010   case Mips::BI__builtin_msa_sat_s_b:
3011   case Mips::BI__builtin_msa_sat_u_b:
3012   case Mips::BI__builtin_msa_slli_b:
3013   case Mips::BI__builtin_msa_srai_b:
3014   case Mips::BI__builtin_msa_srari_b:
3015   case Mips::BI__builtin_msa_srli_b:
3016   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3017   case Mips::BI__builtin_msa_binsli_b:
3018   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3019   // These intrinsics take an unsigned 4 bit immediate.
3020   case Mips::BI__builtin_msa_bclri_h:
3021   case Mips::BI__builtin_msa_bnegi_h:
3022   case Mips::BI__builtin_msa_bseti_h:
3023   case Mips::BI__builtin_msa_sat_s_h:
3024   case Mips::BI__builtin_msa_sat_u_h:
3025   case Mips::BI__builtin_msa_slli_h:
3026   case Mips::BI__builtin_msa_srai_h:
3027   case Mips::BI__builtin_msa_srari_h:
3028   case Mips::BI__builtin_msa_srli_h:
3029   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3030   case Mips::BI__builtin_msa_binsli_h:
3031   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3032   // These intrinsics take an unsigned 5 bit immediate.
3033   // The first block of intrinsics actually have an unsigned 5 bit field,
3034   // not a df/n field.
3035   case Mips::BI__builtin_msa_cfcmsa:
3036   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3037   case Mips::BI__builtin_msa_clei_u_b:
3038   case Mips::BI__builtin_msa_clei_u_h:
3039   case Mips::BI__builtin_msa_clei_u_w:
3040   case Mips::BI__builtin_msa_clei_u_d:
3041   case Mips::BI__builtin_msa_clti_u_b:
3042   case Mips::BI__builtin_msa_clti_u_h:
3043   case Mips::BI__builtin_msa_clti_u_w:
3044   case Mips::BI__builtin_msa_clti_u_d:
3045   case Mips::BI__builtin_msa_maxi_u_b:
3046   case Mips::BI__builtin_msa_maxi_u_h:
3047   case Mips::BI__builtin_msa_maxi_u_w:
3048   case Mips::BI__builtin_msa_maxi_u_d:
3049   case Mips::BI__builtin_msa_mini_u_b:
3050   case Mips::BI__builtin_msa_mini_u_h:
3051   case Mips::BI__builtin_msa_mini_u_w:
3052   case Mips::BI__builtin_msa_mini_u_d:
3053   case Mips::BI__builtin_msa_addvi_b:
3054   case Mips::BI__builtin_msa_addvi_h:
3055   case Mips::BI__builtin_msa_addvi_w:
3056   case Mips::BI__builtin_msa_addvi_d:
3057   case Mips::BI__builtin_msa_bclri_w:
3058   case Mips::BI__builtin_msa_bnegi_w:
3059   case Mips::BI__builtin_msa_bseti_w:
3060   case Mips::BI__builtin_msa_sat_s_w:
3061   case Mips::BI__builtin_msa_sat_u_w:
3062   case Mips::BI__builtin_msa_slli_w:
3063   case Mips::BI__builtin_msa_srai_w:
3064   case Mips::BI__builtin_msa_srari_w:
3065   case Mips::BI__builtin_msa_srli_w:
3066   case Mips::BI__builtin_msa_srlri_w:
3067   case Mips::BI__builtin_msa_subvi_b:
3068   case Mips::BI__builtin_msa_subvi_h:
3069   case Mips::BI__builtin_msa_subvi_w:
3070   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3071   case Mips::BI__builtin_msa_binsli_w:
3072   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3073   // These intrinsics take an unsigned 6 bit immediate.
3074   case Mips::BI__builtin_msa_bclri_d:
3075   case Mips::BI__builtin_msa_bnegi_d:
3076   case Mips::BI__builtin_msa_bseti_d:
3077   case Mips::BI__builtin_msa_sat_s_d:
3078   case Mips::BI__builtin_msa_sat_u_d:
3079   case Mips::BI__builtin_msa_slli_d:
3080   case Mips::BI__builtin_msa_srai_d:
3081   case Mips::BI__builtin_msa_srari_d:
3082   case Mips::BI__builtin_msa_srli_d:
3083   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3084   case Mips::BI__builtin_msa_binsli_d:
3085   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3086   // These intrinsics take a signed 5 bit immediate.
3087   case Mips::BI__builtin_msa_ceqi_b:
3088   case Mips::BI__builtin_msa_ceqi_h:
3089   case Mips::BI__builtin_msa_ceqi_w:
3090   case Mips::BI__builtin_msa_ceqi_d:
3091   case Mips::BI__builtin_msa_clti_s_b:
3092   case Mips::BI__builtin_msa_clti_s_h:
3093   case Mips::BI__builtin_msa_clti_s_w:
3094   case Mips::BI__builtin_msa_clti_s_d:
3095   case Mips::BI__builtin_msa_clei_s_b:
3096   case Mips::BI__builtin_msa_clei_s_h:
3097   case Mips::BI__builtin_msa_clei_s_w:
3098   case Mips::BI__builtin_msa_clei_s_d:
3099   case Mips::BI__builtin_msa_maxi_s_b:
3100   case Mips::BI__builtin_msa_maxi_s_h:
3101   case Mips::BI__builtin_msa_maxi_s_w:
3102   case Mips::BI__builtin_msa_maxi_s_d:
3103   case Mips::BI__builtin_msa_mini_s_b:
3104   case Mips::BI__builtin_msa_mini_s_h:
3105   case Mips::BI__builtin_msa_mini_s_w:
3106   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3107   // These intrinsics take an unsigned 8 bit immediate.
3108   case Mips::BI__builtin_msa_andi_b:
3109   case Mips::BI__builtin_msa_nori_b:
3110   case Mips::BI__builtin_msa_ori_b:
3111   case Mips::BI__builtin_msa_shf_b:
3112   case Mips::BI__builtin_msa_shf_h:
3113   case Mips::BI__builtin_msa_shf_w:
3114   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3115   case Mips::BI__builtin_msa_bseli_b:
3116   case Mips::BI__builtin_msa_bmnzi_b:
3117   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3118   // df/n format
3119   // These intrinsics take an unsigned 4 bit immediate.
3120   case Mips::BI__builtin_msa_copy_s_b:
3121   case Mips::BI__builtin_msa_copy_u_b:
3122   case Mips::BI__builtin_msa_insve_b:
3123   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3124   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3125   // These intrinsics take an unsigned 3 bit immediate.
3126   case Mips::BI__builtin_msa_copy_s_h:
3127   case Mips::BI__builtin_msa_copy_u_h:
3128   case Mips::BI__builtin_msa_insve_h:
3129   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3130   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3131   // These intrinsics take an unsigned 2 bit immediate.
3132   case Mips::BI__builtin_msa_copy_s_w:
3133   case Mips::BI__builtin_msa_copy_u_w:
3134   case Mips::BI__builtin_msa_insve_w:
3135   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3136   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3137   // These intrinsics take an unsigned 1 bit immediate.
3138   case Mips::BI__builtin_msa_copy_s_d:
3139   case Mips::BI__builtin_msa_copy_u_d:
3140   case Mips::BI__builtin_msa_insve_d:
3141   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3142   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3143   // Memory offsets and immediate loads.
3144   // These intrinsics take a signed 10 bit immediate.
3145   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3146   case Mips::BI__builtin_msa_ldi_h:
3147   case Mips::BI__builtin_msa_ldi_w:
3148   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3149   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3150   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3151   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3152   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3153   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3154   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3155   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3156   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3157   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3158   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3159   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3160   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3161   }
3162 
3163   if (!m)
3164     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3165 
3166   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3167          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3168 }
3169 
3170 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3171                                        CallExpr *TheCall) {
3172   unsigned i = 0, l = 0, u = 0;
3173   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3174                       BuiltinID == PPC::BI__builtin_divdeu ||
3175                       BuiltinID == PPC::BI__builtin_bpermd;
3176   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3177   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3178                        BuiltinID == PPC::BI__builtin_divweu ||
3179                        BuiltinID == PPC::BI__builtin_divde ||
3180                        BuiltinID == PPC::BI__builtin_divdeu;
3181 
3182   if (Is64BitBltin && !IsTarget64Bit)
3183     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3184            << TheCall->getSourceRange();
3185 
3186   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3187       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3188     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3189            << TheCall->getSourceRange();
3190 
3191   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3192     if (!TI.hasFeature("vsx"))
3193       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3194              << TheCall->getSourceRange();
3195     return false;
3196   };
3197 
3198   switch (BuiltinID) {
3199   default: return false;
3200   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3201   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3202     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3203            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3204   case PPC::BI__builtin_altivec_dss:
3205     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3206   case PPC::BI__builtin_tbegin:
3207   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3208   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3209   case PPC::BI__builtin_tabortwc:
3210   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3211   case PPC::BI__builtin_tabortwci:
3212   case PPC::BI__builtin_tabortdci:
3213     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3214            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3215   case PPC::BI__builtin_altivec_dst:
3216   case PPC::BI__builtin_altivec_dstt:
3217   case PPC::BI__builtin_altivec_dstst:
3218   case PPC::BI__builtin_altivec_dststt:
3219     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3220   case PPC::BI__builtin_vsx_xxpermdi:
3221   case PPC::BI__builtin_vsx_xxsldwi:
3222     return SemaBuiltinVSX(TheCall);
3223   case PPC::BI__builtin_unpack_vector_int128:
3224     return SemaVSXCheck(TheCall) ||
3225            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3226   case PPC::BI__builtin_pack_vector_int128:
3227     return SemaVSXCheck(TheCall);
3228   case PPC::BI__builtin_altivec_vgnb:
3229      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3230   case PPC::BI__builtin_altivec_vec_replace_elt:
3231   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3232     QualType VecTy = TheCall->getArg(0)->getType();
3233     QualType EltTy = TheCall->getArg(1)->getType();
3234     unsigned Width = Context.getIntWidth(EltTy);
3235     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3236            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3237   }
3238   case PPC::BI__builtin_vsx_xxeval:
3239      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3240   case PPC::BI__builtin_altivec_vsldbi:
3241      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3242   case PPC::BI__builtin_altivec_vsrdbi:
3243      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3244   case PPC::BI__builtin_vsx_xxpermx:
3245      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3246   }
3247   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3248 }
3249 
3250 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3251                                           CallExpr *TheCall) {
3252   // position of memory order and scope arguments in the builtin
3253   unsigned OrderIndex, ScopeIndex;
3254   switch (BuiltinID) {
3255   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3256   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3257   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3258   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3259     OrderIndex = 2;
3260     ScopeIndex = 3;
3261     break;
3262   case AMDGPU::BI__builtin_amdgcn_fence:
3263     OrderIndex = 0;
3264     ScopeIndex = 1;
3265     break;
3266   default:
3267     return false;
3268   }
3269 
3270   ExprResult Arg = TheCall->getArg(OrderIndex);
3271   auto ArgExpr = Arg.get();
3272   Expr::EvalResult ArgResult;
3273 
3274   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3275     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3276            << ArgExpr->getType();
3277   int ord = ArgResult.Val.getInt().getZExtValue();
3278 
3279   // Check valididty of memory ordering as per C11 / C++11's memody model.
3280   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3281   case llvm::AtomicOrderingCABI::acquire:
3282   case llvm::AtomicOrderingCABI::release:
3283   case llvm::AtomicOrderingCABI::acq_rel:
3284   case llvm::AtomicOrderingCABI::seq_cst:
3285     break;
3286   default: {
3287     return Diag(ArgExpr->getBeginLoc(),
3288                 diag::warn_atomic_op_has_invalid_memory_order)
3289            << ArgExpr->getSourceRange();
3290   }
3291   }
3292 
3293   Arg = TheCall->getArg(ScopeIndex);
3294   ArgExpr = Arg.get();
3295   Expr::EvalResult ArgResult1;
3296   // Check that sync scope is a constant literal
3297   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3298     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3299            << ArgExpr->getType();
3300 
3301   return false;
3302 }
3303 
3304 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3305                                            CallExpr *TheCall) {
3306   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3307     Expr *Arg = TheCall->getArg(0);
3308     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3309       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3310         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3311                << Arg->getSourceRange();
3312   }
3313 
3314   // For intrinsics which take an immediate value as part of the instruction,
3315   // range check them here.
3316   unsigned i = 0, l = 0, u = 0;
3317   switch (BuiltinID) {
3318   default: return false;
3319   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3320   case SystemZ::BI__builtin_s390_verimb:
3321   case SystemZ::BI__builtin_s390_verimh:
3322   case SystemZ::BI__builtin_s390_verimf:
3323   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3324   case SystemZ::BI__builtin_s390_vfaeb:
3325   case SystemZ::BI__builtin_s390_vfaeh:
3326   case SystemZ::BI__builtin_s390_vfaef:
3327   case SystemZ::BI__builtin_s390_vfaebs:
3328   case SystemZ::BI__builtin_s390_vfaehs:
3329   case SystemZ::BI__builtin_s390_vfaefs:
3330   case SystemZ::BI__builtin_s390_vfaezb:
3331   case SystemZ::BI__builtin_s390_vfaezh:
3332   case SystemZ::BI__builtin_s390_vfaezf:
3333   case SystemZ::BI__builtin_s390_vfaezbs:
3334   case SystemZ::BI__builtin_s390_vfaezhs:
3335   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3336   case SystemZ::BI__builtin_s390_vfisb:
3337   case SystemZ::BI__builtin_s390_vfidb:
3338     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3339            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3340   case SystemZ::BI__builtin_s390_vftcisb:
3341   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3342   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3343   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3344   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3345   case SystemZ::BI__builtin_s390_vstrcb:
3346   case SystemZ::BI__builtin_s390_vstrch:
3347   case SystemZ::BI__builtin_s390_vstrcf:
3348   case SystemZ::BI__builtin_s390_vstrczb:
3349   case SystemZ::BI__builtin_s390_vstrczh:
3350   case SystemZ::BI__builtin_s390_vstrczf:
3351   case SystemZ::BI__builtin_s390_vstrcbs:
3352   case SystemZ::BI__builtin_s390_vstrchs:
3353   case SystemZ::BI__builtin_s390_vstrcfs:
3354   case SystemZ::BI__builtin_s390_vstrczbs:
3355   case SystemZ::BI__builtin_s390_vstrczhs:
3356   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3357   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3358   case SystemZ::BI__builtin_s390_vfminsb:
3359   case SystemZ::BI__builtin_s390_vfmaxsb:
3360   case SystemZ::BI__builtin_s390_vfmindb:
3361   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3362   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3363   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3364   }
3365   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3366 }
3367 
3368 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3369 /// This checks that the target supports __builtin_cpu_supports and
3370 /// that the string argument is constant and valid.
3371 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3372                                    CallExpr *TheCall) {
3373   Expr *Arg = TheCall->getArg(0);
3374 
3375   // Check if the argument is a string literal.
3376   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3377     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3378            << Arg->getSourceRange();
3379 
3380   // Check the contents of the string.
3381   StringRef Feature =
3382       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3383   if (!TI.validateCpuSupports(Feature))
3384     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3385            << Arg->getSourceRange();
3386   return false;
3387 }
3388 
3389 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3390 /// This checks that the target supports __builtin_cpu_is and
3391 /// that the string argument is constant and valid.
3392 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3393   Expr *Arg = TheCall->getArg(0);
3394 
3395   // Check if the argument is a string literal.
3396   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3397     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3398            << Arg->getSourceRange();
3399 
3400   // Check the contents of the string.
3401   StringRef Feature =
3402       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3403   if (!TI.validateCpuIs(Feature))
3404     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3405            << Arg->getSourceRange();
3406   return false;
3407 }
3408 
3409 // Check if the rounding mode is legal.
3410 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3411   // Indicates if this instruction has rounding control or just SAE.
3412   bool HasRC = false;
3413 
3414   unsigned ArgNum = 0;
3415   switch (BuiltinID) {
3416   default:
3417     return false;
3418   case X86::BI__builtin_ia32_vcvttsd2si32:
3419   case X86::BI__builtin_ia32_vcvttsd2si64:
3420   case X86::BI__builtin_ia32_vcvttsd2usi32:
3421   case X86::BI__builtin_ia32_vcvttsd2usi64:
3422   case X86::BI__builtin_ia32_vcvttss2si32:
3423   case X86::BI__builtin_ia32_vcvttss2si64:
3424   case X86::BI__builtin_ia32_vcvttss2usi32:
3425   case X86::BI__builtin_ia32_vcvttss2usi64:
3426     ArgNum = 1;
3427     break;
3428   case X86::BI__builtin_ia32_maxpd512:
3429   case X86::BI__builtin_ia32_maxps512:
3430   case X86::BI__builtin_ia32_minpd512:
3431   case X86::BI__builtin_ia32_minps512:
3432     ArgNum = 2;
3433     break;
3434   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3435   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3436   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3437   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3438   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3439   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3440   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3441   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3442   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3443   case X86::BI__builtin_ia32_exp2pd_mask:
3444   case X86::BI__builtin_ia32_exp2ps_mask:
3445   case X86::BI__builtin_ia32_getexppd512_mask:
3446   case X86::BI__builtin_ia32_getexpps512_mask:
3447   case X86::BI__builtin_ia32_rcp28pd_mask:
3448   case X86::BI__builtin_ia32_rcp28ps_mask:
3449   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3450   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3451   case X86::BI__builtin_ia32_vcomisd:
3452   case X86::BI__builtin_ia32_vcomiss:
3453   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3454     ArgNum = 3;
3455     break;
3456   case X86::BI__builtin_ia32_cmppd512_mask:
3457   case X86::BI__builtin_ia32_cmpps512_mask:
3458   case X86::BI__builtin_ia32_cmpsd_mask:
3459   case X86::BI__builtin_ia32_cmpss_mask:
3460   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3461   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3462   case X86::BI__builtin_ia32_getexpss128_round_mask:
3463   case X86::BI__builtin_ia32_getmantpd512_mask:
3464   case X86::BI__builtin_ia32_getmantps512_mask:
3465   case X86::BI__builtin_ia32_maxsd_round_mask:
3466   case X86::BI__builtin_ia32_maxss_round_mask:
3467   case X86::BI__builtin_ia32_minsd_round_mask:
3468   case X86::BI__builtin_ia32_minss_round_mask:
3469   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3470   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3471   case X86::BI__builtin_ia32_reducepd512_mask:
3472   case X86::BI__builtin_ia32_reduceps512_mask:
3473   case X86::BI__builtin_ia32_rndscalepd_mask:
3474   case X86::BI__builtin_ia32_rndscaleps_mask:
3475   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3476   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3477     ArgNum = 4;
3478     break;
3479   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3480   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3481   case X86::BI__builtin_ia32_fixupimmps512_mask:
3482   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3483   case X86::BI__builtin_ia32_fixupimmsd_mask:
3484   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3485   case X86::BI__builtin_ia32_fixupimmss_mask:
3486   case X86::BI__builtin_ia32_fixupimmss_maskz:
3487   case X86::BI__builtin_ia32_getmantsd_round_mask:
3488   case X86::BI__builtin_ia32_getmantss_round_mask:
3489   case X86::BI__builtin_ia32_rangepd512_mask:
3490   case X86::BI__builtin_ia32_rangeps512_mask:
3491   case X86::BI__builtin_ia32_rangesd128_round_mask:
3492   case X86::BI__builtin_ia32_rangess128_round_mask:
3493   case X86::BI__builtin_ia32_reducesd_mask:
3494   case X86::BI__builtin_ia32_reducess_mask:
3495   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3496   case X86::BI__builtin_ia32_rndscaless_round_mask:
3497     ArgNum = 5;
3498     break;
3499   case X86::BI__builtin_ia32_vcvtsd2si64:
3500   case X86::BI__builtin_ia32_vcvtsd2si32:
3501   case X86::BI__builtin_ia32_vcvtsd2usi32:
3502   case X86::BI__builtin_ia32_vcvtsd2usi64:
3503   case X86::BI__builtin_ia32_vcvtss2si32:
3504   case X86::BI__builtin_ia32_vcvtss2si64:
3505   case X86::BI__builtin_ia32_vcvtss2usi32:
3506   case X86::BI__builtin_ia32_vcvtss2usi64:
3507   case X86::BI__builtin_ia32_sqrtpd512:
3508   case X86::BI__builtin_ia32_sqrtps512:
3509     ArgNum = 1;
3510     HasRC = true;
3511     break;
3512   case X86::BI__builtin_ia32_addpd512:
3513   case X86::BI__builtin_ia32_addps512:
3514   case X86::BI__builtin_ia32_divpd512:
3515   case X86::BI__builtin_ia32_divps512:
3516   case X86::BI__builtin_ia32_mulpd512:
3517   case X86::BI__builtin_ia32_mulps512:
3518   case X86::BI__builtin_ia32_subpd512:
3519   case X86::BI__builtin_ia32_subps512:
3520   case X86::BI__builtin_ia32_cvtsi2sd64:
3521   case X86::BI__builtin_ia32_cvtsi2ss32:
3522   case X86::BI__builtin_ia32_cvtsi2ss64:
3523   case X86::BI__builtin_ia32_cvtusi2sd64:
3524   case X86::BI__builtin_ia32_cvtusi2ss32:
3525   case X86::BI__builtin_ia32_cvtusi2ss64:
3526     ArgNum = 2;
3527     HasRC = true;
3528     break;
3529   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3530   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3531   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3532   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3533   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3534   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3535   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3536   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3537   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3538   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3539   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3540   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3541   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3542   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3543   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3544     ArgNum = 3;
3545     HasRC = true;
3546     break;
3547   case X86::BI__builtin_ia32_addss_round_mask:
3548   case X86::BI__builtin_ia32_addsd_round_mask:
3549   case X86::BI__builtin_ia32_divss_round_mask:
3550   case X86::BI__builtin_ia32_divsd_round_mask:
3551   case X86::BI__builtin_ia32_mulss_round_mask:
3552   case X86::BI__builtin_ia32_mulsd_round_mask:
3553   case X86::BI__builtin_ia32_subss_round_mask:
3554   case X86::BI__builtin_ia32_subsd_round_mask:
3555   case X86::BI__builtin_ia32_scalefpd512_mask:
3556   case X86::BI__builtin_ia32_scalefps512_mask:
3557   case X86::BI__builtin_ia32_scalefsd_round_mask:
3558   case X86::BI__builtin_ia32_scalefss_round_mask:
3559   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3560   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3561   case X86::BI__builtin_ia32_sqrtss_round_mask:
3562   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3563   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3564   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3565   case X86::BI__builtin_ia32_vfmaddss3_mask:
3566   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3567   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3568   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3569   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3570   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3571   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3572   case X86::BI__builtin_ia32_vfmaddps512_mask:
3573   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3574   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3575   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3576   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3577   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3578   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3579   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3580   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3581   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3582   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3583   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3584     ArgNum = 4;
3585     HasRC = true;
3586     break;
3587   }
3588 
3589   llvm::APSInt Result;
3590 
3591   // We can't check the value of a dependent argument.
3592   Expr *Arg = TheCall->getArg(ArgNum);
3593   if (Arg->isTypeDependent() || Arg->isValueDependent())
3594     return false;
3595 
3596   // Check constant-ness first.
3597   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3598     return true;
3599 
3600   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3601   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3602   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3603   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3604   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3605       Result == 8/*ROUND_NO_EXC*/ ||
3606       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3607       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3608     return false;
3609 
3610   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3611          << Arg->getSourceRange();
3612 }
3613 
3614 // Check if the gather/scatter scale is legal.
3615 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3616                                              CallExpr *TheCall) {
3617   unsigned ArgNum = 0;
3618   switch (BuiltinID) {
3619   default:
3620     return false;
3621   case X86::BI__builtin_ia32_gatherpfdpd:
3622   case X86::BI__builtin_ia32_gatherpfdps:
3623   case X86::BI__builtin_ia32_gatherpfqpd:
3624   case X86::BI__builtin_ia32_gatherpfqps:
3625   case X86::BI__builtin_ia32_scatterpfdpd:
3626   case X86::BI__builtin_ia32_scatterpfdps:
3627   case X86::BI__builtin_ia32_scatterpfqpd:
3628   case X86::BI__builtin_ia32_scatterpfqps:
3629     ArgNum = 3;
3630     break;
3631   case X86::BI__builtin_ia32_gatherd_pd:
3632   case X86::BI__builtin_ia32_gatherd_pd256:
3633   case X86::BI__builtin_ia32_gatherq_pd:
3634   case X86::BI__builtin_ia32_gatherq_pd256:
3635   case X86::BI__builtin_ia32_gatherd_ps:
3636   case X86::BI__builtin_ia32_gatherd_ps256:
3637   case X86::BI__builtin_ia32_gatherq_ps:
3638   case X86::BI__builtin_ia32_gatherq_ps256:
3639   case X86::BI__builtin_ia32_gatherd_q:
3640   case X86::BI__builtin_ia32_gatherd_q256:
3641   case X86::BI__builtin_ia32_gatherq_q:
3642   case X86::BI__builtin_ia32_gatherq_q256:
3643   case X86::BI__builtin_ia32_gatherd_d:
3644   case X86::BI__builtin_ia32_gatherd_d256:
3645   case X86::BI__builtin_ia32_gatherq_d:
3646   case X86::BI__builtin_ia32_gatherq_d256:
3647   case X86::BI__builtin_ia32_gather3div2df:
3648   case X86::BI__builtin_ia32_gather3div2di:
3649   case X86::BI__builtin_ia32_gather3div4df:
3650   case X86::BI__builtin_ia32_gather3div4di:
3651   case X86::BI__builtin_ia32_gather3div4sf:
3652   case X86::BI__builtin_ia32_gather3div4si:
3653   case X86::BI__builtin_ia32_gather3div8sf:
3654   case X86::BI__builtin_ia32_gather3div8si:
3655   case X86::BI__builtin_ia32_gather3siv2df:
3656   case X86::BI__builtin_ia32_gather3siv2di:
3657   case X86::BI__builtin_ia32_gather3siv4df:
3658   case X86::BI__builtin_ia32_gather3siv4di:
3659   case X86::BI__builtin_ia32_gather3siv4sf:
3660   case X86::BI__builtin_ia32_gather3siv4si:
3661   case X86::BI__builtin_ia32_gather3siv8sf:
3662   case X86::BI__builtin_ia32_gather3siv8si:
3663   case X86::BI__builtin_ia32_gathersiv8df:
3664   case X86::BI__builtin_ia32_gathersiv16sf:
3665   case X86::BI__builtin_ia32_gatherdiv8df:
3666   case X86::BI__builtin_ia32_gatherdiv16sf:
3667   case X86::BI__builtin_ia32_gathersiv8di:
3668   case X86::BI__builtin_ia32_gathersiv16si:
3669   case X86::BI__builtin_ia32_gatherdiv8di:
3670   case X86::BI__builtin_ia32_gatherdiv16si:
3671   case X86::BI__builtin_ia32_scatterdiv2df:
3672   case X86::BI__builtin_ia32_scatterdiv2di:
3673   case X86::BI__builtin_ia32_scatterdiv4df:
3674   case X86::BI__builtin_ia32_scatterdiv4di:
3675   case X86::BI__builtin_ia32_scatterdiv4sf:
3676   case X86::BI__builtin_ia32_scatterdiv4si:
3677   case X86::BI__builtin_ia32_scatterdiv8sf:
3678   case X86::BI__builtin_ia32_scatterdiv8si:
3679   case X86::BI__builtin_ia32_scattersiv2df:
3680   case X86::BI__builtin_ia32_scattersiv2di:
3681   case X86::BI__builtin_ia32_scattersiv4df:
3682   case X86::BI__builtin_ia32_scattersiv4di:
3683   case X86::BI__builtin_ia32_scattersiv4sf:
3684   case X86::BI__builtin_ia32_scattersiv4si:
3685   case X86::BI__builtin_ia32_scattersiv8sf:
3686   case X86::BI__builtin_ia32_scattersiv8si:
3687   case X86::BI__builtin_ia32_scattersiv8df:
3688   case X86::BI__builtin_ia32_scattersiv16sf:
3689   case X86::BI__builtin_ia32_scatterdiv8df:
3690   case X86::BI__builtin_ia32_scatterdiv16sf:
3691   case X86::BI__builtin_ia32_scattersiv8di:
3692   case X86::BI__builtin_ia32_scattersiv16si:
3693   case X86::BI__builtin_ia32_scatterdiv8di:
3694   case X86::BI__builtin_ia32_scatterdiv16si:
3695     ArgNum = 4;
3696     break;
3697   }
3698 
3699   llvm::APSInt Result;
3700 
3701   // We can't check the value of a dependent argument.
3702   Expr *Arg = TheCall->getArg(ArgNum);
3703   if (Arg->isTypeDependent() || Arg->isValueDependent())
3704     return false;
3705 
3706   // Check constant-ness first.
3707   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3708     return true;
3709 
3710   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3711     return false;
3712 
3713   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3714          << Arg->getSourceRange();
3715 }
3716 
3717 enum { TileRegLow = 0, TileRegHigh = 7 };
3718 
3719 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3720                                              ArrayRef<int> ArgNums) {
3721   for (int ArgNum : ArgNums) {
3722     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3723       return true;
3724   }
3725   return false;
3726 }
3727 
3728 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3729                                         ArrayRef<int> ArgNums) {
3730   // Because the max number of tile register is TileRegHigh + 1, so here we use
3731   // each bit to represent the usage of them in bitset.
3732   std::bitset<TileRegHigh + 1> ArgValues;
3733   for (int ArgNum : ArgNums) {
3734     Expr *Arg = TheCall->getArg(ArgNum);
3735     if (Arg->isTypeDependent() || Arg->isValueDependent())
3736       continue;
3737 
3738     llvm::APSInt Result;
3739     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3740       return true;
3741     int ArgExtValue = Result.getExtValue();
3742     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3743            "Incorrect tile register num.");
3744     if (ArgValues.test(ArgExtValue))
3745       return Diag(TheCall->getBeginLoc(),
3746                   diag::err_x86_builtin_tile_arg_duplicate)
3747              << TheCall->getArg(ArgNum)->getSourceRange();
3748     ArgValues.set(ArgExtValue);
3749   }
3750   return false;
3751 }
3752 
3753 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3754                                                 ArrayRef<int> ArgNums) {
3755   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3756          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3757 }
3758 
3759 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3760   switch (BuiltinID) {
3761   default:
3762     return false;
3763   case X86::BI__builtin_ia32_tileloadd64:
3764   case X86::BI__builtin_ia32_tileloaddt164:
3765   case X86::BI__builtin_ia32_tilestored64:
3766   case X86::BI__builtin_ia32_tilezero:
3767     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3768   case X86::BI__builtin_ia32_tdpbssd:
3769   case X86::BI__builtin_ia32_tdpbsud:
3770   case X86::BI__builtin_ia32_tdpbusd:
3771   case X86::BI__builtin_ia32_tdpbuud:
3772   case X86::BI__builtin_ia32_tdpbf16ps:
3773     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3774   }
3775 }
3776 static bool isX86_32Builtin(unsigned BuiltinID) {
3777   // These builtins only work on x86-32 targets.
3778   switch (BuiltinID) {
3779   case X86::BI__builtin_ia32_readeflags_u32:
3780   case X86::BI__builtin_ia32_writeeflags_u32:
3781     return true;
3782   }
3783 
3784   return false;
3785 }
3786 
3787 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3788                                        CallExpr *TheCall) {
3789   if (BuiltinID == X86::BI__builtin_cpu_supports)
3790     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3791 
3792   if (BuiltinID == X86::BI__builtin_cpu_is)
3793     return SemaBuiltinCpuIs(*this, TI, TheCall);
3794 
3795   // Check for 32-bit only builtins on a 64-bit target.
3796   const llvm::Triple &TT = TI.getTriple();
3797   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3798     return Diag(TheCall->getCallee()->getBeginLoc(),
3799                 diag::err_32_bit_builtin_64_bit_tgt);
3800 
3801   // If the intrinsic has rounding or SAE make sure its valid.
3802   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3803     return true;
3804 
3805   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3806   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3807     return true;
3808 
3809   // If the intrinsic has a tile arguments, make sure they are valid.
3810   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3811     return true;
3812 
3813   // For intrinsics which take an immediate value as part of the instruction,
3814   // range check them here.
3815   int i = 0, l = 0, u = 0;
3816   switch (BuiltinID) {
3817   default:
3818     return false;
3819   case X86::BI__builtin_ia32_vec_ext_v2si:
3820   case X86::BI__builtin_ia32_vec_ext_v2di:
3821   case X86::BI__builtin_ia32_vextractf128_pd256:
3822   case X86::BI__builtin_ia32_vextractf128_ps256:
3823   case X86::BI__builtin_ia32_vextractf128_si256:
3824   case X86::BI__builtin_ia32_extract128i256:
3825   case X86::BI__builtin_ia32_extractf64x4_mask:
3826   case X86::BI__builtin_ia32_extracti64x4_mask:
3827   case X86::BI__builtin_ia32_extractf32x8_mask:
3828   case X86::BI__builtin_ia32_extracti32x8_mask:
3829   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3830   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3831   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3832   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3833     i = 1; l = 0; u = 1;
3834     break;
3835   case X86::BI__builtin_ia32_vec_set_v2di:
3836   case X86::BI__builtin_ia32_vinsertf128_pd256:
3837   case X86::BI__builtin_ia32_vinsertf128_ps256:
3838   case X86::BI__builtin_ia32_vinsertf128_si256:
3839   case X86::BI__builtin_ia32_insert128i256:
3840   case X86::BI__builtin_ia32_insertf32x8:
3841   case X86::BI__builtin_ia32_inserti32x8:
3842   case X86::BI__builtin_ia32_insertf64x4:
3843   case X86::BI__builtin_ia32_inserti64x4:
3844   case X86::BI__builtin_ia32_insertf64x2_256:
3845   case X86::BI__builtin_ia32_inserti64x2_256:
3846   case X86::BI__builtin_ia32_insertf32x4_256:
3847   case X86::BI__builtin_ia32_inserti32x4_256:
3848     i = 2; l = 0; u = 1;
3849     break;
3850   case X86::BI__builtin_ia32_vpermilpd:
3851   case X86::BI__builtin_ia32_vec_ext_v4hi:
3852   case X86::BI__builtin_ia32_vec_ext_v4si:
3853   case X86::BI__builtin_ia32_vec_ext_v4sf:
3854   case X86::BI__builtin_ia32_vec_ext_v4di:
3855   case X86::BI__builtin_ia32_extractf32x4_mask:
3856   case X86::BI__builtin_ia32_extracti32x4_mask:
3857   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3858   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3859     i = 1; l = 0; u = 3;
3860     break;
3861   case X86::BI_mm_prefetch:
3862   case X86::BI__builtin_ia32_vec_ext_v8hi:
3863   case X86::BI__builtin_ia32_vec_ext_v8si:
3864     i = 1; l = 0; u = 7;
3865     break;
3866   case X86::BI__builtin_ia32_sha1rnds4:
3867   case X86::BI__builtin_ia32_blendpd:
3868   case X86::BI__builtin_ia32_shufpd:
3869   case X86::BI__builtin_ia32_vec_set_v4hi:
3870   case X86::BI__builtin_ia32_vec_set_v4si:
3871   case X86::BI__builtin_ia32_vec_set_v4di:
3872   case X86::BI__builtin_ia32_shuf_f32x4_256:
3873   case X86::BI__builtin_ia32_shuf_f64x2_256:
3874   case X86::BI__builtin_ia32_shuf_i32x4_256:
3875   case X86::BI__builtin_ia32_shuf_i64x2_256:
3876   case X86::BI__builtin_ia32_insertf64x2_512:
3877   case X86::BI__builtin_ia32_inserti64x2_512:
3878   case X86::BI__builtin_ia32_insertf32x4:
3879   case X86::BI__builtin_ia32_inserti32x4:
3880     i = 2; l = 0; u = 3;
3881     break;
3882   case X86::BI__builtin_ia32_vpermil2pd:
3883   case X86::BI__builtin_ia32_vpermil2pd256:
3884   case X86::BI__builtin_ia32_vpermil2ps:
3885   case X86::BI__builtin_ia32_vpermil2ps256:
3886     i = 3; l = 0; u = 3;
3887     break;
3888   case X86::BI__builtin_ia32_cmpb128_mask:
3889   case X86::BI__builtin_ia32_cmpw128_mask:
3890   case X86::BI__builtin_ia32_cmpd128_mask:
3891   case X86::BI__builtin_ia32_cmpq128_mask:
3892   case X86::BI__builtin_ia32_cmpb256_mask:
3893   case X86::BI__builtin_ia32_cmpw256_mask:
3894   case X86::BI__builtin_ia32_cmpd256_mask:
3895   case X86::BI__builtin_ia32_cmpq256_mask:
3896   case X86::BI__builtin_ia32_cmpb512_mask:
3897   case X86::BI__builtin_ia32_cmpw512_mask:
3898   case X86::BI__builtin_ia32_cmpd512_mask:
3899   case X86::BI__builtin_ia32_cmpq512_mask:
3900   case X86::BI__builtin_ia32_ucmpb128_mask:
3901   case X86::BI__builtin_ia32_ucmpw128_mask:
3902   case X86::BI__builtin_ia32_ucmpd128_mask:
3903   case X86::BI__builtin_ia32_ucmpq128_mask:
3904   case X86::BI__builtin_ia32_ucmpb256_mask:
3905   case X86::BI__builtin_ia32_ucmpw256_mask:
3906   case X86::BI__builtin_ia32_ucmpd256_mask:
3907   case X86::BI__builtin_ia32_ucmpq256_mask:
3908   case X86::BI__builtin_ia32_ucmpb512_mask:
3909   case X86::BI__builtin_ia32_ucmpw512_mask:
3910   case X86::BI__builtin_ia32_ucmpd512_mask:
3911   case X86::BI__builtin_ia32_ucmpq512_mask:
3912   case X86::BI__builtin_ia32_vpcomub:
3913   case X86::BI__builtin_ia32_vpcomuw:
3914   case X86::BI__builtin_ia32_vpcomud:
3915   case X86::BI__builtin_ia32_vpcomuq:
3916   case X86::BI__builtin_ia32_vpcomb:
3917   case X86::BI__builtin_ia32_vpcomw:
3918   case X86::BI__builtin_ia32_vpcomd:
3919   case X86::BI__builtin_ia32_vpcomq:
3920   case X86::BI__builtin_ia32_vec_set_v8hi:
3921   case X86::BI__builtin_ia32_vec_set_v8si:
3922     i = 2; l = 0; u = 7;
3923     break;
3924   case X86::BI__builtin_ia32_vpermilpd256:
3925   case X86::BI__builtin_ia32_roundps:
3926   case X86::BI__builtin_ia32_roundpd:
3927   case X86::BI__builtin_ia32_roundps256:
3928   case X86::BI__builtin_ia32_roundpd256:
3929   case X86::BI__builtin_ia32_getmantpd128_mask:
3930   case X86::BI__builtin_ia32_getmantpd256_mask:
3931   case X86::BI__builtin_ia32_getmantps128_mask:
3932   case X86::BI__builtin_ia32_getmantps256_mask:
3933   case X86::BI__builtin_ia32_getmantpd512_mask:
3934   case X86::BI__builtin_ia32_getmantps512_mask:
3935   case X86::BI__builtin_ia32_vec_ext_v16qi:
3936   case X86::BI__builtin_ia32_vec_ext_v16hi:
3937     i = 1; l = 0; u = 15;
3938     break;
3939   case X86::BI__builtin_ia32_pblendd128:
3940   case X86::BI__builtin_ia32_blendps:
3941   case X86::BI__builtin_ia32_blendpd256:
3942   case X86::BI__builtin_ia32_shufpd256:
3943   case X86::BI__builtin_ia32_roundss:
3944   case X86::BI__builtin_ia32_roundsd:
3945   case X86::BI__builtin_ia32_rangepd128_mask:
3946   case X86::BI__builtin_ia32_rangepd256_mask:
3947   case X86::BI__builtin_ia32_rangepd512_mask:
3948   case X86::BI__builtin_ia32_rangeps128_mask:
3949   case X86::BI__builtin_ia32_rangeps256_mask:
3950   case X86::BI__builtin_ia32_rangeps512_mask:
3951   case X86::BI__builtin_ia32_getmantsd_round_mask:
3952   case X86::BI__builtin_ia32_getmantss_round_mask:
3953   case X86::BI__builtin_ia32_vec_set_v16qi:
3954   case X86::BI__builtin_ia32_vec_set_v16hi:
3955     i = 2; l = 0; u = 15;
3956     break;
3957   case X86::BI__builtin_ia32_vec_ext_v32qi:
3958     i = 1; l = 0; u = 31;
3959     break;
3960   case X86::BI__builtin_ia32_cmpps:
3961   case X86::BI__builtin_ia32_cmpss:
3962   case X86::BI__builtin_ia32_cmppd:
3963   case X86::BI__builtin_ia32_cmpsd:
3964   case X86::BI__builtin_ia32_cmpps256:
3965   case X86::BI__builtin_ia32_cmppd256:
3966   case X86::BI__builtin_ia32_cmpps128_mask:
3967   case X86::BI__builtin_ia32_cmppd128_mask:
3968   case X86::BI__builtin_ia32_cmpps256_mask:
3969   case X86::BI__builtin_ia32_cmppd256_mask:
3970   case X86::BI__builtin_ia32_cmpps512_mask:
3971   case X86::BI__builtin_ia32_cmppd512_mask:
3972   case X86::BI__builtin_ia32_cmpsd_mask:
3973   case X86::BI__builtin_ia32_cmpss_mask:
3974   case X86::BI__builtin_ia32_vec_set_v32qi:
3975     i = 2; l = 0; u = 31;
3976     break;
3977   case X86::BI__builtin_ia32_permdf256:
3978   case X86::BI__builtin_ia32_permdi256:
3979   case X86::BI__builtin_ia32_permdf512:
3980   case X86::BI__builtin_ia32_permdi512:
3981   case X86::BI__builtin_ia32_vpermilps:
3982   case X86::BI__builtin_ia32_vpermilps256:
3983   case X86::BI__builtin_ia32_vpermilpd512:
3984   case X86::BI__builtin_ia32_vpermilps512:
3985   case X86::BI__builtin_ia32_pshufd:
3986   case X86::BI__builtin_ia32_pshufd256:
3987   case X86::BI__builtin_ia32_pshufd512:
3988   case X86::BI__builtin_ia32_pshufhw:
3989   case X86::BI__builtin_ia32_pshufhw256:
3990   case X86::BI__builtin_ia32_pshufhw512:
3991   case X86::BI__builtin_ia32_pshuflw:
3992   case X86::BI__builtin_ia32_pshuflw256:
3993   case X86::BI__builtin_ia32_pshuflw512:
3994   case X86::BI__builtin_ia32_vcvtps2ph:
3995   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3996   case X86::BI__builtin_ia32_vcvtps2ph256:
3997   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3998   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3999   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4000   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4001   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4002   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4003   case X86::BI__builtin_ia32_rndscaleps_mask:
4004   case X86::BI__builtin_ia32_rndscalepd_mask:
4005   case X86::BI__builtin_ia32_reducepd128_mask:
4006   case X86::BI__builtin_ia32_reducepd256_mask:
4007   case X86::BI__builtin_ia32_reducepd512_mask:
4008   case X86::BI__builtin_ia32_reduceps128_mask:
4009   case X86::BI__builtin_ia32_reduceps256_mask:
4010   case X86::BI__builtin_ia32_reduceps512_mask:
4011   case X86::BI__builtin_ia32_prold512:
4012   case X86::BI__builtin_ia32_prolq512:
4013   case X86::BI__builtin_ia32_prold128:
4014   case X86::BI__builtin_ia32_prold256:
4015   case X86::BI__builtin_ia32_prolq128:
4016   case X86::BI__builtin_ia32_prolq256:
4017   case X86::BI__builtin_ia32_prord512:
4018   case X86::BI__builtin_ia32_prorq512:
4019   case X86::BI__builtin_ia32_prord128:
4020   case X86::BI__builtin_ia32_prord256:
4021   case X86::BI__builtin_ia32_prorq128:
4022   case X86::BI__builtin_ia32_prorq256:
4023   case X86::BI__builtin_ia32_fpclasspd128_mask:
4024   case X86::BI__builtin_ia32_fpclasspd256_mask:
4025   case X86::BI__builtin_ia32_fpclassps128_mask:
4026   case X86::BI__builtin_ia32_fpclassps256_mask:
4027   case X86::BI__builtin_ia32_fpclassps512_mask:
4028   case X86::BI__builtin_ia32_fpclasspd512_mask:
4029   case X86::BI__builtin_ia32_fpclasssd_mask:
4030   case X86::BI__builtin_ia32_fpclassss_mask:
4031   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4032   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4033   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4034   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4035   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4036   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4037   case X86::BI__builtin_ia32_kshiftliqi:
4038   case X86::BI__builtin_ia32_kshiftlihi:
4039   case X86::BI__builtin_ia32_kshiftlisi:
4040   case X86::BI__builtin_ia32_kshiftlidi:
4041   case X86::BI__builtin_ia32_kshiftriqi:
4042   case X86::BI__builtin_ia32_kshiftrihi:
4043   case X86::BI__builtin_ia32_kshiftrisi:
4044   case X86::BI__builtin_ia32_kshiftridi:
4045     i = 1; l = 0; u = 255;
4046     break;
4047   case X86::BI__builtin_ia32_vperm2f128_pd256:
4048   case X86::BI__builtin_ia32_vperm2f128_ps256:
4049   case X86::BI__builtin_ia32_vperm2f128_si256:
4050   case X86::BI__builtin_ia32_permti256:
4051   case X86::BI__builtin_ia32_pblendw128:
4052   case X86::BI__builtin_ia32_pblendw256:
4053   case X86::BI__builtin_ia32_blendps256:
4054   case X86::BI__builtin_ia32_pblendd256:
4055   case X86::BI__builtin_ia32_palignr128:
4056   case X86::BI__builtin_ia32_palignr256:
4057   case X86::BI__builtin_ia32_palignr512:
4058   case X86::BI__builtin_ia32_alignq512:
4059   case X86::BI__builtin_ia32_alignd512:
4060   case X86::BI__builtin_ia32_alignd128:
4061   case X86::BI__builtin_ia32_alignd256:
4062   case X86::BI__builtin_ia32_alignq128:
4063   case X86::BI__builtin_ia32_alignq256:
4064   case X86::BI__builtin_ia32_vcomisd:
4065   case X86::BI__builtin_ia32_vcomiss:
4066   case X86::BI__builtin_ia32_shuf_f32x4:
4067   case X86::BI__builtin_ia32_shuf_f64x2:
4068   case X86::BI__builtin_ia32_shuf_i32x4:
4069   case X86::BI__builtin_ia32_shuf_i64x2:
4070   case X86::BI__builtin_ia32_shufpd512:
4071   case X86::BI__builtin_ia32_shufps:
4072   case X86::BI__builtin_ia32_shufps256:
4073   case X86::BI__builtin_ia32_shufps512:
4074   case X86::BI__builtin_ia32_dbpsadbw128:
4075   case X86::BI__builtin_ia32_dbpsadbw256:
4076   case X86::BI__builtin_ia32_dbpsadbw512:
4077   case X86::BI__builtin_ia32_vpshldd128:
4078   case X86::BI__builtin_ia32_vpshldd256:
4079   case X86::BI__builtin_ia32_vpshldd512:
4080   case X86::BI__builtin_ia32_vpshldq128:
4081   case X86::BI__builtin_ia32_vpshldq256:
4082   case X86::BI__builtin_ia32_vpshldq512:
4083   case X86::BI__builtin_ia32_vpshldw128:
4084   case X86::BI__builtin_ia32_vpshldw256:
4085   case X86::BI__builtin_ia32_vpshldw512:
4086   case X86::BI__builtin_ia32_vpshrdd128:
4087   case X86::BI__builtin_ia32_vpshrdd256:
4088   case X86::BI__builtin_ia32_vpshrdd512:
4089   case X86::BI__builtin_ia32_vpshrdq128:
4090   case X86::BI__builtin_ia32_vpshrdq256:
4091   case X86::BI__builtin_ia32_vpshrdq512:
4092   case X86::BI__builtin_ia32_vpshrdw128:
4093   case X86::BI__builtin_ia32_vpshrdw256:
4094   case X86::BI__builtin_ia32_vpshrdw512:
4095     i = 2; l = 0; u = 255;
4096     break;
4097   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4098   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4099   case X86::BI__builtin_ia32_fixupimmps512_mask:
4100   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4101   case X86::BI__builtin_ia32_fixupimmsd_mask:
4102   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4103   case X86::BI__builtin_ia32_fixupimmss_mask:
4104   case X86::BI__builtin_ia32_fixupimmss_maskz:
4105   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4106   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4107   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4108   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4109   case X86::BI__builtin_ia32_fixupimmps128_mask:
4110   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4111   case X86::BI__builtin_ia32_fixupimmps256_mask:
4112   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4113   case X86::BI__builtin_ia32_pternlogd512_mask:
4114   case X86::BI__builtin_ia32_pternlogd512_maskz:
4115   case X86::BI__builtin_ia32_pternlogq512_mask:
4116   case X86::BI__builtin_ia32_pternlogq512_maskz:
4117   case X86::BI__builtin_ia32_pternlogd128_mask:
4118   case X86::BI__builtin_ia32_pternlogd128_maskz:
4119   case X86::BI__builtin_ia32_pternlogd256_mask:
4120   case X86::BI__builtin_ia32_pternlogd256_maskz:
4121   case X86::BI__builtin_ia32_pternlogq128_mask:
4122   case X86::BI__builtin_ia32_pternlogq128_maskz:
4123   case X86::BI__builtin_ia32_pternlogq256_mask:
4124   case X86::BI__builtin_ia32_pternlogq256_maskz:
4125     i = 3; l = 0; u = 255;
4126     break;
4127   case X86::BI__builtin_ia32_gatherpfdpd:
4128   case X86::BI__builtin_ia32_gatherpfdps:
4129   case X86::BI__builtin_ia32_gatherpfqpd:
4130   case X86::BI__builtin_ia32_gatherpfqps:
4131   case X86::BI__builtin_ia32_scatterpfdpd:
4132   case X86::BI__builtin_ia32_scatterpfdps:
4133   case X86::BI__builtin_ia32_scatterpfqpd:
4134   case X86::BI__builtin_ia32_scatterpfqps:
4135     i = 4; l = 2; u = 3;
4136     break;
4137   case X86::BI__builtin_ia32_reducesd_mask:
4138   case X86::BI__builtin_ia32_reducess_mask:
4139   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4140   case X86::BI__builtin_ia32_rndscaless_round_mask:
4141     i = 4; l = 0; u = 255;
4142     break;
4143   }
4144 
4145   // Note that we don't force a hard error on the range check here, allowing
4146   // template-generated or macro-generated dead code to potentially have out-of-
4147   // range values. These need to code generate, but don't need to necessarily
4148   // make any sense. We use a warning that defaults to an error.
4149   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4150 }
4151 
4152 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4153 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4154 /// Returns true when the format fits the function and the FormatStringInfo has
4155 /// been populated.
4156 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4157                                FormatStringInfo *FSI) {
4158   FSI->HasVAListArg = Format->getFirstArg() == 0;
4159   FSI->FormatIdx = Format->getFormatIdx() - 1;
4160   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4161 
4162   // The way the format attribute works in GCC, the implicit this argument
4163   // of member functions is counted. However, it doesn't appear in our own
4164   // lists, so decrement format_idx in that case.
4165   if (IsCXXMember) {
4166     if(FSI->FormatIdx == 0)
4167       return false;
4168     --FSI->FormatIdx;
4169     if (FSI->FirstDataArg != 0)
4170       --FSI->FirstDataArg;
4171   }
4172   return true;
4173 }
4174 
4175 /// Checks if a the given expression evaluates to null.
4176 ///
4177 /// Returns true if the value evaluates to null.
4178 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4179   // If the expression has non-null type, it doesn't evaluate to null.
4180   if (auto nullability
4181         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4182     if (*nullability == NullabilityKind::NonNull)
4183       return false;
4184   }
4185 
4186   // As a special case, transparent unions initialized with zero are
4187   // considered null for the purposes of the nonnull attribute.
4188   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4189     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4190       if (const CompoundLiteralExpr *CLE =
4191           dyn_cast<CompoundLiteralExpr>(Expr))
4192         if (const InitListExpr *ILE =
4193             dyn_cast<InitListExpr>(CLE->getInitializer()))
4194           Expr = ILE->getInit(0);
4195   }
4196 
4197   bool Result;
4198   return (!Expr->isValueDependent() &&
4199           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4200           !Result);
4201 }
4202 
4203 static void CheckNonNullArgument(Sema &S,
4204                                  const Expr *ArgExpr,
4205                                  SourceLocation CallSiteLoc) {
4206   if (CheckNonNullExpr(S, ArgExpr))
4207     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4208                           S.PDiag(diag::warn_null_arg)
4209                               << ArgExpr->getSourceRange());
4210 }
4211 
4212 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4213   FormatStringInfo FSI;
4214   if ((GetFormatStringType(Format) == FST_NSString) &&
4215       getFormatStringInfo(Format, false, &FSI)) {
4216     Idx = FSI.FormatIdx;
4217     return true;
4218   }
4219   return false;
4220 }
4221 
4222 /// Diagnose use of %s directive in an NSString which is being passed
4223 /// as formatting string to formatting method.
4224 static void
4225 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4226                                         const NamedDecl *FDecl,
4227                                         Expr **Args,
4228                                         unsigned NumArgs) {
4229   unsigned Idx = 0;
4230   bool Format = false;
4231   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4232   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4233     Idx = 2;
4234     Format = true;
4235   }
4236   else
4237     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4238       if (S.GetFormatNSStringIdx(I, Idx)) {
4239         Format = true;
4240         break;
4241       }
4242     }
4243   if (!Format || NumArgs <= Idx)
4244     return;
4245   const Expr *FormatExpr = Args[Idx];
4246   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4247     FormatExpr = CSCE->getSubExpr();
4248   const StringLiteral *FormatString;
4249   if (const ObjCStringLiteral *OSL =
4250       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4251     FormatString = OSL->getString();
4252   else
4253     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4254   if (!FormatString)
4255     return;
4256   if (S.FormatStringHasSArg(FormatString)) {
4257     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4258       << "%s" << 1 << 1;
4259     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4260       << FDecl->getDeclName();
4261   }
4262 }
4263 
4264 /// Determine whether the given type has a non-null nullability annotation.
4265 static bool isNonNullType(ASTContext &ctx, QualType type) {
4266   if (auto nullability = type->getNullability(ctx))
4267     return *nullability == NullabilityKind::NonNull;
4268 
4269   return false;
4270 }
4271 
4272 static void CheckNonNullArguments(Sema &S,
4273                                   const NamedDecl *FDecl,
4274                                   const FunctionProtoType *Proto,
4275                                   ArrayRef<const Expr *> Args,
4276                                   SourceLocation CallSiteLoc) {
4277   assert((FDecl || Proto) && "Need a function declaration or prototype");
4278 
4279   // Already checked by by constant evaluator.
4280   if (S.isConstantEvaluated())
4281     return;
4282   // Check the attributes attached to the method/function itself.
4283   llvm::SmallBitVector NonNullArgs;
4284   if (FDecl) {
4285     // Handle the nonnull attribute on the function/method declaration itself.
4286     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4287       if (!NonNull->args_size()) {
4288         // Easy case: all pointer arguments are nonnull.
4289         for (const auto *Arg : Args)
4290           if (S.isValidPointerAttrType(Arg->getType()))
4291             CheckNonNullArgument(S, Arg, CallSiteLoc);
4292         return;
4293       }
4294 
4295       for (const ParamIdx &Idx : NonNull->args()) {
4296         unsigned IdxAST = Idx.getASTIndex();
4297         if (IdxAST >= Args.size())
4298           continue;
4299         if (NonNullArgs.empty())
4300           NonNullArgs.resize(Args.size());
4301         NonNullArgs.set(IdxAST);
4302       }
4303     }
4304   }
4305 
4306   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4307     // Handle the nonnull attribute on the parameters of the
4308     // function/method.
4309     ArrayRef<ParmVarDecl*> parms;
4310     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4311       parms = FD->parameters();
4312     else
4313       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4314 
4315     unsigned ParamIndex = 0;
4316     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4317          I != E; ++I, ++ParamIndex) {
4318       const ParmVarDecl *PVD = *I;
4319       if (PVD->hasAttr<NonNullAttr>() ||
4320           isNonNullType(S.Context, PVD->getType())) {
4321         if (NonNullArgs.empty())
4322           NonNullArgs.resize(Args.size());
4323 
4324         NonNullArgs.set(ParamIndex);
4325       }
4326     }
4327   } else {
4328     // If we have a non-function, non-method declaration but no
4329     // function prototype, try to dig out the function prototype.
4330     if (!Proto) {
4331       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4332         QualType type = VD->getType().getNonReferenceType();
4333         if (auto pointerType = type->getAs<PointerType>())
4334           type = pointerType->getPointeeType();
4335         else if (auto blockType = type->getAs<BlockPointerType>())
4336           type = blockType->getPointeeType();
4337         // FIXME: data member pointers?
4338 
4339         // Dig out the function prototype, if there is one.
4340         Proto = type->getAs<FunctionProtoType>();
4341       }
4342     }
4343 
4344     // Fill in non-null argument information from the nullability
4345     // information on the parameter types (if we have them).
4346     if (Proto) {
4347       unsigned Index = 0;
4348       for (auto paramType : Proto->getParamTypes()) {
4349         if (isNonNullType(S.Context, paramType)) {
4350           if (NonNullArgs.empty())
4351             NonNullArgs.resize(Args.size());
4352 
4353           NonNullArgs.set(Index);
4354         }
4355 
4356         ++Index;
4357       }
4358     }
4359   }
4360 
4361   // Check for non-null arguments.
4362   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4363        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4364     if (NonNullArgs[ArgIndex])
4365       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4366   }
4367 }
4368 
4369 /// Handles the checks for format strings, non-POD arguments to vararg
4370 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4371 /// attributes.
4372 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4373                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4374                      bool IsMemberFunction, SourceLocation Loc,
4375                      SourceRange Range, VariadicCallType CallType) {
4376   // FIXME: We should check as much as we can in the template definition.
4377   if (CurContext->isDependentContext())
4378     return;
4379 
4380   // Printf and scanf checking.
4381   llvm::SmallBitVector CheckedVarArgs;
4382   if (FDecl) {
4383     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4384       // Only create vector if there are format attributes.
4385       CheckedVarArgs.resize(Args.size());
4386 
4387       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4388                            CheckedVarArgs);
4389     }
4390   }
4391 
4392   // Refuse POD arguments that weren't caught by the format string
4393   // checks above.
4394   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4395   if (CallType != VariadicDoesNotApply &&
4396       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4397     unsigned NumParams = Proto ? Proto->getNumParams()
4398                        : FDecl && isa<FunctionDecl>(FDecl)
4399                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4400                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4401                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4402                        : 0;
4403 
4404     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4405       // Args[ArgIdx] can be null in malformed code.
4406       if (const Expr *Arg = Args[ArgIdx]) {
4407         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4408           checkVariadicArgument(Arg, CallType);
4409       }
4410     }
4411   }
4412 
4413   if (FDecl || Proto) {
4414     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4415 
4416     // Type safety checking.
4417     if (FDecl) {
4418       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4419         CheckArgumentWithTypeTag(I, Args, Loc);
4420     }
4421   }
4422 
4423   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4424     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4425     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4426     if (!Arg->isValueDependent()) {
4427       Expr::EvalResult Align;
4428       if (Arg->EvaluateAsInt(Align, Context)) {
4429         const llvm::APSInt &I = Align.Val.getInt();
4430         if (!I.isPowerOf2())
4431           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4432               << Arg->getSourceRange();
4433 
4434         if (I > Sema::MaximumAlignment)
4435           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4436               << Arg->getSourceRange() << Sema::MaximumAlignment;
4437       }
4438     }
4439   }
4440 
4441   if (FD)
4442     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4443 }
4444 
4445 /// CheckConstructorCall - Check a constructor call for correctness and safety
4446 /// properties not enforced by the C type system.
4447 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4448                                 ArrayRef<const Expr *> Args,
4449                                 const FunctionProtoType *Proto,
4450                                 SourceLocation Loc) {
4451   VariadicCallType CallType =
4452     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4453   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4454             Loc, SourceRange(), CallType);
4455 }
4456 
4457 /// CheckFunctionCall - Check a direct function call for various correctness
4458 /// and safety properties not strictly enforced by the C type system.
4459 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4460                              const FunctionProtoType *Proto) {
4461   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4462                               isa<CXXMethodDecl>(FDecl);
4463   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4464                           IsMemberOperatorCall;
4465   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4466                                                   TheCall->getCallee());
4467   Expr** Args = TheCall->getArgs();
4468   unsigned NumArgs = TheCall->getNumArgs();
4469 
4470   Expr *ImplicitThis = nullptr;
4471   if (IsMemberOperatorCall) {
4472     // If this is a call to a member operator, hide the first argument
4473     // from checkCall.
4474     // FIXME: Our choice of AST representation here is less than ideal.
4475     ImplicitThis = Args[0];
4476     ++Args;
4477     --NumArgs;
4478   } else if (IsMemberFunction)
4479     ImplicitThis =
4480         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4481 
4482   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4483             IsMemberFunction, TheCall->getRParenLoc(),
4484             TheCall->getCallee()->getSourceRange(), CallType);
4485 
4486   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4487   // None of the checks below are needed for functions that don't have
4488   // simple names (e.g., C++ conversion functions).
4489   if (!FnInfo)
4490     return false;
4491 
4492   CheckAbsoluteValueFunction(TheCall, FDecl);
4493   CheckMaxUnsignedZero(TheCall, FDecl);
4494 
4495   if (getLangOpts().ObjC)
4496     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4497 
4498   unsigned CMId = FDecl->getMemoryFunctionKind();
4499 
4500   // Handle memory setting and copying functions.
4501   switch (CMId) {
4502   case 0:
4503     return false;
4504   case Builtin::BIstrlcpy: // fallthrough
4505   case Builtin::BIstrlcat:
4506     CheckStrlcpycatArguments(TheCall, FnInfo);
4507     break;
4508   case Builtin::BIstrncat:
4509     CheckStrncatArguments(TheCall, FnInfo);
4510     break;
4511   case Builtin::BIfree:
4512     CheckFreeArguments(TheCall);
4513     break;
4514   default:
4515     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4516   }
4517 
4518   return false;
4519 }
4520 
4521 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4522                                ArrayRef<const Expr *> Args) {
4523   VariadicCallType CallType =
4524       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4525 
4526   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4527             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4528             CallType);
4529 
4530   return false;
4531 }
4532 
4533 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4534                             const FunctionProtoType *Proto) {
4535   QualType Ty;
4536   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4537     Ty = V->getType().getNonReferenceType();
4538   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4539     Ty = F->getType().getNonReferenceType();
4540   else
4541     return false;
4542 
4543   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4544       !Ty->isFunctionProtoType())
4545     return false;
4546 
4547   VariadicCallType CallType;
4548   if (!Proto || !Proto->isVariadic()) {
4549     CallType = VariadicDoesNotApply;
4550   } else if (Ty->isBlockPointerType()) {
4551     CallType = VariadicBlock;
4552   } else { // Ty->isFunctionPointerType()
4553     CallType = VariadicFunction;
4554   }
4555 
4556   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4557             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4558             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4559             TheCall->getCallee()->getSourceRange(), CallType);
4560 
4561   return false;
4562 }
4563 
4564 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4565 /// such as function pointers returned from functions.
4566 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4567   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4568                                                   TheCall->getCallee());
4569   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4570             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4571             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4572             TheCall->getCallee()->getSourceRange(), CallType);
4573 
4574   return false;
4575 }
4576 
4577 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4578   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4579     return false;
4580 
4581   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4582   switch (Op) {
4583   case AtomicExpr::AO__c11_atomic_init:
4584   case AtomicExpr::AO__opencl_atomic_init:
4585     llvm_unreachable("There is no ordering argument for an init");
4586 
4587   case AtomicExpr::AO__c11_atomic_load:
4588   case AtomicExpr::AO__opencl_atomic_load:
4589   case AtomicExpr::AO__atomic_load_n:
4590   case AtomicExpr::AO__atomic_load:
4591     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4592            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4593 
4594   case AtomicExpr::AO__c11_atomic_store:
4595   case AtomicExpr::AO__opencl_atomic_store:
4596   case AtomicExpr::AO__atomic_store:
4597   case AtomicExpr::AO__atomic_store_n:
4598     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4599            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4600            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4601 
4602   default:
4603     return true;
4604   }
4605 }
4606 
4607 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4608                                          AtomicExpr::AtomicOp Op) {
4609   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4610   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4611   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4612   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4613                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4614                          Op);
4615 }
4616 
4617 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4618                                  SourceLocation RParenLoc, MultiExprArg Args,
4619                                  AtomicExpr::AtomicOp Op,
4620                                  AtomicArgumentOrder ArgOrder) {
4621   // All the non-OpenCL operations take one of the following forms.
4622   // The OpenCL operations take the __c11 forms with one extra argument for
4623   // synchronization scope.
4624   enum {
4625     // C    __c11_atomic_init(A *, C)
4626     Init,
4627 
4628     // C    __c11_atomic_load(A *, int)
4629     Load,
4630 
4631     // void __atomic_load(A *, CP, int)
4632     LoadCopy,
4633 
4634     // void __atomic_store(A *, CP, int)
4635     Copy,
4636 
4637     // C    __c11_atomic_add(A *, M, int)
4638     Arithmetic,
4639 
4640     // C    __atomic_exchange_n(A *, CP, int)
4641     Xchg,
4642 
4643     // void __atomic_exchange(A *, C *, CP, int)
4644     GNUXchg,
4645 
4646     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4647     C11CmpXchg,
4648 
4649     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4650     GNUCmpXchg
4651   } Form = Init;
4652 
4653   const unsigned NumForm = GNUCmpXchg + 1;
4654   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4655   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4656   // where:
4657   //   C is an appropriate type,
4658   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4659   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4660   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4661   //   the int parameters are for orderings.
4662 
4663   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4664       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4665       "need to update code for modified forms");
4666   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4667                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4668                         AtomicExpr::AO__atomic_load,
4669                 "need to update code for modified C11 atomics");
4670   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4671                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4672   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4673                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4674                IsOpenCL;
4675   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4676              Op == AtomicExpr::AO__atomic_store_n ||
4677              Op == AtomicExpr::AO__atomic_exchange_n ||
4678              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4679   bool IsAddSub = false;
4680 
4681   switch (Op) {
4682   case AtomicExpr::AO__c11_atomic_init:
4683   case AtomicExpr::AO__opencl_atomic_init:
4684     Form = Init;
4685     break;
4686 
4687   case AtomicExpr::AO__c11_atomic_load:
4688   case AtomicExpr::AO__opencl_atomic_load:
4689   case AtomicExpr::AO__atomic_load_n:
4690     Form = Load;
4691     break;
4692 
4693   case AtomicExpr::AO__atomic_load:
4694     Form = LoadCopy;
4695     break;
4696 
4697   case AtomicExpr::AO__c11_atomic_store:
4698   case AtomicExpr::AO__opencl_atomic_store:
4699   case AtomicExpr::AO__atomic_store:
4700   case AtomicExpr::AO__atomic_store_n:
4701     Form = Copy;
4702     break;
4703 
4704   case AtomicExpr::AO__c11_atomic_fetch_add:
4705   case AtomicExpr::AO__c11_atomic_fetch_sub:
4706   case AtomicExpr::AO__opencl_atomic_fetch_add:
4707   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4708   case AtomicExpr::AO__atomic_fetch_add:
4709   case AtomicExpr::AO__atomic_fetch_sub:
4710   case AtomicExpr::AO__atomic_add_fetch:
4711   case AtomicExpr::AO__atomic_sub_fetch:
4712     IsAddSub = true;
4713     LLVM_FALLTHROUGH;
4714   case AtomicExpr::AO__c11_atomic_fetch_and:
4715   case AtomicExpr::AO__c11_atomic_fetch_or:
4716   case AtomicExpr::AO__c11_atomic_fetch_xor:
4717   case AtomicExpr::AO__opencl_atomic_fetch_and:
4718   case AtomicExpr::AO__opencl_atomic_fetch_or:
4719   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4720   case AtomicExpr::AO__atomic_fetch_and:
4721   case AtomicExpr::AO__atomic_fetch_or:
4722   case AtomicExpr::AO__atomic_fetch_xor:
4723   case AtomicExpr::AO__atomic_fetch_nand:
4724   case AtomicExpr::AO__atomic_and_fetch:
4725   case AtomicExpr::AO__atomic_or_fetch:
4726   case AtomicExpr::AO__atomic_xor_fetch:
4727   case AtomicExpr::AO__atomic_nand_fetch:
4728   case AtomicExpr::AO__c11_atomic_fetch_min:
4729   case AtomicExpr::AO__c11_atomic_fetch_max:
4730   case AtomicExpr::AO__opencl_atomic_fetch_min:
4731   case AtomicExpr::AO__opencl_atomic_fetch_max:
4732   case AtomicExpr::AO__atomic_min_fetch:
4733   case AtomicExpr::AO__atomic_max_fetch:
4734   case AtomicExpr::AO__atomic_fetch_min:
4735   case AtomicExpr::AO__atomic_fetch_max:
4736     Form = Arithmetic;
4737     break;
4738 
4739   case AtomicExpr::AO__c11_atomic_exchange:
4740   case AtomicExpr::AO__opencl_atomic_exchange:
4741   case AtomicExpr::AO__atomic_exchange_n:
4742     Form = Xchg;
4743     break;
4744 
4745   case AtomicExpr::AO__atomic_exchange:
4746     Form = GNUXchg;
4747     break;
4748 
4749   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4750   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4751   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4752   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4753     Form = C11CmpXchg;
4754     break;
4755 
4756   case AtomicExpr::AO__atomic_compare_exchange:
4757   case AtomicExpr::AO__atomic_compare_exchange_n:
4758     Form = GNUCmpXchg;
4759     break;
4760   }
4761 
4762   unsigned AdjustedNumArgs = NumArgs[Form];
4763   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4764     ++AdjustedNumArgs;
4765   // Check we have the right number of arguments.
4766   if (Args.size() < AdjustedNumArgs) {
4767     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4768         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4769         << ExprRange;
4770     return ExprError();
4771   } else if (Args.size() > AdjustedNumArgs) {
4772     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4773          diag::err_typecheck_call_too_many_args)
4774         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4775         << ExprRange;
4776     return ExprError();
4777   }
4778 
4779   // Inspect the first argument of the atomic operation.
4780   Expr *Ptr = Args[0];
4781   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4782   if (ConvertedPtr.isInvalid())
4783     return ExprError();
4784 
4785   Ptr = ConvertedPtr.get();
4786   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4787   if (!pointerType) {
4788     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4789         << Ptr->getType() << Ptr->getSourceRange();
4790     return ExprError();
4791   }
4792 
4793   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4794   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4795   QualType ValType = AtomTy; // 'C'
4796   if (IsC11) {
4797     if (!AtomTy->isAtomicType()) {
4798       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4799           << Ptr->getType() << Ptr->getSourceRange();
4800       return ExprError();
4801     }
4802     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4803         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4804       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4805           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4806           << Ptr->getSourceRange();
4807       return ExprError();
4808     }
4809     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4810   } else if (Form != Load && Form != LoadCopy) {
4811     if (ValType.isConstQualified()) {
4812       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4813           << Ptr->getType() << Ptr->getSourceRange();
4814       return ExprError();
4815     }
4816   }
4817 
4818   // For an arithmetic operation, the implied arithmetic must be well-formed.
4819   if (Form == Arithmetic) {
4820     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4821     if (IsAddSub && !ValType->isIntegerType()
4822         && !ValType->isPointerType()) {
4823       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4824           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4825       return ExprError();
4826     }
4827     if (!IsAddSub && !ValType->isIntegerType()) {
4828       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4829           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4830       return ExprError();
4831     }
4832     if (IsC11 && ValType->isPointerType() &&
4833         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4834                             diag::err_incomplete_type)) {
4835       return ExprError();
4836     }
4837   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4838     // For __atomic_*_n operations, the value type must be a scalar integral or
4839     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4840     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4841         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4842     return ExprError();
4843   }
4844 
4845   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4846       !AtomTy->isScalarType()) {
4847     // For GNU atomics, require a trivially-copyable type. This is not part of
4848     // the GNU atomics specification, but we enforce it for sanity.
4849     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4850         << Ptr->getType() << Ptr->getSourceRange();
4851     return ExprError();
4852   }
4853 
4854   switch (ValType.getObjCLifetime()) {
4855   case Qualifiers::OCL_None:
4856   case Qualifiers::OCL_ExplicitNone:
4857     // okay
4858     break;
4859 
4860   case Qualifiers::OCL_Weak:
4861   case Qualifiers::OCL_Strong:
4862   case Qualifiers::OCL_Autoreleasing:
4863     // FIXME: Can this happen? By this point, ValType should be known
4864     // to be trivially copyable.
4865     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4866         << ValType << Ptr->getSourceRange();
4867     return ExprError();
4868   }
4869 
4870   // All atomic operations have an overload which takes a pointer to a volatile
4871   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4872   // into the result or the other operands. Similarly atomic_load takes a
4873   // pointer to a const 'A'.
4874   ValType.removeLocalVolatile();
4875   ValType.removeLocalConst();
4876   QualType ResultType = ValType;
4877   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4878       Form == Init)
4879     ResultType = Context.VoidTy;
4880   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4881     ResultType = Context.BoolTy;
4882 
4883   // The type of a parameter passed 'by value'. In the GNU atomics, such
4884   // arguments are actually passed as pointers.
4885   QualType ByValType = ValType; // 'CP'
4886   bool IsPassedByAddress = false;
4887   if (!IsC11 && !IsN) {
4888     ByValType = Ptr->getType();
4889     IsPassedByAddress = true;
4890   }
4891 
4892   SmallVector<Expr *, 5> APIOrderedArgs;
4893   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4894     APIOrderedArgs.push_back(Args[0]);
4895     switch (Form) {
4896     case Init:
4897     case Load:
4898       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4899       break;
4900     case LoadCopy:
4901     case Copy:
4902     case Arithmetic:
4903     case Xchg:
4904       APIOrderedArgs.push_back(Args[2]); // Val1
4905       APIOrderedArgs.push_back(Args[1]); // Order
4906       break;
4907     case GNUXchg:
4908       APIOrderedArgs.push_back(Args[2]); // Val1
4909       APIOrderedArgs.push_back(Args[3]); // Val2
4910       APIOrderedArgs.push_back(Args[1]); // Order
4911       break;
4912     case C11CmpXchg:
4913       APIOrderedArgs.push_back(Args[2]); // Val1
4914       APIOrderedArgs.push_back(Args[4]); // Val2
4915       APIOrderedArgs.push_back(Args[1]); // Order
4916       APIOrderedArgs.push_back(Args[3]); // OrderFail
4917       break;
4918     case GNUCmpXchg:
4919       APIOrderedArgs.push_back(Args[2]); // Val1
4920       APIOrderedArgs.push_back(Args[4]); // Val2
4921       APIOrderedArgs.push_back(Args[5]); // Weak
4922       APIOrderedArgs.push_back(Args[1]); // Order
4923       APIOrderedArgs.push_back(Args[3]); // OrderFail
4924       break;
4925     }
4926   } else
4927     APIOrderedArgs.append(Args.begin(), Args.end());
4928 
4929   // The first argument's non-CV pointer type is used to deduce the type of
4930   // subsequent arguments, except for:
4931   //  - weak flag (always converted to bool)
4932   //  - memory order (always converted to int)
4933   //  - scope  (always converted to int)
4934   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4935     QualType Ty;
4936     if (i < NumVals[Form] + 1) {
4937       switch (i) {
4938       case 0:
4939         // The first argument is always a pointer. It has a fixed type.
4940         // It is always dereferenced, a nullptr is undefined.
4941         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4942         // Nothing else to do: we already know all we want about this pointer.
4943         continue;
4944       case 1:
4945         // The second argument is the non-atomic operand. For arithmetic, this
4946         // is always passed by value, and for a compare_exchange it is always
4947         // passed by address. For the rest, GNU uses by-address and C11 uses
4948         // by-value.
4949         assert(Form != Load);
4950         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4951           Ty = ValType;
4952         else if (Form == Copy || Form == Xchg) {
4953           if (IsPassedByAddress) {
4954             // The value pointer is always dereferenced, a nullptr is undefined.
4955             CheckNonNullArgument(*this, APIOrderedArgs[i],
4956                                  ExprRange.getBegin());
4957           }
4958           Ty = ByValType;
4959         } else if (Form == Arithmetic)
4960           Ty = Context.getPointerDiffType();
4961         else {
4962           Expr *ValArg = APIOrderedArgs[i];
4963           // The value pointer is always dereferenced, a nullptr is undefined.
4964           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4965           LangAS AS = LangAS::Default;
4966           // Keep address space of non-atomic pointer type.
4967           if (const PointerType *PtrTy =
4968                   ValArg->getType()->getAs<PointerType>()) {
4969             AS = PtrTy->getPointeeType().getAddressSpace();
4970           }
4971           Ty = Context.getPointerType(
4972               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4973         }
4974         break;
4975       case 2:
4976         // The third argument to compare_exchange / GNU exchange is the desired
4977         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4978         if (IsPassedByAddress)
4979           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4980         Ty = ByValType;
4981         break;
4982       case 3:
4983         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4984         Ty = Context.BoolTy;
4985         break;
4986       }
4987     } else {
4988       // The order(s) and scope are always converted to int.
4989       Ty = Context.IntTy;
4990     }
4991 
4992     InitializedEntity Entity =
4993         InitializedEntity::InitializeParameter(Context, Ty, false);
4994     ExprResult Arg = APIOrderedArgs[i];
4995     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4996     if (Arg.isInvalid())
4997       return true;
4998     APIOrderedArgs[i] = Arg.get();
4999   }
5000 
5001   // Permute the arguments into a 'consistent' order.
5002   SmallVector<Expr*, 5> SubExprs;
5003   SubExprs.push_back(Ptr);
5004   switch (Form) {
5005   case Init:
5006     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5007     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5008     break;
5009   case Load:
5010     SubExprs.push_back(APIOrderedArgs[1]); // Order
5011     break;
5012   case LoadCopy:
5013   case Copy:
5014   case Arithmetic:
5015   case Xchg:
5016     SubExprs.push_back(APIOrderedArgs[2]); // Order
5017     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5018     break;
5019   case GNUXchg:
5020     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5021     SubExprs.push_back(APIOrderedArgs[3]); // Order
5022     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5023     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5024     break;
5025   case C11CmpXchg:
5026     SubExprs.push_back(APIOrderedArgs[3]); // Order
5027     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5028     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5029     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5030     break;
5031   case GNUCmpXchg:
5032     SubExprs.push_back(APIOrderedArgs[4]); // Order
5033     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5034     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5035     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5036     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5037     break;
5038   }
5039 
5040   if (SubExprs.size() >= 2 && Form != Init) {
5041     if (Optional<llvm::APSInt> Result =
5042             SubExprs[1]->getIntegerConstantExpr(Context))
5043       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5044         Diag(SubExprs[1]->getBeginLoc(),
5045              diag::warn_atomic_op_has_invalid_memory_order)
5046             << SubExprs[1]->getSourceRange();
5047   }
5048 
5049   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5050     auto *Scope = Args[Args.size() - 1];
5051     if (Optional<llvm::APSInt> Result =
5052             Scope->getIntegerConstantExpr(Context)) {
5053       if (!ScopeModel->isValid(Result->getZExtValue()))
5054         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5055             << Scope->getSourceRange();
5056     }
5057     SubExprs.push_back(Scope);
5058   }
5059 
5060   AtomicExpr *AE = new (Context)
5061       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5062 
5063   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5064        Op == AtomicExpr::AO__c11_atomic_store ||
5065        Op == AtomicExpr::AO__opencl_atomic_load ||
5066        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5067       Context.AtomicUsesUnsupportedLibcall(AE))
5068     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5069         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5070              Op == AtomicExpr::AO__opencl_atomic_load)
5071                 ? 0
5072                 : 1);
5073 
5074   if (ValType->isExtIntType()) {
5075     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5076     return ExprError();
5077   }
5078 
5079   return AE;
5080 }
5081 
5082 /// checkBuiltinArgument - Given a call to a builtin function, perform
5083 /// normal type-checking on the given argument, updating the call in
5084 /// place.  This is useful when a builtin function requires custom
5085 /// type-checking for some of its arguments but not necessarily all of
5086 /// them.
5087 ///
5088 /// Returns true on error.
5089 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5090   FunctionDecl *Fn = E->getDirectCallee();
5091   assert(Fn && "builtin call without direct callee!");
5092 
5093   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5094   InitializedEntity Entity =
5095     InitializedEntity::InitializeParameter(S.Context, Param);
5096 
5097   ExprResult Arg = E->getArg(0);
5098   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5099   if (Arg.isInvalid())
5100     return true;
5101 
5102   E->setArg(ArgIndex, Arg.get());
5103   return false;
5104 }
5105 
5106 /// We have a call to a function like __sync_fetch_and_add, which is an
5107 /// overloaded function based on the pointer type of its first argument.
5108 /// The main BuildCallExpr routines have already promoted the types of
5109 /// arguments because all of these calls are prototyped as void(...).
5110 ///
5111 /// This function goes through and does final semantic checking for these
5112 /// builtins, as well as generating any warnings.
5113 ExprResult
5114 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5115   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5116   Expr *Callee = TheCall->getCallee();
5117   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5118   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5119 
5120   // Ensure that we have at least one argument to do type inference from.
5121   if (TheCall->getNumArgs() < 1) {
5122     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5123         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5124     return ExprError();
5125   }
5126 
5127   // Inspect the first argument of the atomic builtin.  This should always be
5128   // a pointer type, whose element is an integral scalar or pointer type.
5129   // Because it is a pointer type, we don't have to worry about any implicit
5130   // casts here.
5131   // FIXME: We don't allow floating point scalars as input.
5132   Expr *FirstArg = TheCall->getArg(0);
5133   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5134   if (FirstArgResult.isInvalid())
5135     return ExprError();
5136   FirstArg = FirstArgResult.get();
5137   TheCall->setArg(0, FirstArg);
5138 
5139   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5140   if (!pointerType) {
5141     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5142         << FirstArg->getType() << FirstArg->getSourceRange();
5143     return ExprError();
5144   }
5145 
5146   QualType ValType = pointerType->getPointeeType();
5147   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5148       !ValType->isBlockPointerType()) {
5149     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5150         << FirstArg->getType() << FirstArg->getSourceRange();
5151     return ExprError();
5152   }
5153 
5154   if (ValType.isConstQualified()) {
5155     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5156         << FirstArg->getType() << FirstArg->getSourceRange();
5157     return ExprError();
5158   }
5159 
5160   switch (ValType.getObjCLifetime()) {
5161   case Qualifiers::OCL_None:
5162   case Qualifiers::OCL_ExplicitNone:
5163     // okay
5164     break;
5165 
5166   case Qualifiers::OCL_Weak:
5167   case Qualifiers::OCL_Strong:
5168   case Qualifiers::OCL_Autoreleasing:
5169     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5170         << ValType << FirstArg->getSourceRange();
5171     return ExprError();
5172   }
5173 
5174   // Strip any qualifiers off ValType.
5175   ValType = ValType.getUnqualifiedType();
5176 
5177   // The majority of builtins return a value, but a few have special return
5178   // types, so allow them to override appropriately below.
5179   QualType ResultType = ValType;
5180 
5181   // We need to figure out which concrete builtin this maps onto.  For example,
5182   // __sync_fetch_and_add with a 2 byte object turns into
5183   // __sync_fetch_and_add_2.
5184 #define BUILTIN_ROW(x) \
5185   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5186     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5187 
5188   static const unsigned BuiltinIndices[][5] = {
5189     BUILTIN_ROW(__sync_fetch_and_add),
5190     BUILTIN_ROW(__sync_fetch_and_sub),
5191     BUILTIN_ROW(__sync_fetch_and_or),
5192     BUILTIN_ROW(__sync_fetch_and_and),
5193     BUILTIN_ROW(__sync_fetch_and_xor),
5194     BUILTIN_ROW(__sync_fetch_and_nand),
5195 
5196     BUILTIN_ROW(__sync_add_and_fetch),
5197     BUILTIN_ROW(__sync_sub_and_fetch),
5198     BUILTIN_ROW(__sync_and_and_fetch),
5199     BUILTIN_ROW(__sync_or_and_fetch),
5200     BUILTIN_ROW(__sync_xor_and_fetch),
5201     BUILTIN_ROW(__sync_nand_and_fetch),
5202 
5203     BUILTIN_ROW(__sync_val_compare_and_swap),
5204     BUILTIN_ROW(__sync_bool_compare_and_swap),
5205     BUILTIN_ROW(__sync_lock_test_and_set),
5206     BUILTIN_ROW(__sync_lock_release),
5207     BUILTIN_ROW(__sync_swap)
5208   };
5209 #undef BUILTIN_ROW
5210 
5211   // Determine the index of the size.
5212   unsigned SizeIndex;
5213   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5214   case 1: SizeIndex = 0; break;
5215   case 2: SizeIndex = 1; break;
5216   case 4: SizeIndex = 2; break;
5217   case 8: SizeIndex = 3; break;
5218   case 16: SizeIndex = 4; break;
5219   default:
5220     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5221         << FirstArg->getType() << FirstArg->getSourceRange();
5222     return ExprError();
5223   }
5224 
5225   // Each of these builtins has one pointer argument, followed by some number of
5226   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5227   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5228   // as the number of fixed args.
5229   unsigned BuiltinID = FDecl->getBuiltinID();
5230   unsigned BuiltinIndex, NumFixed = 1;
5231   bool WarnAboutSemanticsChange = false;
5232   switch (BuiltinID) {
5233   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5234   case Builtin::BI__sync_fetch_and_add:
5235   case Builtin::BI__sync_fetch_and_add_1:
5236   case Builtin::BI__sync_fetch_and_add_2:
5237   case Builtin::BI__sync_fetch_and_add_4:
5238   case Builtin::BI__sync_fetch_and_add_8:
5239   case Builtin::BI__sync_fetch_and_add_16:
5240     BuiltinIndex = 0;
5241     break;
5242 
5243   case Builtin::BI__sync_fetch_and_sub:
5244   case Builtin::BI__sync_fetch_and_sub_1:
5245   case Builtin::BI__sync_fetch_and_sub_2:
5246   case Builtin::BI__sync_fetch_and_sub_4:
5247   case Builtin::BI__sync_fetch_and_sub_8:
5248   case Builtin::BI__sync_fetch_and_sub_16:
5249     BuiltinIndex = 1;
5250     break;
5251 
5252   case Builtin::BI__sync_fetch_and_or:
5253   case Builtin::BI__sync_fetch_and_or_1:
5254   case Builtin::BI__sync_fetch_and_or_2:
5255   case Builtin::BI__sync_fetch_and_or_4:
5256   case Builtin::BI__sync_fetch_and_or_8:
5257   case Builtin::BI__sync_fetch_and_or_16:
5258     BuiltinIndex = 2;
5259     break;
5260 
5261   case Builtin::BI__sync_fetch_and_and:
5262   case Builtin::BI__sync_fetch_and_and_1:
5263   case Builtin::BI__sync_fetch_and_and_2:
5264   case Builtin::BI__sync_fetch_and_and_4:
5265   case Builtin::BI__sync_fetch_and_and_8:
5266   case Builtin::BI__sync_fetch_and_and_16:
5267     BuiltinIndex = 3;
5268     break;
5269 
5270   case Builtin::BI__sync_fetch_and_xor:
5271   case Builtin::BI__sync_fetch_and_xor_1:
5272   case Builtin::BI__sync_fetch_and_xor_2:
5273   case Builtin::BI__sync_fetch_and_xor_4:
5274   case Builtin::BI__sync_fetch_and_xor_8:
5275   case Builtin::BI__sync_fetch_and_xor_16:
5276     BuiltinIndex = 4;
5277     break;
5278 
5279   case Builtin::BI__sync_fetch_and_nand:
5280   case Builtin::BI__sync_fetch_and_nand_1:
5281   case Builtin::BI__sync_fetch_and_nand_2:
5282   case Builtin::BI__sync_fetch_and_nand_4:
5283   case Builtin::BI__sync_fetch_and_nand_8:
5284   case Builtin::BI__sync_fetch_and_nand_16:
5285     BuiltinIndex = 5;
5286     WarnAboutSemanticsChange = true;
5287     break;
5288 
5289   case Builtin::BI__sync_add_and_fetch:
5290   case Builtin::BI__sync_add_and_fetch_1:
5291   case Builtin::BI__sync_add_and_fetch_2:
5292   case Builtin::BI__sync_add_and_fetch_4:
5293   case Builtin::BI__sync_add_and_fetch_8:
5294   case Builtin::BI__sync_add_and_fetch_16:
5295     BuiltinIndex = 6;
5296     break;
5297 
5298   case Builtin::BI__sync_sub_and_fetch:
5299   case Builtin::BI__sync_sub_and_fetch_1:
5300   case Builtin::BI__sync_sub_and_fetch_2:
5301   case Builtin::BI__sync_sub_and_fetch_4:
5302   case Builtin::BI__sync_sub_and_fetch_8:
5303   case Builtin::BI__sync_sub_and_fetch_16:
5304     BuiltinIndex = 7;
5305     break;
5306 
5307   case Builtin::BI__sync_and_and_fetch:
5308   case Builtin::BI__sync_and_and_fetch_1:
5309   case Builtin::BI__sync_and_and_fetch_2:
5310   case Builtin::BI__sync_and_and_fetch_4:
5311   case Builtin::BI__sync_and_and_fetch_8:
5312   case Builtin::BI__sync_and_and_fetch_16:
5313     BuiltinIndex = 8;
5314     break;
5315 
5316   case Builtin::BI__sync_or_and_fetch:
5317   case Builtin::BI__sync_or_and_fetch_1:
5318   case Builtin::BI__sync_or_and_fetch_2:
5319   case Builtin::BI__sync_or_and_fetch_4:
5320   case Builtin::BI__sync_or_and_fetch_8:
5321   case Builtin::BI__sync_or_and_fetch_16:
5322     BuiltinIndex = 9;
5323     break;
5324 
5325   case Builtin::BI__sync_xor_and_fetch:
5326   case Builtin::BI__sync_xor_and_fetch_1:
5327   case Builtin::BI__sync_xor_and_fetch_2:
5328   case Builtin::BI__sync_xor_and_fetch_4:
5329   case Builtin::BI__sync_xor_and_fetch_8:
5330   case Builtin::BI__sync_xor_and_fetch_16:
5331     BuiltinIndex = 10;
5332     break;
5333 
5334   case Builtin::BI__sync_nand_and_fetch:
5335   case Builtin::BI__sync_nand_and_fetch_1:
5336   case Builtin::BI__sync_nand_and_fetch_2:
5337   case Builtin::BI__sync_nand_and_fetch_4:
5338   case Builtin::BI__sync_nand_and_fetch_8:
5339   case Builtin::BI__sync_nand_and_fetch_16:
5340     BuiltinIndex = 11;
5341     WarnAboutSemanticsChange = true;
5342     break;
5343 
5344   case Builtin::BI__sync_val_compare_and_swap:
5345   case Builtin::BI__sync_val_compare_and_swap_1:
5346   case Builtin::BI__sync_val_compare_and_swap_2:
5347   case Builtin::BI__sync_val_compare_and_swap_4:
5348   case Builtin::BI__sync_val_compare_and_swap_8:
5349   case Builtin::BI__sync_val_compare_and_swap_16:
5350     BuiltinIndex = 12;
5351     NumFixed = 2;
5352     break;
5353 
5354   case Builtin::BI__sync_bool_compare_and_swap:
5355   case Builtin::BI__sync_bool_compare_and_swap_1:
5356   case Builtin::BI__sync_bool_compare_and_swap_2:
5357   case Builtin::BI__sync_bool_compare_and_swap_4:
5358   case Builtin::BI__sync_bool_compare_and_swap_8:
5359   case Builtin::BI__sync_bool_compare_and_swap_16:
5360     BuiltinIndex = 13;
5361     NumFixed = 2;
5362     ResultType = Context.BoolTy;
5363     break;
5364 
5365   case Builtin::BI__sync_lock_test_and_set:
5366   case Builtin::BI__sync_lock_test_and_set_1:
5367   case Builtin::BI__sync_lock_test_and_set_2:
5368   case Builtin::BI__sync_lock_test_and_set_4:
5369   case Builtin::BI__sync_lock_test_and_set_8:
5370   case Builtin::BI__sync_lock_test_and_set_16:
5371     BuiltinIndex = 14;
5372     break;
5373 
5374   case Builtin::BI__sync_lock_release:
5375   case Builtin::BI__sync_lock_release_1:
5376   case Builtin::BI__sync_lock_release_2:
5377   case Builtin::BI__sync_lock_release_4:
5378   case Builtin::BI__sync_lock_release_8:
5379   case Builtin::BI__sync_lock_release_16:
5380     BuiltinIndex = 15;
5381     NumFixed = 0;
5382     ResultType = Context.VoidTy;
5383     break;
5384 
5385   case Builtin::BI__sync_swap:
5386   case Builtin::BI__sync_swap_1:
5387   case Builtin::BI__sync_swap_2:
5388   case Builtin::BI__sync_swap_4:
5389   case Builtin::BI__sync_swap_8:
5390   case Builtin::BI__sync_swap_16:
5391     BuiltinIndex = 16;
5392     break;
5393   }
5394 
5395   // Now that we know how many fixed arguments we expect, first check that we
5396   // have at least that many.
5397   if (TheCall->getNumArgs() < 1+NumFixed) {
5398     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5399         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5400         << Callee->getSourceRange();
5401     return ExprError();
5402   }
5403 
5404   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5405       << Callee->getSourceRange();
5406 
5407   if (WarnAboutSemanticsChange) {
5408     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5409         << Callee->getSourceRange();
5410   }
5411 
5412   // Get the decl for the concrete builtin from this, we can tell what the
5413   // concrete integer type we should convert to is.
5414   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5415   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5416   FunctionDecl *NewBuiltinDecl;
5417   if (NewBuiltinID == BuiltinID)
5418     NewBuiltinDecl = FDecl;
5419   else {
5420     // Perform builtin lookup to avoid redeclaring it.
5421     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5422     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5423     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5424     assert(Res.getFoundDecl());
5425     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5426     if (!NewBuiltinDecl)
5427       return ExprError();
5428   }
5429 
5430   // The first argument --- the pointer --- has a fixed type; we
5431   // deduce the types of the rest of the arguments accordingly.  Walk
5432   // the remaining arguments, converting them to the deduced value type.
5433   for (unsigned i = 0; i != NumFixed; ++i) {
5434     ExprResult Arg = TheCall->getArg(i+1);
5435 
5436     // GCC does an implicit conversion to the pointer or integer ValType.  This
5437     // can fail in some cases (1i -> int**), check for this error case now.
5438     // Initialize the argument.
5439     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5440                                                    ValType, /*consume*/ false);
5441     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5442     if (Arg.isInvalid())
5443       return ExprError();
5444 
5445     // Okay, we have something that *can* be converted to the right type.  Check
5446     // to see if there is a potentially weird extension going on here.  This can
5447     // happen when you do an atomic operation on something like an char* and
5448     // pass in 42.  The 42 gets converted to char.  This is even more strange
5449     // for things like 45.123 -> char, etc.
5450     // FIXME: Do this check.
5451     TheCall->setArg(i+1, Arg.get());
5452   }
5453 
5454   // Create a new DeclRefExpr to refer to the new decl.
5455   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5456       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5457       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5458       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5459 
5460   // Set the callee in the CallExpr.
5461   // FIXME: This loses syntactic information.
5462   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5463   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5464                                               CK_BuiltinFnToFnPtr);
5465   TheCall->setCallee(PromotedCall.get());
5466 
5467   // Change the result type of the call to match the original value type. This
5468   // is arbitrary, but the codegen for these builtins ins design to handle it
5469   // gracefully.
5470   TheCall->setType(ResultType);
5471 
5472   // Prohibit use of _ExtInt with atomic builtins.
5473   // The arguments would have already been converted to the first argument's
5474   // type, so only need to check the first argument.
5475   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5476   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5477     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5478     return ExprError();
5479   }
5480 
5481   return TheCallResult;
5482 }
5483 
5484 /// SemaBuiltinNontemporalOverloaded - We have a call to
5485 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5486 /// overloaded function based on the pointer type of its last argument.
5487 ///
5488 /// This function goes through and does final semantic checking for these
5489 /// builtins.
5490 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5491   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5492   DeclRefExpr *DRE =
5493       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5494   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5495   unsigned BuiltinID = FDecl->getBuiltinID();
5496   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5497           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5498          "Unexpected nontemporal load/store builtin!");
5499   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5500   unsigned numArgs = isStore ? 2 : 1;
5501 
5502   // Ensure that we have the proper number of arguments.
5503   if (checkArgCount(*this, TheCall, numArgs))
5504     return ExprError();
5505 
5506   // Inspect the last argument of the nontemporal builtin.  This should always
5507   // be a pointer type, from which we imply the type of the memory access.
5508   // Because it is a pointer type, we don't have to worry about any implicit
5509   // casts here.
5510   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5511   ExprResult PointerArgResult =
5512       DefaultFunctionArrayLvalueConversion(PointerArg);
5513 
5514   if (PointerArgResult.isInvalid())
5515     return ExprError();
5516   PointerArg = PointerArgResult.get();
5517   TheCall->setArg(numArgs - 1, PointerArg);
5518 
5519   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5520   if (!pointerType) {
5521     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5522         << PointerArg->getType() << PointerArg->getSourceRange();
5523     return ExprError();
5524   }
5525 
5526   QualType ValType = pointerType->getPointeeType();
5527 
5528   // Strip any qualifiers off ValType.
5529   ValType = ValType.getUnqualifiedType();
5530   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5531       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5532       !ValType->isVectorType()) {
5533     Diag(DRE->getBeginLoc(),
5534          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5535         << PointerArg->getType() << PointerArg->getSourceRange();
5536     return ExprError();
5537   }
5538 
5539   if (!isStore) {
5540     TheCall->setType(ValType);
5541     return TheCallResult;
5542   }
5543 
5544   ExprResult ValArg = TheCall->getArg(0);
5545   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5546       Context, ValType, /*consume*/ false);
5547   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5548   if (ValArg.isInvalid())
5549     return ExprError();
5550 
5551   TheCall->setArg(0, ValArg.get());
5552   TheCall->setType(Context.VoidTy);
5553   return TheCallResult;
5554 }
5555 
5556 /// CheckObjCString - Checks that the argument to the builtin
5557 /// CFString constructor is correct
5558 /// Note: It might also make sense to do the UTF-16 conversion here (would
5559 /// simplify the backend).
5560 bool Sema::CheckObjCString(Expr *Arg) {
5561   Arg = Arg->IgnoreParenCasts();
5562   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5563 
5564   if (!Literal || !Literal->isAscii()) {
5565     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5566         << Arg->getSourceRange();
5567     return true;
5568   }
5569 
5570   if (Literal->containsNonAsciiOrNull()) {
5571     StringRef String = Literal->getString();
5572     unsigned NumBytes = String.size();
5573     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5574     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5575     llvm::UTF16 *ToPtr = &ToBuf[0];
5576 
5577     llvm::ConversionResult Result =
5578         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5579                                  ToPtr + NumBytes, llvm::strictConversion);
5580     // Check for conversion failure.
5581     if (Result != llvm::conversionOK)
5582       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5583           << Arg->getSourceRange();
5584   }
5585   return false;
5586 }
5587 
5588 /// CheckObjCString - Checks that the format string argument to the os_log()
5589 /// and os_trace() functions is correct, and converts it to const char *.
5590 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5591   Arg = Arg->IgnoreParenCasts();
5592   auto *Literal = dyn_cast<StringLiteral>(Arg);
5593   if (!Literal) {
5594     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5595       Literal = ObjcLiteral->getString();
5596     }
5597   }
5598 
5599   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5600     return ExprError(
5601         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5602         << Arg->getSourceRange());
5603   }
5604 
5605   ExprResult Result(Literal);
5606   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5607   InitializedEntity Entity =
5608       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5609   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5610   return Result;
5611 }
5612 
5613 /// Check that the user is calling the appropriate va_start builtin for the
5614 /// target and calling convention.
5615 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5616   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5617   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5618   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5619                     TT.getArch() == llvm::Triple::aarch64_32);
5620   bool IsWindows = TT.isOSWindows();
5621   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5622   if (IsX64 || IsAArch64) {
5623     CallingConv CC = CC_C;
5624     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5625       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5626     if (IsMSVAStart) {
5627       // Don't allow this in System V ABI functions.
5628       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5629         return S.Diag(Fn->getBeginLoc(),
5630                       diag::err_ms_va_start_used_in_sysv_function);
5631     } else {
5632       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5633       // On x64 Windows, don't allow this in System V ABI functions.
5634       // (Yes, that means there's no corresponding way to support variadic
5635       // System V ABI functions on Windows.)
5636       if ((IsWindows && CC == CC_X86_64SysV) ||
5637           (!IsWindows && CC == CC_Win64))
5638         return S.Diag(Fn->getBeginLoc(),
5639                       diag::err_va_start_used_in_wrong_abi_function)
5640                << !IsWindows;
5641     }
5642     return false;
5643   }
5644 
5645   if (IsMSVAStart)
5646     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5647   return false;
5648 }
5649 
5650 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5651                                              ParmVarDecl **LastParam = nullptr) {
5652   // Determine whether the current function, block, or obj-c method is variadic
5653   // and get its parameter list.
5654   bool IsVariadic = false;
5655   ArrayRef<ParmVarDecl *> Params;
5656   DeclContext *Caller = S.CurContext;
5657   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5658     IsVariadic = Block->isVariadic();
5659     Params = Block->parameters();
5660   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5661     IsVariadic = FD->isVariadic();
5662     Params = FD->parameters();
5663   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5664     IsVariadic = MD->isVariadic();
5665     // FIXME: This isn't correct for methods (results in bogus warning).
5666     Params = MD->parameters();
5667   } else if (isa<CapturedDecl>(Caller)) {
5668     // We don't support va_start in a CapturedDecl.
5669     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5670     return true;
5671   } else {
5672     // This must be some other declcontext that parses exprs.
5673     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5674     return true;
5675   }
5676 
5677   if (!IsVariadic) {
5678     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5679     return true;
5680   }
5681 
5682   if (LastParam)
5683     *LastParam = Params.empty() ? nullptr : Params.back();
5684 
5685   return false;
5686 }
5687 
5688 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5689 /// for validity.  Emit an error and return true on failure; return false
5690 /// on success.
5691 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5692   Expr *Fn = TheCall->getCallee();
5693 
5694   if (checkVAStartABI(*this, BuiltinID, Fn))
5695     return true;
5696 
5697   if (checkArgCount(*this, TheCall, 2))
5698     return true;
5699 
5700   // Type-check the first argument normally.
5701   if (checkBuiltinArgument(*this, TheCall, 0))
5702     return true;
5703 
5704   // Check that the current function is variadic, and get its last parameter.
5705   ParmVarDecl *LastParam;
5706   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5707     return true;
5708 
5709   // Verify that the second argument to the builtin is the last argument of the
5710   // current function or method.
5711   bool SecondArgIsLastNamedArgument = false;
5712   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5713 
5714   // These are valid if SecondArgIsLastNamedArgument is false after the next
5715   // block.
5716   QualType Type;
5717   SourceLocation ParamLoc;
5718   bool IsCRegister = false;
5719 
5720   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5721     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5722       SecondArgIsLastNamedArgument = PV == LastParam;
5723 
5724       Type = PV->getType();
5725       ParamLoc = PV->getLocation();
5726       IsCRegister =
5727           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5728     }
5729   }
5730 
5731   if (!SecondArgIsLastNamedArgument)
5732     Diag(TheCall->getArg(1)->getBeginLoc(),
5733          diag::warn_second_arg_of_va_start_not_last_named_param);
5734   else if (IsCRegister || Type->isReferenceType() ||
5735            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5736              // Promotable integers are UB, but enumerations need a bit of
5737              // extra checking to see what their promotable type actually is.
5738              if (!Type->isPromotableIntegerType())
5739                return false;
5740              if (!Type->isEnumeralType())
5741                return true;
5742              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5743              return !(ED &&
5744                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5745            }()) {
5746     unsigned Reason = 0;
5747     if (Type->isReferenceType())  Reason = 1;
5748     else if (IsCRegister)         Reason = 2;
5749     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5750     Diag(ParamLoc, diag::note_parameter_type) << Type;
5751   }
5752 
5753   TheCall->setType(Context.VoidTy);
5754   return false;
5755 }
5756 
5757 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5758   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5759   //                 const char *named_addr);
5760 
5761   Expr *Func = Call->getCallee();
5762 
5763   if (Call->getNumArgs() < 3)
5764     return Diag(Call->getEndLoc(),
5765                 diag::err_typecheck_call_too_few_args_at_least)
5766            << 0 /*function call*/ << 3 << Call->getNumArgs();
5767 
5768   // Type-check the first argument normally.
5769   if (checkBuiltinArgument(*this, Call, 0))
5770     return true;
5771 
5772   // Check that the current function is variadic.
5773   if (checkVAStartIsInVariadicFunction(*this, Func))
5774     return true;
5775 
5776   // __va_start on Windows does not validate the parameter qualifiers
5777 
5778   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5779   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5780 
5781   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5782   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5783 
5784   const QualType &ConstCharPtrTy =
5785       Context.getPointerType(Context.CharTy.withConst());
5786   if (!Arg1Ty->isPointerType() ||
5787       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5788     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5789         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5790         << 0                                      /* qualifier difference */
5791         << 3                                      /* parameter mismatch */
5792         << 2 << Arg1->getType() << ConstCharPtrTy;
5793 
5794   const QualType SizeTy = Context.getSizeType();
5795   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5796     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5797         << Arg2->getType() << SizeTy << 1 /* different class */
5798         << 0                              /* qualifier difference */
5799         << 3                              /* parameter mismatch */
5800         << 3 << Arg2->getType() << SizeTy;
5801 
5802   return false;
5803 }
5804 
5805 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5806 /// friends.  This is declared to take (...), so we have to check everything.
5807 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5808   if (checkArgCount(*this, TheCall, 2))
5809     return true;
5810 
5811   ExprResult OrigArg0 = TheCall->getArg(0);
5812   ExprResult OrigArg1 = TheCall->getArg(1);
5813 
5814   // Do standard promotions between the two arguments, returning their common
5815   // type.
5816   QualType Res = UsualArithmeticConversions(
5817       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5818   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5819     return true;
5820 
5821   // Make sure any conversions are pushed back into the call; this is
5822   // type safe since unordered compare builtins are declared as "_Bool
5823   // foo(...)".
5824   TheCall->setArg(0, OrigArg0.get());
5825   TheCall->setArg(1, OrigArg1.get());
5826 
5827   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5828     return false;
5829 
5830   // If the common type isn't a real floating type, then the arguments were
5831   // invalid for this operation.
5832   if (Res.isNull() || !Res->isRealFloatingType())
5833     return Diag(OrigArg0.get()->getBeginLoc(),
5834                 diag::err_typecheck_call_invalid_ordered_compare)
5835            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5836            << SourceRange(OrigArg0.get()->getBeginLoc(),
5837                           OrigArg1.get()->getEndLoc());
5838 
5839   return false;
5840 }
5841 
5842 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5843 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5844 /// to check everything. We expect the last argument to be a floating point
5845 /// value.
5846 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5847   if (checkArgCount(*this, TheCall, NumArgs))
5848     return true;
5849 
5850   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5851   // on all preceding parameters just being int.  Try all of those.
5852   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5853     Expr *Arg = TheCall->getArg(i);
5854 
5855     if (Arg->isTypeDependent())
5856       return false;
5857 
5858     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5859 
5860     if (Res.isInvalid())
5861       return true;
5862     TheCall->setArg(i, Res.get());
5863   }
5864 
5865   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5866 
5867   if (OrigArg->isTypeDependent())
5868     return false;
5869 
5870   // Usual Unary Conversions will convert half to float, which we want for
5871   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5872   // type how it is, but do normal L->Rvalue conversions.
5873   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5874     OrigArg = UsualUnaryConversions(OrigArg).get();
5875   else
5876     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5877   TheCall->setArg(NumArgs - 1, OrigArg);
5878 
5879   // This operation requires a non-_Complex floating-point number.
5880   if (!OrigArg->getType()->isRealFloatingType())
5881     return Diag(OrigArg->getBeginLoc(),
5882                 diag::err_typecheck_call_invalid_unary_fp)
5883            << OrigArg->getType() << OrigArg->getSourceRange();
5884 
5885   return false;
5886 }
5887 
5888 /// Perform semantic analysis for a call to __builtin_complex.
5889 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
5890   if (checkArgCount(*this, TheCall, 2))
5891     return true;
5892 
5893   bool Dependent = false;
5894   for (unsigned I = 0; I != 2; ++I) {
5895     Expr *Arg = TheCall->getArg(I);
5896     QualType T = Arg->getType();
5897     if (T->isDependentType()) {
5898       Dependent = true;
5899       continue;
5900     }
5901 
5902     // Despite supporting _Complex int, GCC requires a real floating point type
5903     // for the operands of __builtin_complex.
5904     if (!T->isRealFloatingType()) {
5905       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5906              << Arg->getType() << Arg->getSourceRange();
5907     }
5908 
5909     ExprResult Converted = DefaultLvalueConversion(Arg);
5910     if (Converted.isInvalid())
5911       return true;
5912     TheCall->setArg(I, Converted.get());
5913   }
5914 
5915   if (Dependent) {
5916     TheCall->setType(Context.DependentTy);
5917     return false;
5918   }
5919 
5920   Expr *Real = TheCall->getArg(0);
5921   Expr *Imag = TheCall->getArg(1);
5922   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5923     return Diag(Real->getBeginLoc(),
5924                 diag::err_typecheck_call_different_arg_types)
5925            << Real->getType() << Imag->getType()
5926            << Real->getSourceRange() << Imag->getSourceRange();
5927   }
5928 
5929   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
5930   // don't allow this builtin to form those types either.
5931   // FIXME: Should we allow these types?
5932   if (Real->getType()->isFloat16Type())
5933     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5934            << "_Float16";
5935   if (Real->getType()->isHalfType())
5936     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5937            << "half";
5938 
5939   TheCall->setType(Context.getComplexType(Real->getType()));
5940   return false;
5941 }
5942 
5943 // Customized Sema Checking for VSX builtins that have the following signature:
5944 // vector [...] builtinName(vector [...], vector [...], const int);
5945 // Which takes the same type of vectors (any legal vector type) for the first
5946 // two arguments and takes compile time constant for the third argument.
5947 // Example builtins are :
5948 // vector double vec_xxpermdi(vector double, vector double, int);
5949 // vector short vec_xxsldwi(vector short, vector short, int);
5950 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5951   unsigned ExpectedNumArgs = 3;
5952   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
5953     return true;
5954 
5955   // Check the third argument is a compile time constant
5956   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
5957     return Diag(TheCall->getBeginLoc(),
5958                 diag::err_vsx_builtin_nonconstant_argument)
5959            << 3 /* argument index */ << TheCall->getDirectCallee()
5960            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5961                           TheCall->getArg(2)->getEndLoc());
5962 
5963   QualType Arg1Ty = TheCall->getArg(0)->getType();
5964   QualType Arg2Ty = TheCall->getArg(1)->getType();
5965 
5966   // Check the type of argument 1 and argument 2 are vectors.
5967   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5968   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5969       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5970     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5971            << TheCall->getDirectCallee()
5972            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5973                           TheCall->getArg(1)->getEndLoc());
5974   }
5975 
5976   // Check the first two arguments are the same type.
5977   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5978     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5979            << TheCall->getDirectCallee()
5980            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5981                           TheCall->getArg(1)->getEndLoc());
5982   }
5983 
5984   // When default clang type checking is turned off and the customized type
5985   // checking is used, the returning type of the function must be explicitly
5986   // set. Otherwise it is _Bool by default.
5987   TheCall->setType(Arg1Ty);
5988 
5989   return false;
5990 }
5991 
5992 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5993 // This is declared to take (...), so we have to check everything.
5994 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5995   if (TheCall->getNumArgs() < 2)
5996     return ExprError(Diag(TheCall->getEndLoc(),
5997                           diag::err_typecheck_call_too_few_args_at_least)
5998                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5999                      << TheCall->getSourceRange());
6000 
6001   // Determine which of the following types of shufflevector we're checking:
6002   // 1) unary, vector mask: (lhs, mask)
6003   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6004   QualType resType = TheCall->getArg(0)->getType();
6005   unsigned numElements = 0;
6006 
6007   if (!TheCall->getArg(0)->isTypeDependent() &&
6008       !TheCall->getArg(1)->isTypeDependent()) {
6009     QualType LHSType = TheCall->getArg(0)->getType();
6010     QualType RHSType = TheCall->getArg(1)->getType();
6011 
6012     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6013       return ExprError(
6014           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6015           << TheCall->getDirectCallee()
6016           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6017                          TheCall->getArg(1)->getEndLoc()));
6018 
6019     numElements = LHSType->castAs<VectorType>()->getNumElements();
6020     unsigned numResElements = TheCall->getNumArgs() - 2;
6021 
6022     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6023     // with mask.  If so, verify that RHS is an integer vector type with the
6024     // same number of elts as lhs.
6025     if (TheCall->getNumArgs() == 2) {
6026       if (!RHSType->hasIntegerRepresentation() ||
6027           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6028         return ExprError(Diag(TheCall->getBeginLoc(),
6029                               diag::err_vec_builtin_incompatible_vector)
6030                          << TheCall->getDirectCallee()
6031                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6032                                         TheCall->getArg(1)->getEndLoc()));
6033     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6034       return ExprError(Diag(TheCall->getBeginLoc(),
6035                             diag::err_vec_builtin_incompatible_vector)
6036                        << TheCall->getDirectCallee()
6037                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6038                                       TheCall->getArg(1)->getEndLoc()));
6039     } else if (numElements != numResElements) {
6040       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6041       resType = Context.getVectorType(eltType, numResElements,
6042                                       VectorType::GenericVector);
6043     }
6044   }
6045 
6046   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6047     if (TheCall->getArg(i)->isTypeDependent() ||
6048         TheCall->getArg(i)->isValueDependent())
6049       continue;
6050 
6051     Optional<llvm::APSInt> Result;
6052     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6053       return ExprError(Diag(TheCall->getBeginLoc(),
6054                             diag::err_shufflevector_nonconstant_argument)
6055                        << TheCall->getArg(i)->getSourceRange());
6056 
6057     // Allow -1 which will be translated to undef in the IR.
6058     if (Result->isSigned() && Result->isAllOnesValue())
6059       continue;
6060 
6061     if (Result->getActiveBits() > 64 ||
6062         Result->getZExtValue() >= numElements * 2)
6063       return ExprError(Diag(TheCall->getBeginLoc(),
6064                             diag::err_shufflevector_argument_too_large)
6065                        << TheCall->getArg(i)->getSourceRange());
6066   }
6067 
6068   SmallVector<Expr*, 32> exprs;
6069 
6070   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6071     exprs.push_back(TheCall->getArg(i));
6072     TheCall->setArg(i, nullptr);
6073   }
6074 
6075   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6076                                          TheCall->getCallee()->getBeginLoc(),
6077                                          TheCall->getRParenLoc());
6078 }
6079 
6080 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6081 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6082                                        SourceLocation BuiltinLoc,
6083                                        SourceLocation RParenLoc) {
6084   ExprValueKind VK = VK_RValue;
6085   ExprObjectKind OK = OK_Ordinary;
6086   QualType DstTy = TInfo->getType();
6087   QualType SrcTy = E->getType();
6088 
6089   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6090     return ExprError(Diag(BuiltinLoc,
6091                           diag::err_convertvector_non_vector)
6092                      << E->getSourceRange());
6093   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6094     return ExprError(Diag(BuiltinLoc,
6095                           diag::err_convertvector_non_vector_type));
6096 
6097   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6098     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6099     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6100     if (SrcElts != DstElts)
6101       return ExprError(Diag(BuiltinLoc,
6102                             diag::err_convertvector_incompatible_vector)
6103                        << E->getSourceRange());
6104   }
6105 
6106   return new (Context)
6107       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6108 }
6109 
6110 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6111 // This is declared to take (const void*, ...) and can take two
6112 // optional constant int args.
6113 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6114   unsigned NumArgs = TheCall->getNumArgs();
6115 
6116   if (NumArgs > 3)
6117     return Diag(TheCall->getEndLoc(),
6118                 diag::err_typecheck_call_too_many_args_at_most)
6119            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6120 
6121   // Argument 0 is checked for us and the remaining arguments must be
6122   // constant integers.
6123   for (unsigned i = 1; i != NumArgs; ++i)
6124     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6125       return true;
6126 
6127   return false;
6128 }
6129 
6130 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6131 // __assume does not evaluate its arguments, and should warn if its argument
6132 // has side effects.
6133 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6134   Expr *Arg = TheCall->getArg(0);
6135   if (Arg->isInstantiationDependent()) return false;
6136 
6137   if (Arg->HasSideEffects(Context))
6138     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6139         << Arg->getSourceRange()
6140         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6141 
6142   return false;
6143 }
6144 
6145 /// Handle __builtin_alloca_with_align. This is declared
6146 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6147 /// than 8.
6148 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6149   // The alignment must be a constant integer.
6150   Expr *Arg = TheCall->getArg(1);
6151 
6152   // We can't check the value of a dependent argument.
6153   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6154     if (const auto *UE =
6155             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6156       if (UE->getKind() == UETT_AlignOf ||
6157           UE->getKind() == UETT_PreferredAlignOf)
6158         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6159             << Arg->getSourceRange();
6160 
6161     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6162 
6163     if (!Result.isPowerOf2())
6164       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6165              << Arg->getSourceRange();
6166 
6167     if (Result < Context.getCharWidth())
6168       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6169              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6170 
6171     if (Result > std::numeric_limits<int32_t>::max())
6172       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6173              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6174   }
6175 
6176   return false;
6177 }
6178 
6179 /// Handle __builtin_assume_aligned. This is declared
6180 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6181 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6182   unsigned NumArgs = TheCall->getNumArgs();
6183 
6184   if (NumArgs > 3)
6185     return Diag(TheCall->getEndLoc(),
6186                 diag::err_typecheck_call_too_many_args_at_most)
6187            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6188 
6189   // The alignment must be a constant integer.
6190   Expr *Arg = TheCall->getArg(1);
6191 
6192   // We can't check the value of a dependent argument.
6193   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6194     llvm::APSInt Result;
6195     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6196       return true;
6197 
6198     if (!Result.isPowerOf2())
6199       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6200              << Arg->getSourceRange();
6201 
6202     if (Result > Sema::MaximumAlignment)
6203       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6204           << Arg->getSourceRange() << Sema::MaximumAlignment;
6205   }
6206 
6207   if (NumArgs > 2) {
6208     ExprResult Arg(TheCall->getArg(2));
6209     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6210       Context.getSizeType(), false);
6211     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6212     if (Arg.isInvalid()) return true;
6213     TheCall->setArg(2, Arg.get());
6214   }
6215 
6216   return false;
6217 }
6218 
6219 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6220   unsigned BuiltinID =
6221       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6222   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6223 
6224   unsigned NumArgs = TheCall->getNumArgs();
6225   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6226   if (NumArgs < NumRequiredArgs) {
6227     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6228            << 0 /* function call */ << NumRequiredArgs << NumArgs
6229            << TheCall->getSourceRange();
6230   }
6231   if (NumArgs >= NumRequiredArgs + 0x100) {
6232     return Diag(TheCall->getEndLoc(),
6233                 diag::err_typecheck_call_too_many_args_at_most)
6234            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6235            << TheCall->getSourceRange();
6236   }
6237   unsigned i = 0;
6238 
6239   // For formatting call, check buffer arg.
6240   if (!IsSizeCall) {
6241     ExprResult Arg(TheCall->getArg(i));
6242     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6243         Context, Context.VoidPtrTy, false);
6244     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6245     if (Arg.isInvalid())
6246       return true;
6247     TheCall->setArg(i, Arg.get());
6248     i++;
6249   }
6250 
6251   // Check string literal arg.
6252   unsigned FormatIdx = i;
6253   {
6254     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6255     if (Arg.isInvalid())
6256       return true;
6257     TheCall->setArg(i, Arg.get());
6258     i++;
6259   }
6260 
6261   // Make sure variadic args are scalar.
6262   unsigned FirstDataArg = i;
6263   while (i < NumArgs) {
6264     ExprResult Arg = DefaultVariadicArgumentPromotion(
6265         TheCall->getArg(i), VariadicFunction, nullptr);
6266     if (Arg.isInvalid())
6267       return true;
6268     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6269     if (ArgSize.getQuantity() >= 0x100) {
6270       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6271              << i << (int)ArgSize.getQuantity() << 0xff
6272              << TheCall->getSourceRange();
6273     }
6274     TheCall->setArg(i, Arg.get());
6275     i++;
6276   }
6277 
6278   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6279   // call to avoid duplicate diagnostics.
6280   if (!IsSizeCall) {
6281     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6282     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6283     bool Success = CheckFormatArguments(
6284         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6285         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6286         CheckedVarArgs);
6287     if (!Success)
6288       return true;
6289   }
6290 
6291   if (IsSizeCall) {
6292     TheCall->setType(Context.getSizeType());
6293   } else {
6294     TheCall->setType(Context.VoidPtrTy);
6295   }
6296   return false;
6297 }
6298 
6299 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6300 /// TheCall is a constant expression.
6301 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6302                                   llvm::APSInt &Result) {
6303   Expr *Arg = TheCall->getArg(ArgNum);
6304   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6305   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6306 
6307   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6308 
6309   Optional<llvm::APSInt> R;
6310   if (!(R = Arg->getIntegerConstantExpr(Context)))
6311     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6312            << FDecl->getDeclName() << Arg->getSourceRange();
6313   Result = *R;
6314   return false;
6315 }
6316 
6317 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6318 /// TheCall is a constant expression in the range [Low, High].
6319 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6320                                        int Low, int High, bool RangeIsError) {
6321   if (isConstantEvaluated())
6322     return false;
6323   llvm::APSInt Result;
6324 
6325   // We can't check the value of a dependent argument.
6326   Expr *Arg = TheCall->getArg(ArgNum);
6327   if (Arg->isTypeDependent() || Arg->isValueDependent())
6328     return false;
6329 
6330   // Check constant-ness first.
6331   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6332     return true;
6333 
6334   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6335     if (RangeIsError)
6336       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6337              << Result.toString(10) << Low << High << Arg->getSourceRange();
6338     else
6339       // Defer the warning until we know if the code will be emitted so that
6340       // dead code can ignore this.
6341       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6342                           PDiag(diag::warn_argument_invalid_range)
6343                               << Result.toString(10) << Low << High
6344                               << Arg->getSourceRange());
6345   }
6346 
6347   return false;
6348 }
6349 
6350 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6351 /// TheCall is a constant expression is a multiple of Num..
6352 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6353                                           unsigned Num) {
6354   llvm::APSInt Result;
6355 
6356   // We can't check the value of a dependent argument.
6357   Expr *Arg = TheCall->getArg(ArgNum);
6358   if (Arg->isTypeDependent() || Arg->isValueDependent())
6359     return false;
6360 
6361   // Check constant-ness first.
6362   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6363     return true;
6364 
6365   if (Result.getSExtValue() % Num != 0)
6366     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6367            << Num << Arg->getSourceRange();
6368 
6369   return false;
6370 }
6371 
6372 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6373 /// constant expression representing a power of 2.
6374 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6375   llvm::APSInt Result;
6376 
6377   // We can't check the value of a dependent argument.
6378   Expr *Arg = TheCall->getArg(ArgNum);
6379   if (Arg->isTypeDependent() || Arg->isValueDependent())
6380     return false;
6381 
6382   // Check constant-ness first.
6383   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6384     return true;
6385 
6386   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6387   // and only if x is a power of 2.
6388   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6389     return false;
6390 
6391   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6392          << Arg->getSourceRange();
6393 }
6394 
6395 static bool IsShiftedByte(llvm::APSInt Value) {
6396   if (Value.isNegative())
6397     return false;
6398 
6399   // Check if it's a shifted byte, by shifting it down
6400   while (true) {
6401     // If the value fits in the bottom byte, the check passes.
6402     if (Value < 0x100)
6403       return true;
6404 
6405     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6406     // fails.
6407     if ((Value & 0xFF) != 0)
6408       return false;
6409 
6410     // If the bottom 8 bits are all 0, but something above that is nonzero,
6411     // then shifting the value right by 8 bits won't affect whether it's a
6412     // shifted byte or not. So do that, and go round again.
6413     Value >>= 8;
6414   }
6415 }
6416 
6417 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6418 /// a constant expression representing an arbitrary byte value shifted left by
6419 /// a multiple of 8 bits.
6420 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6421                                              unsigned ArgBits) {
6422   llvm::APSInt Result;
6423 
6424   // We can't check the value of a dependent argument.
6425   Expr *Arg = TheCall->getArg(ArgNum);
6426   if (Arg->isTypeDependent() || Arg->isValueDependent())
6427     return false;
6428 
6429   // Check constant-ness first.
6430   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6431     return true;
6432 
6433   // Truncate to the given size.
6434   Result = Result.getLoBits(ArgBits);
6435   Result.setIsUnsigned(true);
6436 
6437   if (IsShiftedByte(Result))
6438     return false;
6439 
6440   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6441          << Arg->getSourceRange();
6442 }
6443 
6444 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6445 /// TheCall is a constant expression representing either a shifted byte value,
6446 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6447 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6448 /// Arm MVE intrinsics.
6449 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6450                                                    int ArgNum,
6451                                                    unsigned ArgBits) {
6452   llvm::APSInt Result;
6453 
6454   // We can't check the value of a dependent argument.
6455   Expr *Arg = TheCall->getArg(ArgNum);
6456   if (Arg->isTypeDependent() || Arg->isValueDependent())
6457     return false;
6458 
6459   // Check constant-ness first.
6460   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6461     return true;
6462 
6463   // Truncate to the given size.
6464   Result = Result.getLoBits(ArgBits);
6465   Result.setIsUnsigned(true);
6466 
6467   // Check to see if it's in either of the required forms.
6468   if (IsShiftedByte(Result) ||
6469       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6470     return false;
6471 
6472   return Diag(TheCall->getBeginLoc(),
6473               diag::err_argument_not_shifted_byte_or_xxff)
6474          << Arg->getSourceRange();
6475 }
6476 
6477 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6478 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6479   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6480     if (checkArgCount(*this, TheCall, 2))
6481       return true;
6482     Expr *Arg0 = TheCall->getArg(0);
6483     Expr *Arg1 = TheCall->getArg(1);
6484 
6485     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6486     if (FirstArg.isInvalid())
6487       return true;
6488     QualType FirstArgType = FirstArg.get()->getType();
6489     if (!FirstArgType->isAnyPointerType())
6490       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6491                << "first" << FirstArgType << Arg0->getSourceRange();
6492     TheCall->setArg(0, FirstArg.get());
6493 
6494     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6495     if (SecArg.isInvalid())
6496       return true;
6497     QualType SecArgType = SecArg.get()->getType();
6498     if (!SecArgType->isIntegerType())
6499       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6500                << "second" << SecArgType << Arg1->getSourceRange();
6501 
6502     // Derive the return type from the pointer argument.
6503     TheCall->setType(FirstArgType);
6504     return false;
6505   }
6506 
6507   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6508     if (checkArgCount(*this, TheCall, 2))
6509       return true;
6510 
6511     Expr *Arg0 = TheCall->getArg(0);
6512     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6513     if (FirstArg.isInvalid())
6514       return true;
6515     QualType FirstArgType = FirstArg.get()->getType();
6516     if (!FirstArgType->isAnyPointerType())
6517       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6518                << "first" << FirstArgType << Arg0->getSourceRange();
6519     TheCall->setArg(0, FirstArg.get());
6520 
6521     // Derive the return type from the pointer argument.
6522     TheCall->setType(FirstArgType);
6523 
6524     // Second arg must be an constant in range [0,15]
6525     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6526   }
6527 
6528   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6529     if (checkArgCount(*this, TheCall, 2))
6530       return true;
6531     Expr *Arg0 = TheCall->getArg(0);
6532     Expr *Arg1 = TheCall->getArg(1);
6533 
6534     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6535     if (FirstArg.isInvalid())
6536       return true;
6537     QualType FirstArgType = FirstArg.get()->getType();
6538     if (!FirstArgType->isAnyPointerType())
6539       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6540                << "first" << FirstArgType << Arg0->getSourceRange();
6541 
6542     QualType SecArgType = Arg1->getType();
6543     if (!SecArgType->isIntegerType())
6544       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6545                << "second" << SecArgType << Arg1->getSourceRange();
6546     TheCall->setType(Context.IntTy);
6547     return false;
6548   }
6549 
6550   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6551       BuiltinID == AArch64::BI__builtin_arm_stg) {
6552     if (checkArgCount(*this, TheCall, 1))
6553       return true;
6554     Expr *Arg0 = TheCall->getArg(0);
6555     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6556     if (FirstArg.isInvalid())
6557       return true;
6558 
6559     QualType FirstArgType = FirstArg.get()->getType();
6560     if (!FirstArgType->isAnyPointerType())
6561       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6562                << "first" << FirstArgType << Arg0->getSourceRange();
6563     TheCall->setArg(0, FirstArg.get());
6564 
6565     // Derive the return type from the pointer argument.
6566     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6567       TheCall->setType(FirstArgType);
6568     return false;
6569   }
6570 
6571   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6572     Expr *ArgA = TheCall->getArg(0);
6573     Expr *ArgB = TheCall->getArg(1);
6574 
6575     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6576     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6577 
6578     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6579       return true;
6580 
6581     QualType ArgTypeA = ArgExprA.get()->getType();
6582     QualType ArgTypeB = ArgExprB.get()->getType();
6583 
6584     auto isNull = [&] (Expr *E) -> bool {
6585       return E->isNullPointerConstant(
6586                         Context, Expr::NPC_ValueDependentIsNotNull); };
6587 
6588     // argument should be either a pointer or null
6589     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6590       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6591         << "first" << ArgTypeA << ArgA->getSourceRange();
6592 
6593     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6594       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6595         << "second" << ArgTypeB << ArgB->getSourceRange();
6596 
6597     // Ensure Pointee types are compatible
6598     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6599         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6600       QualType pointeeA = ArgTypeA->getPointeeType();
6601       QualType pointeeB = ArgTypeB->getPointeeType();
6602       if (!Context.typesAreCompatible(
6603              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6604              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6605         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6606           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6607           << ArgB->getSourceRange();
6608       }
6609     }
6610 
6611     // at least one argument should be pointer type
6612     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6613       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6614         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6615 
6616     if (isNull(ArgA)) // adopt type of the other pointer
6617       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6618 
6619     if (isNull(ArgB))
6620       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6621 
6622     TheCall->setArg(0, ArgExprA.get());
6623     TheCall->setArg(1, ArgExprB.get());
6624     TheCall->setType(Context.LongLongTy);
6625     return false;
6626   }
6627   assert(false && "Unhandled ARM MTE intrinsic");
6628   return true;
6629 }
6630 
6631 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6632 /// TheCall is an ARM/AArch64 special register string literal.
6633 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6634                                     int ArgNum, unsigned ExpectedFieldNum,
6635                                     bool AllowName) {
6636   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6637                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6638                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6639                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6640                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6641                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6642   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6643                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6644                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6645                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6646                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6647                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6648   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6649 
6650   // We can't check the value of a dependent argument.
6651   Expr *Arg = TheCall->getArg(ArgNum);
6652   if (Arg->isTypeDependent() || Arg->isValueDependent())
6653     return false;
6654 
6655   // Check if the argument is a string literal.
6656   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6657     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6658            << Arg->getSourceRange();
6659 
6660   // Check the type of special register given.
6661   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6662   SmallVector<StringRef, 6> Fields;
6663   Reg.split(Fields, ":");
6664 
6665   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6666     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6667            << Arg->getSourceRange();
6668 
6669   // If the string is the name of a register then we cannot check that it is
6670   // valid here but if the string is of one the forms described in ACLE then we
6671   // can check that the supplied fields are integers and within the valid
6672   // ranges.
6673   if (Fields.size() > 1) {
6674     bool FiveFields = Fields.size() == 5;
6675 
6676     bool ValidString = true;
6677     if (IsARMBuiltin) {
6678       ValidString &= Fields[0].startswith_lower("cp") ||
6679                      Fields[0].startswith_lower("p");
6680       if (ValidString)
6681         Fields[0] =
6682           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6683 
6684       ValidString &= Fields[2].startswith_lower("c");
6685       if (ValidString)
6686         Fields[2] = Fields[2].drop_front(1);
6687 
6688       if (FiveFields) {
6689         ValidString &= Fields[3].startswith_lower("c");
6690         if (ValidString)
6691           Fields[3] = Fields[3].drop_front(1);
6692       }
6693     }
6694 
6695     SmallVector<int, 5> Ranges;
6696     if (FiveFields)
6697       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6698     else
6699       Ranges.append({15, 7, 15});
6700 
6701     for (unsigned i=0; i<Fields.size(); ++i) {
6702       int IntField;
6703       ValidString &= !Fields[i].getAsInteger(10, IntField);
6704       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6705     }
6706 
6707     if (!ValidString)
6708       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6709              << Arg->getSourceRange();
6710   } else if (IsAArch64Builtin && Fields.size() == 1) {
6711     // If the register name is one of those that appear in the condition below
6712     // and the special register builtin being used is one of the write builtins,
6713     // then we require that the argument provided for writing to the register
6714     // is an integer constant expression. This is because it will be lowered to
6715     // an MSR (immediate) instruction, so we need to know the immediate at
6716     // compile time.
6717     if (TheCall->getNumArgs() != 2)
6718       return false;
6719 
6720     std::string RegLower = Reg.lower();
6721     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6722         RegLower != "pan" && RegLower != "uao")
6723       return false;
6724 
6725     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6726   }
6727 
6728   return false;
6729 }
6730 
6731 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6732 /// This checks that the target supports __builtin_longjmp and
6733 /// that val is a constant 1.
6734 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6735   if (!Context.getTargetInfo().hasSjLjLowering())
6736     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6737            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6738 
6739   Expr *Arg = TheCall->getArg(1);
6740   llvm::APSInt Result;
6741 
6742   // TODO: This is less than ideal. Overload this to take a value.
6743   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6744     return true;
6745 
6746   if (Result != 1)
6747     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6748            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6749 
6750   return false;
6751 }
6752 
6753 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6754 /// This checks that the target supports __builtin_setjmp.
6755 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6756   if (!Context.getTargetInfo().hasSjLjLowering())
6757     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6758            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6759   return false;
6760 }
6761 
6762 namespace {
6763 
6764 class UncoveredArgHandler {
6765   enum { Unknown = -1, AllCovered = -2 };
6766 
6767   signed FirstUncoveredArg = Unknown;
6768   SmallVector<const Expr *, 4> DiagnosticExprs;
6769 
6770 public:
6771   UncoveredArgHandler() = default;
6772 
6773   bool hasUncoveredArg() const {
6774     return (FirstUncoveredArg >= 0);
6775   }
6776 
6777   unsigned getUncoveredArg() const {
6778     assert(hasUncoveredArg() && "no uncovered argument");
6779     return FirstUncoveredArg;
6780   }
6781 
6782   void setAllCovered() {
6783     // A string has been found with all arguments covered, so clear out
6784     // the diagnostics.
6785     DiagnosticExprs.clear();
6786     FirstUncoveredArg = AllCovered;
6787   }
6788 
6789   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6790     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6791 
6792     // Don't update if a previous string covers all arguments.
6793     if (FirstUncoveredArg == AllCovered)
6794       return;
6795 
6796     // UncoveredArgHandler tracks the highest uncovered argument index
6797     // and with it all the strings that match this index.
6798     if (NewFirstUncoveredArg == FirstUncoveredArg)
6799       DiagnosticExprs.push_back(StrExpr);
6800     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6801       DiagnosticExprs.clear();
6802       DiagnosticExprs.push_back(StrExpr);
6803       FirstUncoveredArg = NewFirstUncoveredArg;
6804     }
6805   }
6806 
6807   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6808 };
6809 
6810 enum StringLiteralCheckType {
6811   SLCT_NotALiteral,
6812   SLCT_UncheckedLiteral,
6813   SLCT_CheckedLiteral
6814 };
6815 
6816 } // namespace
6817 
6818 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6819                                      BinaryOperatorKind BinOpKind,
6820                                      bool AddendIsRight) {
6821   unsigned BitWidth = Offset.getBitWidth();
6822   unsigned AddendBitWidth = Addend.getBitWidth();
6823   // There might be negative interim results.
6824   if (Addend.isUnsigned()) {
6825     Addend = Addend.zext(++AddendBitWidth);
6826     Addend.setIsSigned(true);
6827   }
6828   // Adjust the bit width of the APSInts.
6829   if (AddendBitWidth > BitWidth) {
6830     Offset = Offset.sext(AddendBitWidth);
6831     BitWidth = AddendBitWidth;
6832   } else if (BitWidth > AddendBitWidth) {
6833     Addend = Addend.sext(BitWidth);
6834   }
6835 
6836   bool Ov = false;
6837   llvm::APSInt ResOffset = Offset;
6838   if (BinOpKind == BO_Add)
6839     ResOffset = Offset.sadd_ov(Addend, Ov);
6840   else {
6841     assert(AddendIsRight && BinOpKind == BO_Sub &&
6842            "operator must be add or sub with addend on the right");
6843     ResOffset = Offset.ssub_ov(Addend, Ov);
6844   }
6845 
6846   // We add an offset to a pointer here so we should support an offset as big as
6847   // possible.
6848   if (Ov) {
6849     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6850            "index (intermediate) result too big");
6851     Offset = Offset.sext(2 * BitWidth);
6852     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6853     return;
6854   }
6855 
6856   Offset = ResOffset;
6857 }
6858 
6859 namespace {
6860 
6861 // This is a wrapper class around StringLiteral to support offsetted string
6862 // literals as format strings. It takes the offset into account when returning
6863 // the string and its length or the source locations to display notes correctly.
6864 class FormatStringLiteral {
6865   const StringLiteral *FExpr;
6866   int64_t Offset;
6867 
6868  public:
6869   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6870       : FExpr(fexpr), Offset(Offset) {}
6871 
6872   StringRef getString() const {
6873     return FExpr->getString().drop_front(Offset);
6874   }
6875 
6876   unsigned getByteLength() const {
6877     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6878   }
6879 
6880   unsigned getLength() const { return FExpr->getLength() - Offset; }
6881   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6882 
6883   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6884 
6885   QualType getType() const { return FExpr->getType(); }
6886 
6887   bool isAscii() const { return FExpr->isAscii(); }
6888   bool isWide() const { return FExpr->isWide(); }
6889   bool isUTF8() const { return FExpr->isUTF8(); }
6890   bool isUTF16() const { return FExpr->isUTF16(); }
6891   bool isUTF32() const { return FExpr->isUTF32(); }
6892   bool isPascal() const { return FExpr->isPascal(); }
6893 
6894   SourceLocation getLocationOfByte(
6895       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6896       const TargetInfo &Target, unsigned *StartToken = nullptr,
6897       unsigned *StartTokenByteOffset = nullptr) const {
6898     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6899                                     StartToken, StartTokenByteOffset);
6900   }
6901 
6902   SourceLocation getBeginLoc() const LLVM_READONLY {
6903     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6904   }
6905 
6906   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6907 };
6908 
6909 }  // namespace
6910 
6911 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6912                               const Expr *OrigFormatExpr,
6913                               ArrayRef<const Expr *> Args,
6914                               bool HasVAListArg, unsigned format_idx,
6915                               unsigned firstDataArg,
6916                               Sema::FormatStringType Type,
6917                               bool inFunctionCall,
6918                               Sema::VariadicCallType CallType,
6919                               llvm::SmallBitVector &CheckedVarArgs,
6920                               UncoveredArgHandler &UncoveredArg,
6921                               bool IgnoreStringsWithoutSpecifiers);
6922 
6923 // Determine if an expression is a string literal or constant string.
6924 // If this function returns false on the arguments to a function expecting a
6925 // format string, we will usually need to emit a warning.
6926 // True string literals are then checked by CheckFormatString.
6927 static StringLiteralCheckType
6928 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6929                       bool HasVAListArg, unsigned format_idx,
6930                       unsigned firstDataArg, Sema::FormatStringType Type,
6931                       Sema::VariadicCallType CallType, bool InFunctionCall,
6932                       llvm::SmallBitVector &CheckedVarArgs,
6933                       UncoveredArgHandler &UncoveredArg,
6934                       llvm::APSInt Offset,
6935                       bool IgnoreStringsWithoutSpecifiers = false) {
6936   if (S.isConstantEvaluated())
6937     return SLCT_NotALiteral;
6938  tryAgain:
6939   assert(Offset.isSigned() && "invalid offset");
6940 
6941   if (E->isTypeDependent() || E->isValueDependent())
6942     return SLCT_NotALiteral;
6943 
6944   E = E->IgnoreParenCasts();
6945 
6946   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6947     // Technically -Wformat-nonliteral does not warn about this case.
6948     // The behavior of printf and friends in this case is implementation
6949     // dependent.  Ideally if the format string cannot be null then
6950     // it should have a 'nonnull' attribute in the function prototype.
6951     return SLCT_UncheckedLiteral;
6952 
6953   switch (E->getStmtClass()) {
6954   case Stmt::BinaryConditionalOperatorClass:
6955   case Stmt::ConditionalOperatorClass: {
6956     // The expression is a literal if both sub-expressions were, and it was
6957     // completely checked only if both sub-expressions were checked.
6958     const AbstractConditionalOperator *C =
6959         cast<AbstractConditionalOperator>(E);
6960 
6961     // Determine whether it is necessary to check both sub-expressions, for
6962     // example, because the condition expression is a constant that can be
6963     // evaluated at compile time.
6964     bool CheckLeft = true, CheckRight = true;
6965 
6966     bool Cond;
6967     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6968                                                  S.isConstantEvaluated())) {
6969       if (Cond)
6970         CheckRight = false;
6971       else
6972         CheckLeft = false;
6973     }
6974 
6975     // We need to maintain the offsets for the right and the left hand side
6976     // separately to check if every possible indexed expression is a valid
6977     // string literal. They might have different offsets for different string
6978     // literals in the end.
6979     StringLiteralCheckType Left;
6980     if (!CheckLeft)
6981       Left = SLCT_UncheckedLiteral;
6982     else {
6983       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6984                                    HasVAListArg, format_idx, firstDataArg,
6985                                    Type, CallType, InFunctionCall,
6986                                    CheckedVarArgs, UncoveredArg, Offset,
6987                                    IgnoreStringsWithoutSpecifiers);
6988       if (Left == SLCT_NotALiteral || !CheckRight) {
6989         return Left;
6990       }
6991     }
6992 
6993     StringLiteralCheckType Right = checkFormatStringExpr(
6994         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6995         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6996         IgnoreStringsWithoutSpecifiers);
6997 
6998     return (CheckLeft && Left < Right) ? Left : Right;
6999   }
7000 
7001   case Stmt::ImplicitCastExprClass:
7002     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7003     goto tryAgain;
7004 
7005   case Stmt::OpaqueValueExprClass:
7006     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7007       E = src;
7008       goto tryAgain;
7009     }
7010     return SLCT_NotALiteral;
7011 
7012   case Stmt::PredefinedExprClass:
7013     // While __func__, etc., are technically not string literals, they
7014     // cannot contain format specifiers and thus are not a security
7015     // liability.
7016     return SLCT_UncheckedLiteral;
7017 
7018   case Stmt::DeclRefExprClass: {
7019     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7020 
7021     // As an exception, do not flag errors for variables binding to
7022     // const string literals.
7023     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7024       bool isConstant = false;
7025       QualType T = DR->getType();
7026 
7027       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7028         isConstant = AT->getElementType().isConstant(S.Context);
7029       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7030         isConstant = T.isConstant(S.Context) &&
7031                      PT->getPointeeType().isConstant(S.Context);
7032       } else if (T->isObjCObjectPointerType()) {
7033         // In ObjC, there is usually no "const ObjectPointer" type,
7034         // so don't check if the pointee type is constant.
7035         isConstant = T.isConstant(S.Context);
7036       }
7037 
7038       if (isConstant) {
7039         if (const Expr *Init = VD->getAnyInitializer()) {
7040           // Look through initializers like const char c[] = { "foo" }
7041           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7042             if (InitList->isStringLiteralInit())
7043               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7044           }
7045           return checkFormatStringExpr(S, Init, Args,
7046                                        HasVAListArg, format_idx,
7047                                        firstDataArg, Type, CallType,
7048                                        /*InFunctionCall*/ false, CheckedVarArgs,
7049                                        UncoveredArg, Offset);
7050         }
7051       }
7052 
7053       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7054       // special check to see if the format string is a function parameter
7055       // of the function calling the printf function.  If the function
7056       // has an attribute indicating it is a printf-like function, then we
7057       // should suppress warnings concerning non-literals being used in a call
7058       // to a vprintf function.  For example:
7059       //
7060       // void
7061       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7062       //      va_list ap;
7063       //      va_start(ap, fmt);
7064       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7065       //      ...
7066       // }
7067       if (HasVAListArg) {
7068         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7069           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7070             int PVIndex = PV->getFunctionScopeIndex() + 1;
7071             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7072               // adjust for implicit parameter
7073               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7074                 if (MD->isInstance())
7075                   ++PVIndex;
7076               // We also check if the formats are compatible.
7077               // We can't pass a 'scanf' string to a 'printf' function.
7078               if (PVIndex == PVFormat->getFormatIdx() &&
7079                   Type == S.GetFormatStringType(PVFormat))
7080                 return SLCT_UncheckedLiteral;
7081             }
7082           }
7083         }
7084       }
7085     }
7086 
7087     return SLCT_NotALiteral;
7088   }
7089 
7090   case Stmt::CallExprClass:
7091   case Stmt::CXXMemberCallExprClass: {
7092     const CallExpr *CE = cast<CallExpr>(E);
7093     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7094       bool IsFirst = true;
7095       StringLiteralCheckType CommonResult;
7096       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7097         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7098         StringLiteralCheckType Result = checkFormatStringExpr(
7099             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7100             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7101             IgnoreStringsWithoutSpecifiers);
7102         if (IsFirst) {
7103           CommonResult = Result;
7104           IsFirst = false;
7105         }
7106       }
7107       if (!IsFirst)
7108         return CommonResult;
7109 
7110       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7111         unsigned BuiltinID = FD->getBuiltinID();
7112         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7113             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7114           const Expr *Arg = CE->getArg(0);
7115           return checkFormatStringExpr(S, Arg, Args,
7116                                        HasVAListArg, format_idx,
7117                                        firstDataArg, Type, CallType,
7118                                        InFunctionCall, CheckedVarArgs,
7119                                        UncoveredArg, Offset,
7120                                        IgnoreStringsWithoutSpecifiers);
7121         }
7122       }
7123     }
7124 
7125     return SLCT_NotALiteral;
7126   }
7127   case Stmt::ObjCMessageExprClass: {
7128     const auto *ME = cast<ObjCMessageExpr>(E);
7129     if (const auto *MD = ME->getMethodDecl()) {
7130       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7131         // As a special case heuristic, if we're using the method -[NSBundle
7132         // localizedStringForKey:value:table:], ignore any key strings that lack
7133         // format specifiers. The idea is that if the key doesn't have any
7134         // format specifiers then its probably just a key to map to the
7135         // localized strings. If it does have format specifiers though, then its
7136         // likely that the text of the key is the format string in the
7137         // programmer's language, and should be checked.
7138         const ObjCInterfaceDecl *IFace;
7139         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7140             IFace->getIdentifier()->isStr("NSBundle") &&
7141             MD->getSelector().isKeywordSelector(
7142                 {"localizedStringForKey", "value", "table"})) {
7143           IgnoreStringsWithoutSpecifiers = true;
7144         }
7145 
7146         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7147         return checkFormatStringExpr(
7148             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7149             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7150             IgnoreStringsWithoutSpecifiers);
7151       }
7152     }
7153 
7154     return SLCT_NotALiteral;
7155   }
7156   case Stmt::ObjCStringLiteralClass:
7157   case Stmt::StringLiteralClass: {
7158     const StringLiteral *StrE = nullptr;
7159 
7160     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7161       StrE = ObjCFExpr->getString();
7162     else
7163       StrE = cast<StringLiteral>(E);
7164 
7165     if (StrE) {
7166       if (Offset.isNegative() || Offset > StrE->getLength()) {
7167         // TODO: It would be better to have an explicit warning for out of
7168         // bounds literals.
7169         return SLCT_NotALiteral;
7170       }
7171       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7172       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7173                         firstDataArg, Type, InFunctionCall, CallType,
7174                         CheckedVarArgs, UncoveredArg,
7175                         IgnoreStringsWithoutSpecifiers);
7176       return SLCT_CheckedLiteral;
7177     }
7178 
7179     return SLCT_NotALiteral;
7180   }
7181   case Stmt::BinaryOperatorClass: {
7182     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7183 
7184     // A string literal + an int offset is still a string literal.
7185     if (BinOp->isAdditiveOp()) {
7186       Expr::EvalResult LResult, RResult;
7187 
7188       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7189           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7190       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7191           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7192 
7193       if (LIsInt != RIsInt) {
7194         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7195 
7196         if (LIsInt) {
7197           if (BinOpKind == BO_Add) {
7198             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7199             E = BinOp->getRHS();
7200             goto tryAgain;
7201           }
7202         } else {
7203           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7204           E = BinOp->getLHS();
7205           goto tryAgain;
7206         }
7207       }
7208     }
7209 
7210     return SLCT_NotALiteral;
7211   }
7212   case Stmt::UnaryOperatorClass: {
7213     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7214     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7215     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7216       Expr::EvalResult IndexResult;
7217       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7218                                        Expr::SE_NoSideEffects,
7219                                        S.isConstantEvaluated())) {
7220         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7221                    /*RHS is int*/ true);
7222         E = ASE->getBase();
7223         goto tryAgain;
7224       }
7225     }
7226 
7227     return SLCT_NotALiteral;
7228   }
7229 
7230   default:
7231     return SLCT_NotALiteral;
7232   }
7233 }
7234 
7235 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7236   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7237       .Case("scanf", FST_Scanf)
7238       .Cases("printf", "printf0", FST_Printf)
7239       .Cases("NSString", "CFString", FST_NSString)
7240       .Case("strftime", FST_Strftime)
7241       .Case("strfmon", FST_Strfmon)
7242       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7243       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7244       .Case("os_trace", FST_OSLog)
7245       .Case("os_log", FST_OSLog)
7246       .Default(FST_Unknown);
7247 }
7248 
7249 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7250 /// functions) for correct use of format strings.
7251 /// Returns true if a format string has been fully checked.
7252 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7253                                 ArrayRef<const Expr *> Args,
7254                                 bool IsCXXMember,
7255                                 VariadicCallType CallType,
7256                                 SourceLocation Loc, SourceRange Range,
7257                                 llvm::SmallBitVector &CheckedVarArgs) {
7258   FormatStringInfo FSI;
7259   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7260     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7261                                 FSI.FirstDataArg, GetFormatStringType(Format),
7262                                 CallType, Loc, Range, CheckedVarArgs);
7263   return false;
7264 }
7265 
7266 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7267                                 bool HasVAListArg, unsigned format_idx,
7268                                 unsigned firstDataArg, FormatStringType Type,
7269                                 VariadicCallType CallType,
7270                                 SourceLocation Loc, SourceRange Range,
7271                                 llvm::SmallBitVector &CheckedVarArgs) {
7272   // CHECK: printf/scanf-like function is called with no format string.
7273   if (format_idx >= Args.size()) {
7274     Diag(Loc, diag::warn_missing_format_string) << Range;
7275     return false;
7276   }
7277 
7278   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7279 
7280   // CHECK: format string is not a string literal.
7281   //
7282   // Dynamically generated format strings are difficult to
7283   // automatically vet at compile time.  Requiring that format strings
7284   // are string literals: (1) permits the checking of format strings by
7285   // the compiler and thereby (2) can practically remove the source of
7286   // many format string exploits.
7287 
7288   // Format string can be either ObjC string (e.g. @"%d") or
7289   // C string (e.g. "%d")
7290   // ObjC string uses the same format specifiers as C string, so we can use
7291   // the same format string checking logic for both ObjC and C strings.
7292   UncoveredArgHandler UncoveredArg;
7293   StringLiteralCheckType CT =
7294       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7295                             format_idx, firstDataArg, Type, CallType,
7296                             /*IsFunctionCall*/ true, CheckedVarArgs,
7297                             UncoveredArg,
7298                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7299 
7300   // Generate a diagnostic where an uncovered argument is detected.
7301   if (UncoveredArg.hasUncoveredArg()) {
7302     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7303     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7304     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7305   }
7306 
7307   if (CT != SLCT_NotALiteral)
7308     // Literal format string found, check done!
7309     return CT == SLCT_CheckedLiteral;
7310 
7311   // Strftime is particular as it always uses a single 'time' argument,
7312   // so it is safe to pass a non-literal string.
7313   if (Type == FST_Strftime)
7314     return false;
7315 
7316   // Do not emit diag when the string param is a macro expansion and the
7317   // format is either NSString or CFString. This is a hack to prevent
7318   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7319   // which are usually used in place of NS and CF string literals.
7320   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7321   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7322     return false;
7323 
7324   // If there are no arguments specified, warn with -Wformat-security, otherwise
7325   // warn only with -Wformat-nonliteral.
7326   if (Args.size() == firstDataArg) {
7327     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7328       << OrigFormatExpr->getSourceRange();
7329     switch (Type) {
7330     default:
7331       break;
7332     case FST_Kprintf:
7333     case FST_FreeBSDKPrintf:
7334     case FST_Printf:
7335       Diag(FormatLoc, diag::note_format_security_fixit)
7336         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7337       break;
7338     case FST_NSString:
7339       Diag(FormatLoc, diag::note_format_security_fixit)
7340         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7341       break;
7342     }
7343   } else {
7344     Diag(FormatLoc, diag::warn_format_nonliteral)
7345       << OrigFormatExpr->getSourceRange();
7346   }
7347   return false;
7348 }
7349 
7350 namespace {
7351 
7352 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7353 protected:
7354   Sema &S;
7355   const FormatStringLiteral *FExpr;
7356   const Expr *OrigFormatExpr;
7357   const Sema::FormatStringType FSType;
7358   const unsigned FirstDataArg;
7359   const unsigned NumDataArgs;
7360   const char *Beg; // Start of format string.
7361   const bool HasVAListArg;
7362   ArrayRef<const Expr *> Args;
7363   unsigned FormatIdx;
7364   llvm::SmallBitVector CoveredArgs;
7365   bool usesPositionalArgs = false;
7366   bool atFirstArg = true;
7367   bool inFunctionCall;
7368   Sema::VariadicCallType CallType;
7369   llvm::SmallBitVector &CheckedVarArgs;
7370   UncoveredArgHandler &UncoveredArg;
7371 
7372 public:
7373   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7374                      const Expr *origFormatExpr,
7375                      const Sema::FormatStringType type, unsigned firstDataArg,
7376                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7377                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7378                      bool inFunctionCall, Sema::VariadicCallType callType,
7379                      llvm::SmallBitVector &CheckedVarArgs,
7380                      UncoveredArgHandler &UncoveredArg)
7381       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7382         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7383         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7384         inFunctionCall(inFunctionCall), CallType(callType),
7385         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7386     CoveredArgs.resize(numDataArgs);
7387     CoveredArgs.reset();
7388   }
7389 
7390   void DoneProcessing();
7391 
7392   void HandleIncompleteSpecifier(const char *startSpecifier,
7393                                  unsigned specifierLen) override;
7394 
7395   void HandleInvalidLengthModifier(
7396                            const analyze_format_string::FormatSpecifier &FS,
7397                            const analyze_format_string::ConversionSpecifier &CS,
7398                            const char *startSpecifier, unsigned specifierLen,
7399                            unsigned DiagID);
7400 
7401   void HandleNonStandardLengthModifier(
7402                     const analyze_format_string::FormatSpecifier &FS,
7403                     const char *startSpecifier, unsigned specifierLen);
7404 
7405   void HandleNonStandardConversionSpecifier(
7406                     const analyze_format_string::ConversionSpecifier &CS,
7407                     const char *startSpecifier, unsigned specifierLen);
7408 
7409   void HandlePosition(const char *startPos, unsigned posLen) override;
7410 
7411   void HandleInvalidPosition(const char *startSpecifier,
7412                              unsigned specifierLen,
7413                              analyze_format_string::PositionContext p) override;
7414 
7415   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7416 
7417   void HandleNullChar(const char *nullCharacter) override;
7418 
7419   template <typename Range>
7420   static void
7421   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7422                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7423                        bool IsStringLocation, Range StringRange,
7424                        ArrayRef<FixItHint> Fixit = None);
7425 
7426 protected:
7427   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7428                                         const char *startSpec,
7429                                         unsigned specifierLen,
7430                                         const char *csStart, unsigned csLen);
7431 
7432   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7433                                          const char *startSpec,
7434                                          unsigned specifierLen);
7435 
7436   SourceRange getFormatStringRange();
7437   CharSourceRange getSpecifierRange(const char *startSpecifier,
7438                                     unsigned specifierLen);
7439   SourceLocation getLocationOfByte(const char *x);
7440 
7441   const Expr *getDataArg(unsigned i) const;
7442 
7443   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7444                     const analyze_format_string::ConversionSpecifier &CS,
7445                     const char *startSpecifier, unsigned specifierLen,
7446                     unsigned argIndex);
7447 
7448   template <typename Range>
7449   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7450                             bool IsStringLocation, Range StringRange,
7451                             ArrayRef<FixItHint> Fixit = None);
7452 };
7453 
7454 } // namespace
7455 
7456 SourceRange CheckFormatHandler::getFormatStringRange() {
7457   return OrigFormatExpr->getSourceRange();
7458 }
7459 
7460 CharSourceRange CheckFormatHandler::
7461 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7462   SourceLocation Start = getLocationOfByte(startSpecifier);
7463   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7464 
7465   // Advance the end SourceLocation by one due to half-open ranges.
7466   End = End.getLocWithOffset(1);
7467 
7468   return CharSourceRange::getCharRange(Start, End);
7469 }
7470 
7471 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7472   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7473                                   S.getLangOpts(), S.Context.getTargetInfo());
7474 }
7475 
7476 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7477                                                    unsigned specifierLen){
7478   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7479                        getLocationOfByte(startSpecifier),
7480                        /*IsStringLocation*/true,
7481                        getSpecifierRange(startSpecifier, specifierLen));
7482 }
7483 
7484 void CheckFormatHandler::HandleInvalidLengthModifier(
7485     const analyze_format_string::FormatSpecifier &FS,
7486     const analyze_format_string::ConversionSpecifier &CS,
7487     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7488   using namespace analyze_format_string;
7489 
7490   const LengthModifier &LM = FS.getLengthModifier();
7491   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7492 
7493   // See if we know how to fix this length modifier.
7494   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7495   if (FixedLM) {
7496     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7497                          getLocationOfByte(LM.getStart()),
7498                          /*IsStringLocation*/true,
7499                          getSpecifierRange(startSpecifier, specifierLen));
7500 
7501     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7502       << FixedLM->toString()
7503       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7504 
7505   } else {
7506     FixItHint Hint;
7507     if (DiagID == diag::warn_format_nonsensical_length)
7508       Hint = FixItHint::CreateRemoval(LMRange);
7509 
7510     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7511                          getLocationOfByte(LM.getStart()),
7512                          /*IsStringLocation*/true,
7513                          getSpecifierRange(startSpecifier, specifierLen),
7514                          Hint);
7515   }
7516 }
7517 
7518 void CheckFormatHandler::HandleNonStandardLengthModifier(
7519     const analyze_format_string::FormatSpecifier &FS,
7520     const char *startSpecifier, unsigned specifierLen) {
7521   using namespace analyze_format_string;
7522 
7523   const LengthModifier &LM = FS.getLengthModifier();
7524   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7525 
7526   // See if we know how to fix this length modifier.
7527   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7528   if (FixedLM) {
7529     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7530                            << LM.toString() << 0,
7531                          getLocationOfByte(LM.getStart()),
7532                          /*IsStringLocation*/true,
7533                          getSpecifierRange(startSpecifier, specifierLen));
7534 
7535     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7536       << FixedLM->toString()
7537       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7538 
7539   } else {
7540     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7541                            << LM.toString() << 0,
7542                          getLocationOfByte(LM.getStart()),
7543                          /*IsStringLocation*/true,
7544                          getSpecifierRange(startSpecifier, specifierLen));
7545   }
7546 }
7547 
7548 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7549     const analyze_format_string::ConversionSpecifier &CS,
7550     const char *startSpecifier, unsigned specifierLen) {
7551   using namespace analyze_format_string;
7552 
7553   // See if we know how to fix this conversion specifier.
7554   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7555   if (FixedCS) {
7556     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7557                           << CS.toString() << /*conversion specifier*/1,
7558                          getLocationOfByte(CS.getStart()),
7559                          /*IsStringLocation*/true,
7560                          getSpecifierRange(startSpecifier, specifierLen));
7561 
7562     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7563     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7564       << FixedCS->toString()
7565       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7566   } else {
7567     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7568                           << CS.toString() << /*conversion specifier*/1,
7569                          getLocationOfByte(CS.getStart()),
7570                          /*IsStringLocation*/true,
7571                          getSpecifierRange(startSpecifier, specifierLen));
7572   }
7573 }
7574 
7575 void CheckFormatHandler::HandlePosition(const char *startPos,
7576                                         unsigned posLen) {
7577   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7578                                getLocationOfByte(startPos),
7579                                /*IsStringLocation*/true,
7580                                getSpecifierRange(startPos, posLen));
7581 }
7582 
7583 void
7584 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7585                                      analyze_format_string::PositionContext p) {
7586   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7587                          << (unsigned) p,
7588                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7589                        getSpecifierRange(startPos, posLen));
7590 }
7591 
7592 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7593                                             unsigned posLen) {
7594   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7595                                getLocationOfByte(startPos),
7596                                /*IsStringLocation*/true,
7597                                getSpecifierRange(startPos, posLen));
7598 }
7599 
7600 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7601   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7602     // The presence of a null character is likely an error.
7603     EmitFormatDiagnostic(
7604       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7605       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7606       getFormatStringRange());
7607   }
7608 }
7609 
7610 // Note that this may return NULL if there was an error parsing or building
7611 // one of the argument expressions.
7612 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7613   return Args[FirstDataArg + i];
7614 }
7615 
7616 void CheckFormatHandler::DoneProcessing() {
7617   // Does the number of data arguments exceed the number of
7618   // format conversions in the format string?
7619   if (!HasVAListArg) {
7620       // Find any arguments that weren't covered.
7621     CoveredArgs.flip();
7622     signed notCoveredArg = CoveredArgs.find_first();
7623     if (notCoveredArg >= 0) {
7624       assert((unsigned)notCoveredArg < NumDataArgs);
7625       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7626     } else {
7627       UncoveredArg.setAllCovered();
7628     }
7629   }
7630 }
7631 
7632 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7633                                    const Expr *ArgExpr) {
7634   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7635          "Invalid state");
7636 
7637   if (!ArgExpr)
7638     return;
7639 
7640   SourceLocation Loc = ArgExpr->getBeginLoc();
7641 
7642   if (S.getSourceManager().isInSystemMacro(Loc))
7643     return;
7644 
7645   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7646   for (auto E : DiagnosticExprs)
7647     PDiag << E->getSourceRange();
7648 
7649   CheckFormatHandler::EmitFormatDiagnostic(
7650                                   S, IsFunctionCall, DiagnosticExprs[0],
7651                                   PDiag, Loc, /*IsStringLocation*/false,
7652                                   DiagnosticExprs[0]->getSourceRange());
7653 }
7654 
7655 bool
7656 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7657                                                      SourceLocation Loc,
7658                                                      const char *startSpec,
7659                                                      unsigned specifierLen,
7660                                                      const char *csStart,
7661                                                      unsigned csLen) {
7662   bool keepGoing = true;
7663   if (argIndex < NumDataArgs) {
7664     // Consider the argument coverered, even though the specifier doesn't
7665     // make sense.
7666     CoveredArgs.set(argIndex);
7667   }
7668   else {
7669     // If argIndex exceeds the number of data arguments we
7670     // don't issue a warning because that is just a cascade of warnings (and
7671     // they may have intended '%%' anyway). We don't want to continue processing
7672     // the format string after this point, however, as we will like just get
7673     // gibberish when trying to match arguments.
7674     keepGoing = false;
7675   }
7676 
7677   StringRef Specifier(csStart, csLen);
7678 
7679   // If the specifier in non-printable, it could be the first byte of a UTF-8
7680   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7681   // hex value.
7682   std::string CodePointStr;
7683   if (!llvm::sys::locale::isPrint(*csStart)) {
7684     llvm::UTF32 CodePoint;
7685     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7686     const llvm::UTF8 *E =
7687         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7688     llvm::ConversionResult Result =
7689         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7690 
7691     if (Result != llvm::conversionOK) {
7692       unsigned char FirstChar = *csStart;
7693       CodePoint = (llvm::UTF32)FirstChar;
7694     }
7695 
7696     llvm::raw_string_ostream OS(CodePointStr);
7697     if (CodePoint < 256)
7698       OS << "\\x" << llvm::format("%02x", CodePoint);
7699     else if (CodePoint <= 0xFFFF)
7700       OS << "\\u" << llvm::format("%04x", CodePoint);
7701     else
7702       OS << "\\U" << llvm::format("%08x", CodePoint);
7703     OS.flush();
7704     Specifier = CodePointStr;
7705   }
7706 
7707   EmitFormatDiagnostic(
7708       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7709       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7710 
7711   return keepGoing;
7712 }
7713 
7714 void
7715 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7716                                                       const char *startSpec,
7717                                                       unsigned specifierLen) {
7718   EmitFormatDiagnostic(
7719     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7720     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7721 }
7722 
7723 bool
7724 CheckFormatHandler::CheckNumArgs(
7725   const analyze_format_string::FormatSpecifier &FS,
7726   const analyze_format_string::ConversionSpecifier &CS,
7727   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7728 
7729   if (argIndex >= NumDataArgs) {
7730     PartialDiagnostic PDiag = FS.usesPositionalArg()
7731       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7732            << (argIndex+1) << NumDataArgs)
7733       : S.PDiag(diag::warn_printf_insufficient_data_args);
7734     EmitFormatDiagnostic(
7735       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7736       getSpecifierRange(startSpecifier, specifierLen));
7737 
7738     // Since more arguments than conversion tokens are given, by extension
7739     // all arguments are covered, so mark this as so.
7740     UncoveredArg.setAllCovered();
7741     return false;
7742   }
7743   return true;
7744 }
7745 
7746 template<typename Range>
7747 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7748                                               SourceLocation Loc,
7749                                               bool IsStringLocation,
7750                                               Range StringRange,
7751                                               ArrayRef<FixItHint> FixIt) {
7752   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7753                        Loc, IsStringLocation, StringRange, FixIt);
7754 }
7755 
7756 /// If the format string is not within the function call, emit a note
7757 /// so that the function call and string are in diagnostic messages.
7758 ///
7759 /// \param InFunctionCall if true, the format string is within the function
7760 /// call and only one diagnostic message will be produced.  Otherwise, an
7761 /// extra note will be emitted pointing to location of the format string.
7762 ///
7763 /// \param ArgumentExpr the expression that is passed as the format string
7764 /// argument in the function call.  Used for getting locations when two
7765 /// diagnostics are emitted.
7766 ///
7767 /// \param PDiag the callee should already have provided any strings for the
7768 /// diagnostic message.  This function only adds locations and fixits
7769 /// to diagnostics.
7770 ///
7771 /// \param Loc primary location for diagnostic.  If two diagnostics are
7772 /// required, one will be at Loc and a new SourceLocation will be created for
7773 /// the other one.
7774 ///
7775 /// \param IsStringLocation if true, Loc points to the format string should be
7776 /// used for the note.  Otherwise, Loc points to the argument list and will
7777 /// be used with PDiag.
7778 ///
7779 /// \param StringRange some or all of the string to highlight.  This is
7780 /// templated so it can accept either a CharSourceRange or a SourceRange.
7781 ///
7782 /// \param FixIt optional fix it hint for the format string.
7783 template <typename Range>
7784 void CheckFormatHandler::EmitFormatDiagnostic(
7785     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7786     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7787     Range StringRange, ArrayRef<FixItHint> FixIt) {
7788   if (InFunctionCall) {
7789     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7790     D << StringRange;
7791     D << FixIt;
7792   } else {
7793     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7794       << ArgumentExpr->getSourceRange();
7795 
7796     const Sema::SemaDiagnosticBuilder &Note =
7797       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7798              diag::note_format_string_defined);
7799 
7800     Note << StringRange;
7801     Note << FixIt;
7802   }
7803 }
7804 
7805 //===--- CHECK: Printf format string checking ------------------------------===//
7806 
7807 namespace {
7808 
7809 class CheckPrintfHandler : public CheckFormatHandler {
7810 public:
7811   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7812                      const Expr *origFormatExpr,
7813                      const Sema::FormatStringType type, unsigned firstDataArg,
7814                      unsigned numDataArgs, bool isObjC, const char *beg,
7815                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7816                      unsigned formatIdx, bool inFunctionCall,
7817                      Sema::VariadicCallType CallType,
7818                      llvm::SmallBitVector &CheckedVarArgs,
7819                      UncoveredArgHandler &UncoveredArg)
7820       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7821                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7822                            inFunctionCall, CallType, CheckedVarArgs,
7823                            UncoveredArg) {}
7824 
7825   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7826 
7827   /// Returns true if '%@' specifiers are allowed in the format string.
7828   bool allowsObjCArg() const {
7829     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7830            FSType == Sema::FST_OSTrace;
7831   }
7832 
7833   bool HandleInvalidPrintfConversionSpecifier(
7834                                       const analyze_printf::PrintfSpecifier &FS,
7835                                       const char *startSpecifier,
7836                                       unsigned specifierLen) override;
7837 
7838   void handleInvalidMaskType(StringRef MaskType) override;
7839 
7840   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7841                              const char *startSpecifier,
7842                              unsigned specifierLen) override;
7843   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7844                        const char *StartSpecifier,
7845                        unsigned SpecifierLen,
7846                        const Expr *E);
7847 
7848   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7849                     const char *startSpecifier, unsigned specifierLen);
7850   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7851                            const analyze_printf::OptionalAmount &Amt,
7852                            unsigned type,
7853                            const char *startSpecifier, unsigned specifierLen);
7854   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7855                   const analyze_printf::OptionalFlag &flag,
7856                   const char *startSpecifier, unsigned specifierLen);
7857   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7858                          const analyze_printf::OptionalFlag &ignoredFlag,
7859                          const analyze_printf::OptionalFlag &flag,
7860                          const char *startSpecifier, unsigned specifierLen);
7861   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7862                            const Expr *E);
7863 
7864   void HandleEmptyObjCModifierFlag(const char *startFlag,
7865                                    unsigned flagLen) override;
7866 
7867   void HandleInvalidObjCModifierFlag(const char *startFlag,
7868                                             unsigned flagLen) override;
7869 
7870   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7871                                            const char *flagsEnd,
7872                                            const char *conversionPosition)
7873                                              override;
7874 };
7875 
7876 } // namespace
7877 
7878 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7879                                       const analyze_printf::PrintfSpecifier &FS,
7880                                       const char *startSpecifier,
7881                                       unsigned specifierLen) {
7882   const analyze_printf::PrintfConversionSpecifier &CS =
7883     FS.getConversionSpecifier();
7884 
7885   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7886                                           getLocationOfByte(CS.getStart()),
7887                                           startSpecifier, specifierLen,
7888                                           CS.getStart(), CS.getLength());
7889 }
7890 
7891 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7892   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7893 }
7894 
7895 bool CheckPrintfHandler::HandleAmount(
7896                                const analyze_format_string::OptionalAmount &Amt,
7897                                unsigned k, const char *startSpecifier,
7898                                unsigned specifierLen) {
7899   if (Amt.hasDataArgument()) {
7900     if (!HasVAListArg) {
7901       unsigned argIndex = Amt.getArgIndex();
7902       if (argIndex >= NumDataArgs) {
7903         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7904                                << k,
7905                              getLocationOfByte(Amt.getStart()),
7906                              /*IsStringLocation*/true,
7907                              getSpecifierRange(startSpecifier, specifierLen));
7908         // Don't do any more checking.  We will just emit
7909         // spurious errors.
7910         return false;
7911       }
7912 
7913       // Type check the data argument.  It should be an 'int'.
7914       // Although not in conformance with C99, we also allow the argument to be
7915       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7916       // doesn't emit a warning for that case.
7917       CoveredArgs.set(argIndex);
7918       const Expr *Arg = getDataArg(argIndex);
7919       if (!Arg)
7920         return false;
7921 
7922       QualType T = Arg->getType();
7923 
7924       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7925       assert(AT.isValid());
7926 
7927       if (!AT.matchesType(S.Context, T)) {
7928         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7929                                << k << AT.getRepresentativeTypeName(S.Context)
7930                                << T << Arg->getSourceRange(),
7931                              getLocationOfByte(Amt.getStart()),
7932                              /*IsStringLocation*/true,
7933                              getSpecifierRange(startSpecifier, specifierLen));
7934         // Don't do any more checking.  We will just emit
7935         // spurious errors.
7936         return false;
7937       }
7938     }
7939   }
7940   return true;
7941 }
7942 
7943 void CheckPrintfHandler::HandleInvalidAmount(
7944                                       const analyze_printf::PrintfSpecifier &FS,
7945                                       const analyze_printf::OptionalAmount &Amt,
7946                                       unsigned type,
7947                                       const char *startSpecifier,
7948                                       unsigned specifierLen) {
7949   const analyze_printf::PrintfConversionSpecifier &CS =
7950     FS.getConversionSpecifier();
7951 
7952   FixItHint fixit =
7953     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7954       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7955                                  Amt.getConstantLength()))
7956       : FixItHint();
7957 
7958   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7959                          << type << CS.toString(),
7960                        getLocationOfByte(Amt.getStart()),
7961                        /*IsStringLocation*/true,
7962                        getSpecifierRange(startSpecifier, specifierLen),
7963                        fixit);
7964 }
7965 
7966 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7967                                     const analyze_printf::OptionalFlag &flag,
7968                                     const char *startSpecifier,
7969                                     unsigned specifierLen) {
7970   // Warn about pointless flag with a fixit removal.
7971   const analyze_printf::PrintfConversionSpecifier &CS =
7972     FS.getConversionSpecifier();
7973   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7974                          << flag.toString() << CS.toString(),
7975                        getLocationOfByte(flag.getPosition()),
7976                        /*IsStringLocation*/true,
7977                        getSpecifierRange(startSpecifier, specifierLen),
7978                        FixItHint::CreateRemoval(
7979                          getSpecifierRange(flag.getPosition(), 1)));
7980 }
7981 
7982 void CheckPrintfHandler::HandleIgnoredFlag(
7983                                 const analyze_printf::PrintfSpecifier &FS,
7984                                 const analyze_printf::OptionalFlag &ignoredFlag,
7985                                 const analyze_printf::OptionalFlag &flag,
7986                                 const char *startSpecifier,
7987                                 unsigned specifierLen) {
7988   // Warn about ignored flag with a fixit removal.
7989   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7990                          << ignoredFlag.toString() << flag.toString(),
7991                        getLocationOfByte(ignoredFlag.getPosition()),
7992                        /*IsStringLocation*/true,
7993                        getSpecifierRange(startSpecifier, specifierLen),
7994                        FixItHint::CreateRemoval(
7995                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7996 }
7997 
7998 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7999                                                      unsigned flagLen) {
8000   // Warn about an empty flag.
8001   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8002                        getLocationOfByte(startFlag),
8003                        /*IsStringLocation*/true,
8004                        getSpecifierRange(startFlag, flagLen));
8005 }
8006 
8007 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8008                                                        unsigned flagLen) {
8009   // Warn about an invalid flag.
8010   auto Range = getSpecifierRange(startFlag, flagLen);
8011   StringRef flag(startFlag, flagLen);
8012   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8013                       getLocationOfByte(startFlag),
8014                       /*IsStringLocation*/true,
8015                       Range, FixItHint::CreateRemoval(Range));
8016 }
8017 
8018 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8019     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8020     // Warn about using '[...]' without a '@' conversion.
8021     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8022     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8023     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8024                          getLocationOfByte(conversionPosition),
8025                          /*IsStringLocation*/true,
8026                          Range, FixItHint::CreateRemoval(Range));
8027 }
8028 
8029 // Determines if the specified is a C++ class or struct containing
8030 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8031 // "c_str()").
8032 template<typename MemberKind>
8033 static llvm::SmallPtrSet<MemberKind*, 1>
8034 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8035   const RecordType *RT = Ty->getAs<RecordType>();
8036   llvm::SmallPtrSet<MemberKind*, 1> Results;
8037 
8038   if (!RT)
8039     return Results;
8040   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8041   if (!RD || !RD->getDefinition())
8042     return Results;
8043 
8044   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8045                  Sema::LookupMemberName);
8046   R.suppressDiagnostics();
8047 
8048   // We just need to include all members of the right kind turned up by the
8049   // filter, at this point.
8050   if (S.LookupQualifiedName(R, RT->getDecl()))
8051     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8052       NamedDecl *decl = (*I)->getUnderlyingDecl();
8053       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8054         Results.insert(FK);
8055     }
8056   return Results;
8057 }
8058 
8059 /// Check if we could call '.c_str()' on an object.
8060 ///
8061 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8062 /// allow the call, or if it would be ambiguous).
8063 bool Sema::hasCStrMethod(const Expr *E) {
8064   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8065 
8066   MethodSet Results =
8067       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8068   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8069        MI != ME; ++MI)
8070     if ((*MI)->getMinRequiredArguments() == 0)
8071       return true;
8072   return false;
8073 }
8074 
8075 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8076 // better diagnostic if so. AT is assumed to be valid.
8077 // Returns true when a c_str() conversion method is found.
8078 bool CheckPrintfHandler::checkForCStrMembers(
8079     const analyze_printf::ArgType &AT, const Expr *E) {
8080   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8081 
8082   MethodSet Results =
8083       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8084 
8085   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8086        MI != ME; ++MI) {
8087     const CXXMethodDecl *Method = *MI;
8088     if (Method->getMinRequiredArguments() == 0 &&
8089         AT.matchesType(S.Context, Method->getReturnType())) {
8090       // FIXME: Suggest parens if the expression needs them.
8091       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8092       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8093           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8094       return true;
8095     }
8096   }
8097 
8098   return false;
8099 }
8100 
8101 bool
8102 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8103                                             &FS,
8104                                           const char *startSpecifier,
8105                                           unsigned specifierLen) {
8106   using namespace analyze_format_string;
8107   using namespace analyze_printf;
8108 
8109   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8110 
8111   if (FS.consumesDataArgument()) {
8112     if (atFirstArg) {
8113         atFirstArg = false;
8114         usesPositionalArgs = FS.usesPositionalArg();
8115     }
8116     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8117       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8118                                         startSpecifier, specifierLen);
8119       return false;
8120     }
8121   }
8122 
8123   // First check if the field width, precision, and conversion specifier
8124   // have matching data arguments.
8125   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8126                     startSpecifier, specifierLen)) {
8127     return false;
8128   }
8129 
8130   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8131                     startSpecifier, specifierLen)) {
8132     return false;
8133   }
8134 
8135   if (!CS.consumesDataArgument()) {
8136     // FIXME: Technically specifying a precision or field width here
8137     // makes no sense.  Worth issuing a warning at some point.
8138     return true;
8139   }
8140 
8141   // Consume the argument.
8142   unsigned argIndex = FS.getArgIndex();
8143   if (argIndex < NumDataArgs) {
8144     // The check to see if the argIndex is valid will come later.
8145     // We set the bit here because we may exit early from this
8146     // function if we encounter some other error.
8147     CoveredArgs.set(argIndex);
8148   }
8149 
8150   // FreeBSD kernel extensions.
8151   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8152       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8153     // We need at least two arguments.
8154     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8155       return false;
8156 
8157     // Claim the second argument.
8158     CoveredArgs.set(argIndex + 1);
8159 
8160     // Type check the first argument (int for %b, pointer for %D)
8161     const Expr *Ex = getDataArg(argIndex);
8162     const analyze_printf::ArgType &AT =
8163       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8164         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8165     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8166       EmitFormatDiagnostic(
8167           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8168               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8169               << false << Ex->getSourceRange(),
8170           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8171           getSpecifierRange(startSpecifier, specifierLen));
8172 
8173     // Type check the second argument (char * for both %b and %D)
8174     Ex = getDataArg(argIndex + 1);
8175     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8176     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8177       EmitFormatDiagnostic(
8178           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8179               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8180               << false << Ex->getSourceRange(),
8181           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8182           getSpecifierRange(startSpecifier, specifierLen));
8183 
8184      return true;
8185   }
8186 
8187   // Check for using an Objective-C specific conversion specifier
8188   // in a non-ObjC literal.
8189   if (!allowsObjCArg() && CS.isObjCArg()) {
8190     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8191                                                   specifierLen);
8192   }
8193 
8194   // %P can only be used with os_log.
8195   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8196     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8197                                                   specifierLen);
8198   }
8199 
8200   // %n is not allowed with os_log.
8201   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8202     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8203                          getLocationOfByte(CS.getStart()),
8204                          /*IsStringLocation*/ false,
8205                          getSpecifierRange(startSpecifier, specifierLen));
8206 
8207     return true;
8208   }
8209 
8210   // Only scalars are allowed for os_trace.
8211   if (FSType == Sema::FST_OSTrace &&
8212       (CS.getKind() == ConversionSpecifier::PArg ||
8213        CS.getKind() == ConversionSpecifier::sArg ||
8214        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8215     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8216                                                   specifierLen);
8217   }
8218 
8219   // Check for use of public/private annotation outside of os_log().
8220   if (FSType != Sema::FST_OSLog) {
8221     if (FS.isPublic().isSet()) {
8222       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8223                                << "public",
8224                            getLocationOfByte(FS.isPublic().getPosition()),
8225                            /*IsStringLocation*/ false,
8226                            getSpecifierRange(startSpecifier, specifierLen));
8227     }
8228     if (FS.isPrivate().isSet()) {
8229       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8230                                << "private",
8231                            getLocationOfByte(FS.isPrivate().getPosition()),
8232                            /*IsStringLocation*/ false,
8233                            getSpecifierRange(startSpecifier, specifierLen));
8234     }
8235   }
8236 
8237   // Check for invalid use of field width
8238   if (!FS.hasValidFieldWidth()) {
8239     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8240         startSpecifier, specifierLen);
8241   }
8242 
8243   // Check for invalid use of precision
8244   if (!FS.hasValidPrecision()) {
8245     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8246         startSpecifier, specifierLen);
8247   }
8248 
8249   // Precision is mandatory for %P specifier.
8250   if (CS.getKind() == ConversionSpecifier::PArg &&
8251       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8252     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8253                          getLocationOfByte(startSpecifier),
8254                          /*IsStringLocation*/ false,
8255                          getSpecifierRange(startSpecifier, specifierLen));
8256   }
8257 
8258   // Check each flag does not conflict with any other component.
8259   if (!FS.hasValidThousandsGroupingPrefix())
8260     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8261   if (!FS.hasValidLeadingZeros())
8262     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8263   if (!FS.hasValidPlusPrefix())
8264     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8265   if (!FS.hasValidSpacePrefix())
8266     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8267   if (!FS.hasValidAlternativeForm())
8268     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8269   if (!FS.hasValidLeftJustified())
8270     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8271 
8272   // Check that flags are not ignored by another flag
8273   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8274     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8275         startSpecifier, specifierLen);
8276   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8277     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8278             startSpecifier, specifierLen);
8279 
8280   // Check the length modifier is valid with the given conversion specifier.
8281   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8282                                  S.getLangOpts()))
8283     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8284                                 diag::warn_format_nonsensical_length);
8285   else if (!FS.hasStandardLengthModifier())
8286     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8287   else if (!FS.hasStandardLengthConversionCombination())
8288     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8289                                 diag::warn_format_non_standard_conversion_spec);
8290 
8291   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8292     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8293 
8294   // The remaining checks depend on the data arguments.
8295   if (HasVAListArg)
8296     return true;
8297 
8298   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8299     return false;
8300 
8301   const Expr *Arg = getDataArg(argIndex);
8302   if (!Arg)
8303     return true;
8304 
8305   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8306 }
8307 
8308 static bool requiresParensToAddCast(const Expr *E) {
8309   // FIXME: We should have a general way to reason about operator
8310   // precedence and whether parens are actually needed here.
8311   // Take care of a few common cases where they aren't.
8312   const Expr *Inside = E->IgnoreImpCasts();
8313   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8314     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8315 
8316   switch (Inside->getStmtClass()) {
8317   case Stmt::ArraySubscriptExprClass:
8318   case Stmt::CallExprClass:
8319   case Stmt::CharacterLiteralClass:
8320   case Stmt::CXXBoolLiteralExprClass:
8321   case Stmt::DeclRefExprClass:
8322   case Stmt::FloatingLiteralClass:
8323   case Stmt::IntegerLiteralClass:
8324   case Stmt::MemberExprClass:
8325   case Stmt::ObjCArrayLiteralClass:
8326   case Stmt::ObjCBoolLiteralExprClass:
8327   case Stmt::ObjCBoxedExprClass:
8328   case Stmt::ObjCDictionaryLiteralClass:
8329   case Stmt::ObjCEncodeExprClass:
8330   case Stmt::ObjCIvarRefExprClass:
8331   case Stmt::ObjCMessageExprClass:
8332   case Stmt::ObjCPropertyRefExprClass:
8333   case Stmt::ObjCStringLiteralClass:
8334   case Stmt::ObjCSubscriptRefExprClass:
8335   case Stmt::ParenExprClass:
8336   case Stmt::StringLiteralClass:
8337   case Stmt::UnaryOperatorClass:
8338     return false;
8339   default:
8340     return true;
8341   }
8342 }
8343 
8344 static std::pair<QualType, StringRef>
8345 shouldNotPrintDirectly(const ASTContext &Context,
8346                        QualType IntendedTy,
8347                        const Expr *E) {
8348   // Use a 'while' to peel off layers of typedefs.
8349   QualType TyTy = IntendedTy;
8350   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8351     StringRef Name = UserTy->getDecl()->getName();
8352     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8353       .Case("CFIndex", Context.getNSIntegerType())
8354       .Case("NSInteger", Context.getNSIntegerType())
8355       .Case("NSUInteger", Context.getNSUIntegerType())
8356       .Case("SInt32", Context.IntTy)
8357       .Case("UInt32", Context.UnsignedIntTy)
8358       .Default(QualType());
8359 
8360     if (!CastTy.isNull())
8361       return std::make_pair(CastTy, Name);
8362 
8363     TyTy = UserTy->desugar();
8364   }
8365 
8366   // Strip parens if necessary.
8367   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8368     return shouldNotPrintDirectly(Context,
8369                                   PE->getSubExpr()->getType(),
8370                                   PE->getSubExpr());
8371 
8372   // If this is a conditional expression, then its result type is constructed
8373   // via usual arithmetic conversions and thus there might be no necessary
8374   // typedef sugar there.  Recurse to operands to check for NSInteger &
8375   // Co. usage condition.
8376   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8377     QualType TrueTy, FalseTy;
8378     StringRef TrueName, FalseName;
8379 
8380     std::tie(TrueTy, TrueName) =
8381       shouldNotPrintDirectly(Context,
8382                              CO->getTrueExpr()->getType(),
8383                              CO->getTrueExpr());
8384     std::tie(FalseTy, FalseName) =
8385       shouldNotPrintDirectly(Context,
8386                              CO->getFalseExpr()->getType(),
8387                              CO->getFalseExpr());
8388 
8389     if (TrueTy == FalseTy)
8390       return std::make_pair(TrueTy, TrueName);
8391     else if (TrueTy.isNull())
8392       return std::make_pair(FalseTy, FalseName);
8393     else if (FalseTy.isNull())
8394       return std::make_pair(TrueTy, TrueName);
8395   }
8396 
8397   return std::make_pair(QualType(), StringRef());
8398 }
8399 
8400 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8401 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8402 /// type do not count.
8403 static bool
8404 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8405   QualType From = ICE->getSubExpr()->getType();
8406   QualType To = ICE->getType();
8407   // It's an integer promotion if the destination type is the promoted
8408   // source type.
8409   if (ICE->getCastKind() == CK_IntegralCast &&
8410       From->isPromotableIntegerType() &&
8411       S.Context.getPromotedIntegerType(From) == To)
8412     return true;
8413   // Look through vector types, since we do default argument promotion for
8414   // those in OpenCL.
8415   if (const auto *VecTy = From->getAs<ExtVectorType>())
8416     From = VecTy->getElementType();
8417   if (const auto *VecTy = To->getAs<ExtVectorType>())
8418     To = VecTy->getElementType();
8419   // It's a floating promotion if the source type is a lower rank.
8420   return ICE->getCastKind() == CK_FloatingCast &&
8421          S.Context.getFloatingTypeOrder(From, To) < 0;
8422 }
8423 
8424 bool
8425 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8426                                     const char *StartSpecifier,
8427                                     unsigned SpecifierLen,
8428                                     const Expr *E) {
8429   using namespace analyze_format_string;
8430   using namespace analyze_printf;
8431 
8432   // Now type check the data expression that matches the
8433   // format specifier.
8434   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8435   if (!AT.isValid())
8436     return true;
8437 
8438   QualType ExprTy = E->getType();
8439   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8440     ExprTy = TET->getUnderlyingExpr()->getType();
8441   }
8442 
8443   // Diagnose attempts to print a boolean value as a character. Unlike other
8444   // -Wformat diagnostics, this is fine from a type perspective, but it still
8445   // doesn't make sense.
8446   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8447       E->isKnownToHaveBooleanValue()) {
8448     const CharSourceRange &CSR =
8449         getSpecifierRange(StartSpecifier, SpecifierLen);
8450     SmallString<4> FSString;
8451     llvm::raw_svector_ostream os(FSString);
8452     FS.toString(os);
8453     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8454                              << FSString,
8455                          E->getExprLoc(), false, CSR);
8456     return true;
8457   }
8458 
8459   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8460   if (Match == analyze_printf::ArgType::Match)
8461     return true;
8462 
8463   // Look through argument promotions for our error message's reported type.
8464   // This includes the integral and floating promotions, but excludes array
8465   // and function pointer decay (seeing that an argument intended to be a
8466   // string has type 'char [6]' is probably more confusing than 'char *') and
8467   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8468   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8469     if (isArithmeticArgumentPromotion(S, ICE)) {
8470       E = ICE->getSubExpr();
8471       ExprTy = E->getType();
8472 
8473       // Check if we didn't match because of an implicit cast from a 'char'
8474       // or 'short' to an 'int'.  This is done because printf is a varargs
8475       // function.
8476       if (ICE->getType() == S.Context.IntTy ||
8477           ICE->getType() == S.Context.UnsignedIntTy) {
8478         // All further checking is done on the subexpression
8479         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8480             AT.matchesType(S.Context, ExprTy);
8481         if (ImplicitMatch == analyze_printf::ArgType::Match)
8482           return true;
8483         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8484             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8485           Match = ImplicitMatch;
8486       }
8487     }
8488   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8489     // Special case for 'a', which has type 'int' in C.
8490     // Note, however, that we do /not/ want to treat multibyte constants like
8491     // 'MooV' as characters! This form is deprecated but still exists.
8492     if (ExprTy == S.Context.IntTy)
8493       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8494         ExprTy = S.Context.CharTy;
8495   }
8496 
8497   // Look through enums to their underlying type.
8498   bool IsEnum = false;
8499   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8500     ExprTy = EnumTy->getDecl()->getIntegerType();
8501     IsEnum = true;
8502   }
8503 
8504   // %C in an Objective-C context prints a unichar, not a wchar_t.
8505   // If the argument is an integer of some kind, believe the %C and suggest
8506   // a cast instead of changing the conversion specifier.
8507   QualType IntendedTy = ExprTy;
8508   if (isObjCContext() &&
8509       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8510     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8511         !ExprTy->isCharType()) {
8512       // 'unichar' is defined as a typedef of unsigned short, but we should
8513       // prefer using the typedef if it is visible.
8514       IntendedTy = S.Context.UnsignedShortTy;
8515 
8516       // While we are here, check if the value is an IntegerLiteral that happens
8517       // to be within the valid range.
8518       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8519         const llvm::APInt &V = IL->getValue();
8520         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8521           return true;
8522       }
8523 
8524       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8525                           Sema::LookupOrdinaryName);
8526       if (S.LookupName(Result, S.getCurScope())) {
8527         NamedDecl *ND = Result.getFoundDecl();
8528         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8529           if (TD->getUnderlyingType() == IntendedTy)
8530             IntendedTy = S.Context.getTypedefType(TD);
8531       }
8532     }
8533   }
8534 
8535   // Special-case some of Darwin's platform-independence types by suggesting
8536   // casts to primitive types that are known to be large enough.
8537   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8538   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8539     QualType CastTy;
8540     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8541     if (!CastTy.isNull()) {
8542       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8543       // (long in ASTContext). Only complain to pedants.
8544       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8545           (AT.isSizeT() || AT.isPtrdiffT()) &&
8546           AT.matchesType(S.Context, CastTy))
8547         Match = ArgType::NoMatchPedantic;
8548       IntendedTy = CastTy;
8549       ShouldNotPrintDirectly = true;
8550     }
8551   }
8552 
8553   // We may be able to offer a FixItHint if it is a supported type.
8554   PrintfSpecifier fixedFS = FS;
8555   bool Success =
8556       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8557 
8558   if (Success) {
8559     // Get the fix string from the fixed format specifier
8560     SmallString<16> buf;
8561     llvm::raw_svector_ostream os(buf);
8562     fixedFS.toString(os);
8563 
8564     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8565 
8566     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8567       unsigned Diag;
8568       switch (Match) {
8569       case ArgType::Match: llvm_unreachable("expected non-matching");
8570       case ArgType::NoMatchPedantic:
8571         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8572         break;
8573       case ArgType::NoMatchTypeConfusion:
8574         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8575         break;
8576       case ArgType::NoMatch:
8577         Diag = diag::warn_format_conversion_argument_type_mismatch;
8578         break;
8579       }
8580 
8581       // In this case, the specifier is wrong and should be changed to match
8582       // the argument.
8583       EmitFormatDiagnostic(S.PDiag(Diag)
8584                                << AT.getRepresentativeTypeName(S.Context)
8585                                << IntendedTy << IsEnum << E->getSourceRange(),
8586                            E->getBeginLoc(),
8587                            /*IsStringLocation*/ false, SpecRange,
8588                            FixItHint::CreateReplacement(SpecRange, os.str()));
8589     } else {
8590       // The canonical type for formatting this value is different from the
8591       // actual type of the expression. (This occurs, for example, with Darwin's
8592       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8593       // should be printed as 'long' for 64-bit compatibility.)
8594       // Rather than emitting a normal format/argument mismatch, we want to
8595       // add a cast to the recommended type (and correct the format string
8596       // if necessary).
8597       SmallString<16> CastBuf;
8598       llvm::raw_svector_ostream CastFix(CastBuf);
8599       CastFix << "(";
8600       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8601       CastFix << ")";
8602 
8603       SmallVector<FixItHint,4> Hints;
8604       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8605         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8606 
8607       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8608         // If there's already a cast present, just replace it.
8609         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8610         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8611 
8612       } else if (!requiresParensToAddCast(E)) {
8613         // If the expression has high enough precedence,
8614         // just write the C-style cast.
8615         Hints.push_back(
8616             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8617       } else {
8618         // Otherwise, add parens around the expression as well as the cast.
8619         CastFix << "(";
8620         Hints.push_back(
8621             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8622 
8623         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8624         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8625       }
8626 
8627       if (ShouldNotPrintDirectly) {
8628         // The expression has a type that should not be printed directly.
8629         // We extract the name from the typedef because we don't want to show
8630         // the underlying type in the diagnostic.
8631         StringRef Name;
8632         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8633           Name = TypedefTy->getDecl()->getName();
8634         else
8635           Name = CastTyName;
8636         unsigned Diag = Match == ArgType::NoMatchPedantic
8637                             ? diag::warn_format_argument_needs_cast_pedantic
8638                             : diag::warn_format_argument_needs_cast;
8639         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8640                                            << E->getSourceRange(),
8641                              E->getBeginLoc(), /*IsStringLocation=*/false,
8642                              SpecRange, Hints);
8643       } else {
8644         // In this case, the expression could be printed using a different
8645         // specifier, but we've decided that the specifier is probably correct
8646         // and we should cast instead. Just use the normal warning message.
8647         EmitFormatDiagnostic(
8648             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8649                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8650                 << E->getSourceRange(),
8651             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8652       }
8653     }
8654   } else {
8655     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8656                                                    SpecifierLen);
8657     // Since the warning for passing non-POD types to variadic functions
8658     // was deferred until now, we emit a warning for non-POD
8659     // arguments here.
8660     switch (S.isValidVarArgType(ExprTy)) {
8661     case Sema::VAK_Valid:
8662     case Sema::VAK_ValidInCXX11: {
8663       unsigned Diag;
8664       switch (Match) {
8665       case ArgType::Match: llvm_unreachable("expected non-matching");
8666       case ArgType::NoMatchPedantic:
8667         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8668         break;
8669       case ArgType::NoMatchTypeConfusion:
8670         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8671         break;
8672       case ArgType::NoMatch:
8673         Diag = diag::warn_format_conversion_argument_type_mismatch;
8674         break;
8675       }
8676 
8677       EmitFormatDiagnostic(
8678           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8679                         << IsEnum << CSR << E->getSourceRange(),
8680           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8681       break;
8682     }
8683     case Sema::VAK_Undefined:
8684     case Sema::VAK_MSVCUndefined:
8685       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8686                                << S.getLangOpts().CPlusPlus11 << ExprTy
8687                                << CallType
8688                                << AT.getRepresentativeTypeName(S.Context) << CSR
8689                                << E->getSourceRange(),
8690                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8691       checkForCStrMembers(AT, E);
8692       break;
8693 
8694     case Sema::VAK_Invalid:
8695       if (ExprTy->isObjCObjectType())
8696         EmitFormatDiagnostic(
8697             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8698                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8699                 << AT.getRepresentativeTypeName(S.Context) << CSR
8700                 << E->getSourceRange(),
8701             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8702       else
8703         // FIXME: If this is an initializer list, suggest removing the braces
8704         // or inserting a cast to the target type.
8705         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8706             << isa<InitListExpr>(E) << ExprTy << CallType
8707             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8708       break;
8709     }
8710 
8711     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8712            "format string specifier index out of range");
8713     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8714   }
8715 
8716   return true;
8717 }
8718 
8719 //===--- CHECK: Scanf format string checking ------------------------------===//
8720 
8721 namespace {
8722 
8723 class CheckScanfHandler : public CheckFormatHandler {
8724 public:
8725   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8726                     const Expr *origFormatExpr, Sema::FormatStringType type,
8727                     unsigned firstDataArg, unsigned numDataArgs,
8728                     const char *beg, bool hasVAListArg,
8729                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8730                     bool inFunctionCall, Sema::VariadicCallType CallType,
8731                     llvm::SmallBitVector &CheckedVarArgs,
8732                     UncoveredArgHandler &UncoveredArg)
8733       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8734                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8735                            inFunctionCall, CallType, CheckedVarArgs,
8736                            UncoveredArg) {}
8737 
8738   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8739                             const char *startSpecifier,
8740                             unsigned specifierLen) override;
8741 
8742   bool HandleInvalidScanfConversionSpecifier(
8743           const analyze_scanf::ScanfSpecifier &FS,
8744           const char *startSpecifier,
8745           unsigned specifierLen) override;
8746 
8747   void HandleIncompleteScanList(const char *start, const char *end) override;
8748 };
8749 
8750 } // namespace
8751 
8752 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8753                                                  const char *end) {
8754   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8755                        getLocationOfByte(end), /*IsStringLocation*/true,
8756                        getSpecifierRange(start, end - start));
8757 }
8758 
8759 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8760                                         const analyze_scanf::ScanfSpecifier &FS,
8761                                         const char *startSpecifier,
8762                                         unsigned specifierLen) {
8763   const analyze_scanf::ScanfConversionSpecifier &CS =
8764     FS.getConversionSpecifier();
8765 
8766   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8767                                           getLocationOfByte(CS.getStart()),
8768                                           startSpecifier, specifierLen,
8769                                           CS.getStart(), CS.getLength());
8770 }
8771 
8772 bool CheckScanfHandler::HandleScanfSpecifier(
8773                                        const analyze_scanf::ScanfSpecifier &FS,
8774                                        const char *startSpecifier,
8775                                        unsigned specifierLen) {
8776   using namespace analyze_scanf;
8777   using namespace analyze_format_string;
8778 
8779   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8780 
8781   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8782   // be used to decide if we are using positional arguments consistently.
8783   if (FS.consumesDataArgument()) {
8784     if (atFirstArg) {
8785       atFirstArg = false;
8786       usesPositionalArgs = FS.usesPositionalArg();
8787     }
8788     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8789       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8790                                         startSpecifier, specifierLen);
8791       return false;
8792     }
8793   }
8794 
8795   // Check if the field with is non-zero.
8796   const OptionalAmount &Amt = FS.getFieldWidth();
8797   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8798     if (Amt.getConstantAmount() == 0) {
8799       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8800                                                    Amt.getConstantLength());
8801       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8802                            getLocationOfByte(Amt.getStart()),
8803                            /*IsStringLocation*/true, R,
8804                            FixItHint::CreateRemoval(R));
8805     }
8806   }
8807 
8808   if (!FS.consumesDataArgument()) {
8809     // FIXME: Technically specifying a precision or field width here
8810     // makes no sense.  Worth issuing a warning at some point.
8811     return true;
8812   }
8813 
8814   // Consume the argument.
8815   unsigned argIndex = FS.getArgIndex();
8816   if (argIndex < NumDataArgs) {
8817       // The check to see if the argIndex is valid will come later.
8818       // We set the bit here because we may exit early from this
8819       // function if we encounter some other error.
8820     CoveredArgs.set(argIndex);
8821   }
8822 
8823   // Check the length modifier is valid with the given conversion specifier.
8824   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8825                                  S.getLangOpts()))
8826     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8827                                 diag::warn_format_nonsensical_length);
8828   else if (!FS.hasStandardLengthModifier())
8829     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8830   else if (!FS.hasStandardLengthConversionCombination())
8831     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8832                                 diag::warn_format_non_standard_conversion_spec);
8833 
8834   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8835     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8836 
8837   // The remaining checks depend on the data arguments.
8838   if (HasVAListArg)
8839     return true;
8840 
8841   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8842     return false;
8843 
8844   // Check that the argument type matches the format specifier.
8845   const Expr *Ex = getDataArg(argIndex);
8846   if (!Ex)
8847     return true;
8848 
8849   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8850 
8851   if (!AT.isValid()) {
8852     return true;
8853   }
8854 
8855   analyze_format_string::ArgType::MatchKind Match =
8856       AT.matchesType(S.Context, Ex->getType());
8857   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8858   if (Match == analyze_format_string::ArgType::Match)
8859     return true;
8860 
8861   ScanfSpecifier fixedFS = FS;
8862   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8863                                  S.getLangOpts(), S.Context);
8864 
8865   unsigned Diag =
8866       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8867                : diag::warn_format_conversion_argument_type_mismatch;
8868 
8869   if (Success) {
8870     // Get the fix string from the fixed format specifier.
8871     SmallString<128> buf;
8872     llvm::raw_svector_ostream os(buf);
8873     fixedFS.toString(os);
8874 
8875     EmitFormatDiagnostic(
8876         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8877                       << Ex->getType() << false << Ex->getSourceRange(),
8878         Ex->getBeginLoc(),
8879         /*IsStringLocation*/ false,
8880         getSpecifierRange(startSpecifier, specifierLen),
8881         FixItHint::CreateReplacement(
8882             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8883   } else {
8884     EmitFormatDiagnostic(S.PDiag(Diag)
8885                              << AT.getRepresentativeTypeName(S.Context)
8886                              << Ex->getType() << false << Ex->getSourceRange(),
8887                          Ex->getBeginLoc(),
8888                          /*IsStringLocation*/ false,
8889                          getSpecifierRange(startSpecifier, specifierLen));
8890   }
8891 
8892   return true;
8893 }
8894 
8895 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8896                               const Expr *OrigFormatExpr,
8897                               ArrayRef<const Expr *> Args,
8898                               bool HasVAListArg, unsigned format_idx,
8899                               unsigned firstDataArg,
8900                               Sema::FormatStringType Type,
8901                               bool inFunctionCall,
8902                               Sema::VariadicCallType CallType,
8903                               llvm::SmallBitVector &CheckedVarArgs,
8904                               UncoveredArgHandler &UncoveredArg,
8905                               bool IgnoreStringsWithoutSpecifiers) {
8906   // CHECK: is the format string a wide literal?
8907   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8908     CheckFormatHandler::EmitFormatDiagnostic(
8909         S, inFunctionCall, Args[format_idx],
8910         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8911         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8912     return;
8913   }
8914 
8915   // Str - The format string.  NOTE: this is NOT null-terminated!
8916   StringRef StrRef = FExpr->getString();
8917   const char *Str = StrRef.data();
8918   // Account for cases where the string literal is truncated in a declaration.
8919   const ConstantArrayType *T =
8920     S.Context.getAsConstantArrayType(FExpr->getType());
8921   assert(T && "String literal not of constant array type!");
8922   size_t TypeSize = T->getSize().getZExtValue();
8923   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8924   const unsigned numDataArgs = Args.size() - firstDataArg;
8925 
8926   if (IgnoreStringsWithoutSpecifiers &&
8927       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8928           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8929     return;
8930 
8931   // Emit a warning if the string literal is truncated and does not contain an
8932   // embedded null character.
8933   if (TypeSize <= StrRef.size() &&
8934       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8935     CheckFormatHandler::EmitFormatDiagnostic(
8936         S, inFunctionCall, Args[format_idx],
8937         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8938         FExpr->getBeginLoc(),
8939         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8940     return;
8941   }
8942 
8943   // CHECK: empty format string?
8944   if (StrLen == 0 && numDataArgs > 0) {
8945     CheckFormatHandler::EmitFormatDiagnostic(
8946         S, inFunctionCall, Args[format_idx],
8947         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8948         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8949     return;
8950   }
8951 
8952   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8953       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8954       Type == Sema::FST_OSTrace) {
8955     CheckPrintfHandler H(
8956         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8957         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8958         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8959         CheckedVarArgs, UncoveredArg);
8960 
8961     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8962                                                   S.getLangOpts(),
8963                                                   S.Context.getTargetInfo(),
8964                                             Type == Sema::FST_FreeBSDKPrintf))
8965       H.DoneProcessing();
8966   } else if (Type == Sema::FST_Scanf) {
8967     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8968                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8969                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8970 
8971     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8972                                                  S.getLangOpts(),
8973                                                  S.Context.getTargetInfo()))
8974       H.DoneProcessing();
8975   } // TODO: handle other formats
8976 }
8977 
8978 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8979   // Str - The format string.  NOTE: this is NOT null-terminated!
8980   StringRef StrRef = FExpr->getString();
8981   const char *Str = StrRef.data();
8982   // Account for cases where the string literal is truncated in a declaration.
8983   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8984   assert(T && "String literal not of constant array type!");
8985   size_t TypeSize = T->getSize().getZExtValue();
8986   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8987   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8988                                                          getLangOpts(),
8989                                                          Context.getTargetInfo());
8990 }
8991 
8992 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8993 
8994 // Returns the related absolute value function that is larger, of 0 if one
8995 // does not exist.
8996 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8997   switch (AbsFunction) {
8998   default:
8999     return 0;
9000 
9001   case Builtin::BI__builtin_abs:
9002     return Builtin::BI__builtin_labs;
9003   case Builtin::BI__builtin_labs:
9004     return Builtin::BI__builtin_llabs;
9005   case Builtin::BI__builtin_llabs:
9006     return 0;
9007 
9008   case Builtin::BI__builtin_fabsf:
9009     return Builtin::BI__builtin_fabs;
9010   case Builtin::BI__builtin_fabs:
9011     return Builtin::BI__builtin_fabsl;
9012   case Builtin::BI__builtin_fabsl:
9013     return 0;
9014 
9015   case Builtin::BI__builtin_cabsf:
9016     return Builtin::BI__builtin_cabs;
9017   case Builtin::BI__builtin_cabs:
9018     return Builtin::BI__builtin_cabsl;
9019   case Builtin::BI__builtin_cabsl:
9020     return 0;
9021 
9022   case Builtin::BIabs:
9023     return Builtin::BIlabs;
9024   case Builtin::BIlabs:
9025     return Builtin::BIllabs;
9026   case Builtin::BIllabs:
9027     return 0;
9028 
9029   case Builtin::BIfabsf:
9030     return Builtin::BIfabs;
9031   case Builtin::BIfabs:
9032     return Builtin::BIfabsl;
9033   case Builtin::BIfabsl:
9034     return 0;
9035 
9036   case Builtin::BIcabsf:
9037    return Builtin::BIcabs;
9038   case Builtin::BIcabs:
9039     return Builtin::BIcabsl;
9040   case Builtin::BIcabsl:
9041     return 0;
9042   }
9043 }
9044 
9045 // Returns the argument type of the absolute value function.
9046 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9047                                              unsigned AbsType) {
9048   if (AbsType == 0)
9049     return QualType();
9050 
9051   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9052   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9053   if (Error != ASTContext::GE_None)
9054     return QualType();
9055 
9056   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9057   if (!FT)
9058     return QualType();
9059 
9060   if (FT->getNumParams() != 1)
9061     return QualType();
9062 
9063   return FT->getParamType(0);
9064 }
9065 
9066 // Returns the best absolute value function, or zero, based on type and
9067 // current absolute value function.
9068 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9069                                    unsigned AbsFunctionKind) {
9070   unsigned BestKind = 0;
9071   uint64_t ArgSize = Context.getTypeSize(ArgType);
9072   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9073        Kind = getLargerAbsoluteValueFunction(Kind)) {
9074     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9075     if (Context.getTypeSize(ParamType) >= ArgSize) {
9076       if (BestKind == 0)
9077         BestKind = Kind;
9078       else if (Context.hasSameType(ParamType, ArgType)) {
9079         BestKind = Kind;
9080         break;
9081       }
9082     }
9083   }
9084   return BestKind;
9085 }
9086 
9087 enum AbsoluteValueKind {
9088   AVK_Integer,
9089   AVK_Floating,
9090   AVK_Complex
9091 };
9092 
9093 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9094   if (T->isIntegralOrEnumerationType())
9095     return AVK_Integer;
9096   if (T->isRealFloatingType())
9097     return AVK_Floating;
9098   if (T->isAnyComplexType())
9099     return AVK_Complex;
9100 
9101   llvm_unreachable("Type not integer, floating, or complex");
9102 }
9103 
9104 // Changes the absolute value function to a different type.  Preserves whether
9105 // the function is a builtin.
9106 static unsigned changeAbsFunction(unsigned AbsKind,
9107                                   AbsoluteValueKind ValueKind) {
9108   switch (ValueKind) {
9109   case AVK_Integer:
9110     switch (AbsKind) {
9111     default:
9112       return 0;
9113     case Builtin::BI__builtin_fabsf:
9114     case Builtin::BI__builtin_fabs:
9115     case Builtin::BI__builtin_fabsl:
9116     case Builtin::BI__builtin_cabsf:
9117     case Builtin::BI__builtin_cabs:
9118     case Builtin::BI__builtin_cabsl:
9119       return Builtin::BI__builtin_abs;
9120     case Builtin::BIfabsf:
9121     case Builtin::BIfabs:
9122     case Builtin::BIfabsl:
9123     case Builtin::BIcabsf:
9124     case Builtin::BIcabs:
9125     case Builtin::BIcabsl:
9126       return Builtin::BIabs;
9127     }
9128   case AVK_Floating:
9129     switch (AbsKind) {
9130     default:
9131       return 0;
9132     case Builtin::BI__builtin_abs:
9133     case Builtin::BI__builtin_labs:
9134     case Builtin::BI__builtin_llabs:
9135     case Builtin::BI__builtin_cabsf:
9136     case Builtin::BI__builtin_cabs:
9137     case Builtin::BI__builtin_cabsl:
9138       return Builtin::BI__builtin_fabsf;
9139     case Builtin::BIabs:
9140     case Builtin::BIlabs:
9141     case Builtin::BIllabs:
9142     case Builtin::BIcabsf:
9143     case Builtin::BIcabs:
9144     case Builtin::BIcabsl:
9145       return Builtin::BIfabsf;
9146     }
9147   case AVK_Complex:
9148     switch (AbsKind) {
9149     default:
9150       return 0;
9151     case Builtin::BI__builtin_abs:
9152     case Builtin::BI__builtin_labs:
9153     case Builtin::BI__builtin_llabs:
9154     case Builtin::BI__builtin_fabsf:
9155     case Builtin::BI__builtin_fabs:
9156     case Builtin::BI__builtin_fabsl:
9157       return Builtin::BI__builtin_cabsf;
9158     case Builtin::BIabs:
9159     case Builtin::BIlabs:
9160     case Builtin::BIllabs:
9161     case Builtin::BIfabsf:
9162     case Builtin::BIfabs:
9163     case Builtin::BIfabsl:
9164       return Builtin::BIcabsf;
9165     }
9166   }
9167   llvm_unreachable("Unable to convert function");
9168 }
9169 
9170 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9171   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9172   if (!FnInfo)
9173     return 0;
9174 
9175   switch (FDecl->getBuiltinID()) {
9176   default:
9177     return 0;
9178   case Builtin::BI__builtin_abs:
9179   case Builtin::BI__builtin_fabs:
9180   case Builtin::BI__builtin_fabsf:
9181   case Builtin::BI__builtin_fabsl:
9182   case Builtin::BI__builtin_labs:
9183   case Builtin::BI__builtin_llabs:
9184   case Builtin::BI__builtin_cabs:
9185   case Builtin::BI__builtin_cabsf:
9186   case Builtin::BI__builtin_cabsl:
9187   case Builtin::BIabs:
9188   case Builtin::BIlabs:
9189   case Builtin::BIllabs:
9190   case Builtin::BIfabs:
9191   case Builtin::BIfabsf:
9192   case Builtin::BIfabsl:
9193   case Builtin::BIcabs:
9194   case Builtin::BIcabsf:
9195   case Builtin::BIcabsl:
9196     return FDecl->getBuiltinID();
9197   }
9198   llvm_unreachable("Unknown Builtin type");
9199 }
9200 
9201 // If the replacement is valid, emit a note with replacement function.
9202 // Additionally, suggest including the proper header if not already included.
9203 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9204                             unsigned AbsKind, QualType ArgType) {
9205   bool EmitHeaderHint = true;
9206   const char *HeaderName = nullptr;
9207   const char *FunctionName = nullptr;
9208   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9209     FunctionName = "std::abs";
9210     if (ArgType->isIntegralOrEnumerationType()) {
9211       HeaderName = "cstdlib";
9212     } else if (ArgType->isRealFloatingType()) {
9213       HeaderName = "cmath";
9214     } else {
9215       llvm_unreachable("Invalid Type");
9216     }
9217 
9218     // Lookup all std::abs
9219     if (NamespaceDecl *Std = S.getStdNamespace()) {
9220       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9221       R.suppressDiagnostics();
9222       S.LookupQualifiedName(R, Std);
9223 
9224       for (const auto *I : R) {
9225         const FunctionDecl *FDecl = nullptr;
9226         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9227           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9228         } else {
9229           FDecl = dyn_cast<FunctionDecl>(I);
9230         }
9231         if (!FDecl)
9232           continue;
9233 
9234         // Found std::abs(), check that they are the right ones.
9235         if (FDecl->getNumParams() != 1)
9236           continue;
9237 
9238         // Check that the parameter type can handle the argument.
9239         QualType ParamType = FDecl->getParamDecl(0)->getType();
9240         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9241             S.Context.getTypeSize(ArgType) <=
9242                 S.Context.getTypeSize(ParamType)) {
9243           // Found a function, don't need the header hint.
9244           EmitHeaderHint = false;
9245           break;
9246         }
9247       }
9248     }
9249   } else {
9250     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9251     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9252 
9253     if (HeaderName) {
9254       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9255       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9256       R.suppressDiagnostics();
9257       S.LookupName(R, S.getCurScope());
9258 
9259       if (R.isSingleResult()) {
9260         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9261         if (FD && FD->getBuiltinID() == AbsKind) {
9262           EmitHeaderHint = false;
9263         } else {
9264           return;
9265         }
9266       } else if (!R.empty()) {
9267         return;
9268       }
9269     }
9270   }
9271 
9272   S.Diag(Loc, diag::note_replace_abs_function)
9273       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9274 
9275   if (!HeaderName)
9276     return;
9277 
9278   if (!EmitHeaderHint)
9279     return;
9280 
9281   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9282                                                     << FunctionName;
9283 }
9284 
9285 template <std::size_t StrLen>
9286 static bool IsStdFunction(const FunctionDecl *FDecl,
9287                           const char (&Str)[StrLen]) {
9288   if (!FDecl)
9289     return false;
9290   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9291     return false;
9292   if (!FDecl->isInStdNamespace())
9293     return false;
9294 
9295   return true;
9296 }
9297 
9298 // Warn when using the wrong abs() function.
9299 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9300                                       const FunctionDecl *FDecl) {
9301   if (Call->getNumArgs() != 1)
9302     return;
9303 
9304   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9305   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9306   if (AbsKind == 0 && !IsStdAbs)
9307     return;
9308 
9309   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9310   QualType ParamType = Call->getArg(0)->getType();
9311 
9312   // Unsigned types cannot be negative.  Suggest removing the absolute value
9313   // function call.
9314   if (ArgType->isUnsignedIntegerType()) {
9315     const char *FunctionName =
9316         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9317     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9318     Diag(Call->getExprLoc(), diag::note_remove_abs)
9319         << FunctionName
9320         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9321     return;
9322   }
9323 
9324   // Taking the absolute value of a pointer is very suspicious, they probably
9325   // wanted to index into an array, dereference a pointer, call a function, etc.
9326   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9327     unsigned DiagType = 0;
9328     if (ArgType->isFunctionType())
9329       DiagType = 1;
9330     else if (ArgType->isArrayType())
9331       DiagType = 2;
9332 
9333     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9334     return;
9335   }
9336 
9337   // std::abs has overloads which prevent most of the absolute value problems
9338   // from occurring.
9339   if (IsStdAbs)
9340     return;
9341 
9342   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9343   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9344 
9345   // The argument and parameter are the same kind.  Check if they are the right
9346   // size.
9347   if (ArgValueKind == ParamValueKind) {
9348     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9349       return;
9350 
9351     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9352     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9353         << FDecl << ArgType << ParamType;
9354 
9355     if (NewAbsKind == 0)
9356       return;
9357 
9358     emitReplacement(*this, Call->getExprLoc(),
9359                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9360     return;
9361   }
9362 
9363   // ArgValueKind != ParamValueKind
9364   // The wrong type of absolute value function was used.  Attempt to find the
9365   // proper one.
9366   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9367   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9368   if (NewAbsKind == 0)
9369     return;
9370 
9371   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9372       << FDecl << ParamValueKind << ArgValueKind;
9373 
9374   emitReplacement(*this, Call->getExprLoc(),
9375                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9376 }
9377 
9378 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9379 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9380                                 const FunctionDecl *FDecl) {
9381   if (!Call || !FDecl) return;
9382 
9383   // Ignore template specializations and macros.
9384   if (inTemplateInstantiation()) return;
9385   if (Call->getExprLoc().isMacroID()) return;
9386 
9387   // Only care about the one template argument, two function parameter std::max
9388   if (Call->getNumArgs() != 2) return;
9389   if (!IsStdFunction(FDecl, "max")) return;
9390   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9391   if (!ArgList) return;
9392   if (ArgList->size() != 1) return;
9393 
9394   // Check that template type argument is unsigned integer.
9395   const auto& TA = ArgList->get(0);
9396   if (TA.getKind() != TemplateArgument::Type) return;
9397   QualType ArgType = TA.getAsType();
9398   if (!ArgType->isUnsignedIntegerType()) return;
9399 
9400   // See if either argument is a literal zero.
9401   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9402     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9403     if (!MTE) return false;
9404     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9405     if (!Num) return false;
9406     if (Num->getValue() != 0) return false;
9407     return true;
9408   };
9409 
9410   const Expr *FirstArg = Call->getArg(0);
9411   const Expr *SecondArg = Call->getArg(1);
9412   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9413   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9414 
9415   // Only warn when exactly one argument is zero.
9416   if (IsFirstArgZero == IsSecondArgZero) return;
9417 
9418   SourceRange FirstRange = FirstArg->getSourceRange();
9419   SourceRange SecondRange = SecondArg->getSourceRange();
9420 
9421   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9422 
9423   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9424       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9425 
9426   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9427   SourceRange RemovalRange;
9428   if (IsFirstArgZero) {
9429     RemovalRange = SourceRange(FirstRange.getBegin(),
9430                                SecondRange.getBegin().getLocWithOffset(-1));
9431   } else {
9432     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9433                                SecondRange.getEnd());
9434   }
9435 
9436   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9437         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9438         << FixItHint::CreateRemoval(RemovalRange);
9439 }
9440 
9441 //===--- CHECK: Standard memory functions ---------------------------------===//
9442 
9443 /// Takes the expression passed to the size_t parameter of functions
9444 /// such as memcmp, strncat, etc and warns if it's a comparison.
9445 ///
9446 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9447 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9448                                            IdentifierInfo *FnName,
9449                                            SourceLocation FnLoc,
9450                                            SourceLocation RParenLoc) {
9451   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9452   if (!Size)
9453     return false;
9454 
9455   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9456   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9457     return false;
9458 
9459   SourceRange SizeRange = Size->getSourceRange();
9460   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9461       << SizeRange << FnName;
9462   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9463       << FnName
9464       << FixItHint::CreateInsertion(
9465              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9466       << FixItHint::CreateRemoval(RParenLoc);
9467   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9468       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9469       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9470                                     ")");
9471 
9472   return true;
9473 }
9474 
9475 /// Determine whether the given type is or contains a dynamic class type
9476 /// (e.g., whether it has a vtable).
9477 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9478                                                      bool &IsContained) {
9479   // Look through array types while ignoring qualifiers.
9480   const Type *Ty = T->getBaseElementTypeUnsafe();
9481   IsContained = false;
9482 
9483   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9484   RD = RD ? RD->getDefinition() : nullptr;
9485   if (!RD || RD->isInvalidDecl())
9486     return nullptr;
9487 
9488   if (RD->isDynamicClass())
9489     return RD;
9490 
9491   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9492   // It's impossible for a class to transitively contain itself by value, so
9493   // infinite recursion is impossible.
9494   for (auto *FD : RD->fields()) {
9495     bool SubContained;
9496     if (const CXXRecordDecl *ContainedRD =
9497             getContainedDynamicClass(FD->getType(), SubContained)) {
9498       IsContained = true;
9499       return ContainedRD;
9500     }
9501   }
9502 
9503   return nullptr;
9504 }
9505 
9506 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9507   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9508     if (Unary->getKind() == UETT_SizeOf)
9509       return Unary;
9510   return nullptr;
9511 }
9512 
9513 /// If E is a sizeof expression, returns its argument expression,
9514 /// otherwise returns NULL.
9515 static const Expr *getSizeOfExprArg(const Expr *E) {
9516   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9517     if (!SizeOf->isArgumentType())
9518       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9519   return nullptr;
9520 }
9521 
9522 /// If E is a sizeof expression, returns its argument type.
9523 static QualType getSizeOfArgType(const Expr *E) {
9524   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9525     return SizeOf->getTypeOfArgument();
9526   return QualType();
9527 }
9528 
9529 namespace {
9530 
9531 struct SearchNonTrivialToInitializeField
9532     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9533   using Super =
9534       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9535 
9536   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9537 
9538   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9539                      SourceLocation SL) {
9540     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9541       asDerived().visitArray(PDIK, AT, SL);
9542       return;
9543     }
9544 
9545     Super::visitWithKind(PDIK, FT, SL);
9546   }
9547 
9548   void visitARCStrong(QualType FT, SourceLocation SL) {
9549     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9550   }
9551   void visitARCWeak(QualType FT, SourceLocation SL) {
9552     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9553   }
9554   void visitStruct(QualType FT, SourceLocation SL) {
9555     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9556       visit(FD->getType(), FD->getLocation());
9557   }
9558   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9559                   const ArrayType *AT, SourceLocation SL) {
9560     visit(getContext().getBaseElementType(AT), SL);
9561   }
9562   void visitTrivial(QualType FT, SourceLocation SL) {}
9563 
9564   static void diag(QualType RT, const Expr *E, Sema &S) {
9565     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9566   }
9567 
9568   ASTContext &getContext() { return S.getASTContext(); }
9569 
9570   const Expr *E;
9571   Sema &S;
9572 };
9573 
9574 struct SearchNonTrivialToCopyField
9575     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9576   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9577 
9578   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9579 
9580   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9581                      SourceLocation SL) {
9582     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9583       asDerived().visitArray(PCK, AT, SL);
9584       return;
9585     }
9586 
9587     Super::visitWithKind(PCK, FT, SL);
9588   }
9589 
9590   void visitARCStrong(QualType FT, SourceLocation SL) {
9591     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9592   }
9593   void visitARCWeak(QualType FT, SourceLocation SL) {
9594     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9595   }
9596   void visitStruct(QualType FT, SourceLocation SL) {
9597     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9598       visit(FD->getType(), FD->getLocation());
9599   }
9600   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9601                   SourceLocation SL) {
9602     visit(getContext().getBaseElementType(AT), SL);
9603   }
9604   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9605                 SourceLocation SL) {}
9606   void visitTrivial(QualType FT, SourceLocation SL) {}
9607   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9608 
9609   static void diag(QualType RT, const Expr *E, Sema &S) {
9610     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9611   }
9612 
9613   ASTContext &getContext() { return S.getASTContext(); }
9614 
9615   const Expr *E;
9616   Sema &S;
9617 };
9618 
9619 }
9620 
9621 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9622 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9623   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9624 
9625   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9626     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9627       return false;
9628 
9629     return doesExprLikelyComputeSize(BO->getLHS()) ||
9630            doesExprLikelyComputeSize(BO->getRHS());
9631   }
9632 
9633   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9634 }
9635 
9636 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9637 ///
9638 /// \code
9639 ///   #define MACRO 0
9640 ///   foo(MACRO);
9641 ///   foo(0);
9642 /// \endcode
9643 ///
9644 /// This should return true for the first call to foo, but not for the second
9645 /// (regardless of whether foo is a macro or function).
9646 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9647                                         SourceLocation CallLoc,
9648                                         SourceLocation ArgLoc) {
9649   if (!CallLoc.isMacroID())
9650     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9651 
9652   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9653          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9654 }
9655 
9656 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9657 /// last two arguments transposed.
9658 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9659   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9660     return;
9661 
9662   const Expr *SizeArg =
9663     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9664 
9665   auto isLiteralZero = [](const Expr *E) {
9666     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9667   };
9668 
9669   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9670   SourceLocation CallLoc = Call->getRParenLoc();
9671   SourceManager &SM = S.getSourceManager();
9672   if (isLiteralZero(SizeArg) &&
9673       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9674 
9675     SourceLocation DiagLoc = SizeArg->getExprLoc();
9676 
9677     // Some platforms #define bzero to __builtin_memset. See if this is the
9678     // case, and if so, emit a better diagnostic.
9679     if (BId == Builtin::BIbzero ||
9680         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9681                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9682       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9683       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9684     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9685       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9686       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9687     }
9688     return;
9689   }
9690 
9691   // If the second argument to a memset is a sizeof expression and the third
9692   // isn't, this is also likely an error. This should catch
9693   // 'memset(buf, sizeof(buf), 0xff)'.
9694   if (BId == Builtin::BImemset &&
9695       doesExprLikelyComputeSize(Call->getArg(1)) &&
9696       !doesExprLikelyComputeSize(Call->getArg(2))) {
9697     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9698     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9699     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9700     return;
9701   }
9702 }
9703 
9704 /// Check for dangerous or invalid arguments to memset().
9705 ///
9706 /// This issues warnings on known problematic, dangerous or unspecified
9707 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9708 /// function calls.
9709 ///
9710 /// \param Call The call expression to diagnose.
9711 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9712                                    unsigned BId,
9713                                    IdentifierInfo *FnName) {
9714   assert(BId != 0);
9715 
9716   // It is possible to have a non-standard definition of memset.  Validate
9717   // we have enough arguments, and if not, abort further checking.
9718   unsigned ExpectedNumArgs =
9719       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9720   if (Call->getNumArgs() < ExpectedNumArgs)
9721     return;
9722 
9723   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9724                       BId == Builtin::BIstrndup ? 1 : 2);
9725   unsigned LenArg =
9726       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9727   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9728 
9729   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9730                                      Call->getBeginLoc(), Call->getRParenLoc()))
9731     return;
9732 
9733   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9734   CheckMemaccessSize(*this, BId, Call);
9735 
9736   // We have special checking when the length is a sizeof expression.
9737   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9738   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9739   llvm::FoldingSetNodeID SizeOfArgID;
9740 
9741   // Although widely used, 'bzero' is not a standard function. Be more strict
9742   // with the argument types before allowing diagnostics and only allow the
9743   // form bzero(ptr, sizeof(...)).
9744   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9745   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9746     return;
9747 
9748   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9749     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9750     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9751 
9752     QualType DestTy = Dest->getType();
9753     QualType PointeeTy;
9754     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9755       PointeeTy = DestPtrTy->getPointeeType();
9756 
9757       // Never warn about void type pointers. This can be used to suppress
9758       // false positives.
9759       if (PointeeTy->isVoidType())
9760         continue;
9761 
9762       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9763       // actually comparing the expressions for equality. Because computing the
9764       // expression IDs can be expensive, we only do this if the diagnostic is
9765       // enabled.
9766       if (SizeOfArg &&
9767           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9768                            SizeOfArg->getExprLoc())) {
9769         // We only compute IDs for expressions if the warning is enabled, and
9770         // cache the sizeof arg's ID.
9771         if (SizeOfArgID == llvm::FoldingSetNodeID())
9772           SizeOfArg->Profile(SizeOfArgID, Context, true);
9773         llvm::FoldingSetNodeID DestID;
9774         Dest->Profile(DestID, Context, true);
9775         if (DestID == SizeOfArgID) {
9776           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9777           //       over sizeof(src) as well.
9778           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9779           StringRef ReadableName = FnName->getName();
9780 
9781           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9782             if (UnaryOp->getOpcode() == UO_AddrOf)
9783               ActionIdx = 1; // If its an address-of operator, just remove it.
9784           if (!PointeeTy->isIncompleteType() &&
9785               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9786             ActionIdx = 2; // If the pointee's size is sizeof(char),
9787                            // suggest an explicit length.
9788 
9789           // If the function is defined as a builtin macro, do not show macro
9790           // expansion.
9791           SourceLocation SL = SizeOfArg->getExprLoc();
9792           SourceRange DSR = Dest->getSourceRange();
9793           SourceRange SSR = SizeOfArg->getSourceRange();
9794           SourceManager &SM = getSourceManager();
9795 
9796           if (SM.isMacroArgExpansion(SL)) {
9797             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9798             SL = SM.getSpellingLoc(SL);
9799             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9800                              SM.getSpellingLoc(DSR.getEnd()));
9801             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9802                              SM.getSpellingLoc(SSR.getEnd()));
9803           }
9804 
9805           DiagRuntimeBehavior(SL, SizeOfArg,
9806                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9807                                 << ReadableName
9808                                 << PointeeTy
9809                                 << DestTy
9810                                 << DSR
9811                                 << SSR);
9812           DiagRuntimeBehavior(SL, SizeOfArg,
9813                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9814                                 << ActionIdx
9815                                 << SSR);
9816 
9817           break;
9818         }
9819       }
9820 
9821       // Also check for cases where the sizeof argument is the exact same
9822       // type as the memory argument, and where it points to a user-defined
9823       // record type.
9824       if (SizeOfArgTy != QualType()) {
9825         if (PointeeTy->isRecordType() &&
9826             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9827           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9828                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9829                                 << FnName << SizeOfArgTy << ArgIdx
9830                                 << PointeeTy << Dest->getSourceRange()
9831                                 << LenExpr->getSourceRange());
9832           break;
9833         }
9834       }
9835     } else if (DestTy->isArrayType()) {
9836       PointeeTy = DestTy;
9837     }
9838 
9839     if (PointeeTy == QualType())
9840       continue;
9841 
9842     // Always complain about dynamic classes.
9843     bool IsContained;
9844     if (const CXXRecordDecl *ContainedRD =
9845             getContainedDynamicClass(PointeeTy, IsContained)) {
9846 
9847       unsigned OperationType = 0;
9848       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9849       // "overwritten" if we're warning about the destination for any call
9850       // but memcmp; otherwise a verb appropriate to the call.
9851       if (ArgIdx != 0 || IsCmp) {
9852         if (BId == Builtin::BImemcpy)
9853           OperationType = 1;
9854         else if(BId == Builtin::BImemmove)
9855           OperationType = 2;
9856         else if (IsCmp)
9857           OperationType = 3;
9858       }
9859 
9860       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9861                           PDiag(diag::warn_dyn_class_memaccess)
9862                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9863                               << IsContained << ContainedRD << OperationType
9864                               << Call->getCallee()->getSourceRange());
9865     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9866              BId != Builtin::BImemset)
9867       DiagRuntimeBehavior(
9868         Dest->getExprLoc(), Dest,
9869         PDiag(diag::warn_arc_object_memaccess)
9870           << ArgIdx << FnName << PointeeTy
9871           << Call->getCallee()->getSourceRange());
9872     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9873       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9874           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9875         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9876                             PDiag(diag::warn_cstruct_memaccess)
9877                                 << ArgIdx << FnName << PointeeTy << 0);
9878         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9879       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9880                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9881         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9882                             PDiag(diag::warn_cstruct_memaccess)
9883                                 << ArgIdx << FnName << PointeeTy << 1);
9884         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9885       } else {
9886         continue;
9887       }
9888     } else
9889       continue;
9890 
9891     DiagRuntimeBehavior(
9892       Dest->getExprLoc(), Dest,
9893       PDiag(diag::note_bad_memaccess_silence)
9894         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9895     break;
9896   }
9897 }
9898 
9899 // A little helper routine: ignore addition and subtraction of integer literals.
9900 // This intentionally does not ignore all integer constant expressions because
9901 // we don't want to remove sizeof().
9902 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9903   Ex = Ex->IgnoreParenCasts();
9904 
9905   while (true) {
9906     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9907     if (!BO || !BO->isAdditiveOp())
9908       break;
9909 
9910     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9911     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9912 
9913     if (isa<IntegerLiteral>(RHS))
9914       Ex = LHS;
9915     else if (isa<IntegerLiteral>(LHS))
9916       Ex = RHS;
9917     else
9918       break;
9919   }
9920 
9921   return Ex;
9922 }
9923 
9924 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9925                                                       ASTContext &Context) {
9926   // Only handle constant-sized or VLAs, but not flexible members.
9927   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9928     // Only issue the FIXIT for arrays of size > 1.
9929     if (CAT->getSize().getSExtValue() <= 1)
9930       return false;
9931   } else if (!Ty->isVariableArrayType()) {
9932     return false;
9933   }
9934   return true;
9935 }
9936 
9937 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9938 // be the size of the source, instead of the destination.
9939 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9940                                     IdentifierInfo *FnName) {
9941 
9942   // Don't crash if the user has the wrong number of arguments
9943   unsigned NumArgs = Call->getNumArgs();
9944   if ((NumArgs != 3) && (NumArgs != 4))
9945     return;
9946 
9947   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9948   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9949   const Expr *CompareWithSrc = nullptr;
9950 
9951   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9952                                      Call->getBeginLoc(), Call->getRParenLoc()))
9953     return;
9954 
9955   // Look for 'strlcpy(dst, x, sizeof(x))'
9956   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9957     CompareWithSrc = Ex;
9958   else {
9959     // Look for 'strlcpy(dst, x, strlen(x))'
9960     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9961       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9962           SizeCall->getNumArgs() == 1)
9963         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9964     }
9965   }
9966 
9967   if (!CompareWithSrc)
9968     return;
9969 
9970   // Determine if the argument to sizeof/strlen is equal to the source
9971   // argument.  In principle there's all kinds of things you could do
9972   // here, for instance creating an == expression and evaluating it with
9973   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9974   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9975   if (!SrcArgDRE)
9976     return;
9977 
9978   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9979   if (!CompareWithSrcDRE ||
9980       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9981     return;
9982 
9983   const Expr *OriginalSizeArg = Call->getArg(2);
9984   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9985       << OriginalSizeArg->getSourceRange() << FnName;
9986 
9987   // Output a FIXIT hint if the destination is an array (rather than a
9988   // pointer to an array).  This could be enhanced to handle some
9989   // pointers if we know the actual size, like if DstArg is 'array+2'
9990   // we could say 'sizeof(array)-2'.
9991   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9992   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9993     return;
9994 
9995   SmallString<128> sizeString;
9996   llvm::raw_svector_ostream OS(sizeString);
9997   OS << "sizeof(";
9998   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9999   OS << ")";
10000 
10001   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10002       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10003                                       OS.str());
10004 }
10005 
10006 /// Check if two expressions refer to the same declaration.
10007 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10008   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10009     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10010       return D1->getDecl() == D2->getDecl();
10011   return false;
10012 }
10013 
10014 static const Expr *getStrlenExprArg(const Expr *E) {
10015   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10016     const FunctionDecl *FD = CE->getDirectCallee();
10017     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10018       return nullptr;
10019     return CE->getArg(0)->IgnoreParenCasts();
10020   }
10021   return nullptr;
10022 }
10023 
10024 // Warn on anti-patterns as the 'size' argument to strncat.
10025 // The correct size argument should look like following:
10026 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10027 void Sema::CheckStrncatArguments(const CallExpr *CE,
10028                                  IdentifierInfo *FnName) {
10029   // Don't crash if the user has the wrong number of arguments.
10030   if (CE->getNumArgs() < 3)
10031     return;
10032   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10033   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10034   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10035 
10036   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10037                                      CE->getRParenLoc()))
10038     return;
10039 
10040   // Identify common expressions, which are wrongly used as the size argument
10041   // to strncat and may lead to buffer overflows.
10042   unsigned PatternType = 0;
10043   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10044     // - sizeof(dst)
10045     if (referToTheSameDecl(SizeOfArg, DstArg))
10046       PatternType = 1;
10047     // - sizeof(src)
10048     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10049       PatternType = 2;
10050   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10051     if (BE->getOpcode() == BO_Sub) {
10052       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10053       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10054       // - sizeof(dst) - strlen(dst)
10055       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10056           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10057         PatternType = 1;
10058       // - sizeof(src) - (anything)
10059       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10060         PatternType = 2;
10061     }
10062   }
10063 
10064   if (PatternType == 0)
10065     return;
10066 
10067   // Generate the diagnostic.
10068   SourceLocation SL = LenArg->getBeginLoc();
10069   SourceRange SR = LenArg->getSourceRange();
10070   SourceManager &SM = getSourceManager();
10071 
10072   // If the function is defined as a builtin macro, do not show macro expansion.
10073   if (SM.isMacroArgExpansion(SL)) {
10074     SL = SM.getSpellingLoc(SL);
10075     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10076                      SM.getSpellingLoc(SR.getEnd()));
10077   }
10078 
10079   // Check if the destination is an array (rather than a pointer to an array).
10080   QualType DstTy = DstArg->getType();
10081   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10082                                                                     Context);
10083   if (!isKnownSizeArray) {
10084     if (PatternType == 1)
10085       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10086     else
10087       Diag(SL, diag::warn_strncat_src_size) << SR;
10088     return;
10089   }
10090 
10091   if (PatternType == 1)
10092     Diag(SL, diag::warn_strncat_large_size) << SR;
10093   else
10094     Diag(SL, diag::warn_strncat_src_size) << SR;
10095 
10096   SmallString<128> sizeString;
10097   llvm::raw_svector_ostream OS(sizeString);
10098   OS << "sizeof(";
10099   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10100   OS << ") - ";
10101   OS << "strlen(";
10102   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10103   OS << ") - 1";
10104 
10105   Diag(SL, diag::note_strncat_wrong_size)
10106     << FixItHint::CreateReplacement(SR, OS.str());
10107 }
10108 
10109 namespace {
10110 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10111                                 const UnaryOperator *UnaryExpr,
10112                                 const VarDecl *Var) {
10113   StorageClass Class = Var->getStorageClass();
10114   if (Class == StorageClass::SC_Extern ||
10115       Class == StorageClass::SC_PrivateExtern ||
10116       Var->getType()->isReferenceType())
10117     return;
10118 
10119   S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10120       << CalleeName << Var;
10121 }
10122 
10123 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10124                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10125   if (const auto *Field = dyn_cast<FieldDecl>(D))
10126     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10127         << CalleeName << Field;
10128 }
10129 
10130 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10131                                  const UnaryOperator *UnaryExpr) {
10132   if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
10133     return;
10134 
10135   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr()))
10136     if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()))
10137       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);
10138 
10139   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10140     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10141                                       Lvalue->getMemberDecl());
10142 }
10143 
10144 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10145                                   const DeclRefExpr *Lvalue) {
10146   if (!Lvalue->getType()->isArrayType())
10147     return;
10148 
10149   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10150   if (Var == nullptr)
10151     return;
10152 
10153   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10154       << CalleeName << Var;
10155 }
10156 } // namespace
10157 
10158 /// Alerts the user that they are attempting to free a non-malloc'd object.
10159 void Sema::CheckFreeArguments(const CallExpr *E) {
10160   const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10161   const std::string CalleeName =
10162       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10163 
10164   if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10165     return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10166 
10167   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10168     return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10169 }
10170 
10171 void
10172 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10173                          SourceLocation ReturnLoc,
10174                          bool isObjCMethod,
10175                          const AttrVec *Attrs,
10176                          const FunctionDecl *FD) {
10177   // Check if the return value is null but should not be.
10178   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10179        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10180       CheckNonNullExpr(*this, RetValExp))
10181     Diag(ReturnLoc, diag::warn_null_ret)
10182       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10183 
10184   // C++11 [basic.stc.dynamic.allocation]p4:
10185   //   If an allocation function declared with a non-throwing
10186   //   exception-specification fails to allocate storage, it shall return
10187   //   a null pointer. Any other allocation function that fails to allocate
10188   //   storage shall indicate failure only by throwing an exception [...]
10189   if (FD) {
10190     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10191     if (Op == OO_New || Op == OO_Array_New) {
10192       const FunctionProtoType *Proto
10193         = FD->getType()->castAs<FunctionProtoType>();
10194       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10195           CheckNonNullExpr(*this, RetValExp))
10196         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10197           << FD << getLangOpts().CPlusPlus11;
10198     }
10199   }
10200 }
10201 
10202 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10203 
10204 /// Check for comparisons of floating point operands using != and ==.
10205 /// Issue a warning if these are no self-comparisons, as they are not likely
10206 /// to do what the programmer intended.
10207 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10208   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10209   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10210 
10211   // Special case: check for x == x (which is OK).
10212   // Do not emit warnings for such cases.
10213   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10214     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10215       if (DRL->getDecl() == DRR->getDecl())
10216         return;
10217 
10218   // Special case: check for comparisons against literals that can be exactly
10219   //  represented by APFloat.  In such cases, do not emit a warning.  This
10220   //  is a heuristic: often comparison against such literals are used to
10221   //  detect if a value in a variable has not changed.  This clearly can
10222   //  lead to false negatives.
10223   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10224     if (FLL->isExact())
10225       return;
10226   } else
10227     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10228       if (FLR->isExact())
10229         return;
10230 
10231   // Check for comparisons with builtin types.
10232   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10233     if (CL->getBuiltinCallee())
10234       return;
10235 
10236   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10237     if (CR->getBuiltinCallee())
10238       return;
10239 
10240   // Emit the diagnostic.
10241   Diag(Loc, diag::warn_floatingpoint_eq)
10242     << LHS->getSourceRange() << RHS->getSourceRange();
10243 }
10244 
10245 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10246 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10247 
10248 namespace {
10249 
10250 /// Structure recording the 'active' range of an integer-valued
10251 /// expression.
10252 struct IntRange {
10253   /// The number of bits active in the int. Note that this includes exactly one
10254   /// sign bit if !NonNegative.
10255   unsigned Width;
10256 
10257   /// True if the int is known not to have negative values. If so, all leading
10258   /// bits before Width are known zero, otherwise they are known to be the
10259   /// same as the MSB within Width.
10260   bool NonNegative;
10261 
10262   IntRange(unsigned Width, bool NonNegative)
10263       : Width(Width), NonNegative(NonNegative) {}
10264 
10265   /// Number of bits excluding the sign bit.
10266   unsigned valueBits() const {
10267     return NonNegative ? Width : Width - 1;
10268   }
10269 
10270   /// Returns the range of the bool type.
10271   static IntRange forBoolType() {
10272     return IntRange(1, true);
10273   }
10274 
10275   /// Returns the range of an opaque value of the given integral type.
10276   static IntRange forValueOfType(ASTContext &C, QualType T) {
10277     return forValueOfCanonicalType(C,
10278                           T->getCanonicalTypeInternal().getTypePtr());
10279   }
10280 
10281   /// Returns the range of an opaque value of a canonical integral type.
10282   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10283     assert(T->isCanonicalUnqualified());
10284 
10285     if (const VectorType *VT = dyn_cast<VectorType>(T))
10286       T = VT->getElementType().getTypePtr();
10287     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10288       T = CT->getElementType().getTypePtr();
10289     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10290       T = AT->getValueType().getTypePtr();
10291 
10292     if (!C.getLangOpts().CPlusPlus) {
10293       // For enum types in C code, use the underlying datatype.
10294       if (const EnumType *ET = dyn_cast<EnumType>(T))
10295         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10296     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10297       // For enum types in C++, use the known bit width of the enumerators.
10298       EnumDecl *Enum = ET->getDecl();
10299       // In C++11, enums can have a fixed underlying type. Use this type to
10300       // compute the range.
10301       if (Enum->isFixed()) {
10302         return IntRange(C.getIntWidth(QualType(T, 0)),
10303                         !ET->isSignedIntegerOrEnumerationType());
10304       }
10305 
10306       unsigned NumPositive = Enum->getNumPositiveBits();
10307       unsigned NumNegative = Enum->getNumNegativeBits();
10308 
10309       if (NumNegative == 0)
10310         return IntRange(NumPositive, true/*NonNegative*/);
10311       else
10312         return IntRange(std::max(NumPositive + 1, NumNegative),
10313                         false/*NonNegative*/);
10314     }
10315 
10316     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10317       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10318 
10319     const BuiltinType *BT = cast<BuiltinType>(T);
10320     assert(BT->isInteger());
10321 
10322     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10323   }
10324 
10325   /// Returns the "target" range of a canonical integral type, i.e.
10326   /// the range of values expressible in the type.
10327   ///
10328   /// This matches forValueOfCanonicalType except that enums have the
10329   /// full range of their type, not the range of their enumerators.
10330   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10331     assert(T->isCanonicalUnqualified());
10332 
10333     if (const VectorType *VT = dyn_cast<VectorType>(T))
10334       T = VT->getElementType().getTypePtr();
10335     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10336       T = CT->getElementType().getTypePtr();
10337     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10338       T = AT->getValueType().getTypePtr();
10339     if (const EnumType *ET = dyn_cast<EnumType>(T))
10340       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10341 
10342     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10343       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10344 
10345     const BuiltinType *BT = cast<BuiltinType>(T);
10346     assert(BT->isInteger());
10347 
10348     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10349   }
10350 
10351   /// Returns the supremum of two ranges: i.e. their conservative merge.
10352   static IntRange join(IntRange L, IntRange R) {
10353     bool Unsigned = L.NonNegative && R.NonNegative;
10354     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10355                     L.NonNegative && R.NonNegative);
10356   }
10357 
10358   /// Return the range of a bitwise-AND of the two ranges.
10359   static IntRange bit_and(IntRange L, IntRange R) {
10360     unsigned Bits = std::max(L.Width, R.Width);
10361     bool NonNegative = false;
10362     if (L.NonNegative) {
10363       Bits = std::min(Bits, L.Width);
10364       NonNegative = true;
10365     }
10366     if (R.NonNegative) {
10367       Bits = std::min(Bits, R.Width);
10368       NonNegative = true;
10369     }
10370     return IntRange(Bits, NonNegative);
10371   }
10372 
10373   /// Return the range of a sum of the two ranges.
10374   static IntRange sum(IntRange L, IntRange R) {
10375     bool Unsigned = L.NonNegative && R.NonNegative;
10376     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10377                     Unsigned);
10378   }
10379 
10380   /// Return the range of a difference of the two ranges.
10381   static IntRange difference(IntRange L, IntRange R) {
10382     // We need a 1-bit-wider range if:
10383     //   1) LHS can be negative: least value can be reduced.
10384     //   2) RHS can be negative: greatest value can be increased.
10385     bool CanWiden = !L.NonNegative || !R.NonNegative;
10386     bool Unsigned = L.NonNegative && R.Width == 0;
10387     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10388                         !Unsigned,
10389                     Unsigned);
10390   }
10391 
10392   /// Return the range of a product of the two ranges.
10393   static IntRange product(IntRange L, IntRange R) {
10394     // If both LHS and RHS can be negative, we can form
10395     //   -2^L * -2^R = 2^(L + R)
10396     // which requires L + R + 1 value bits to represent.
10397     bool CanWiden = !L.NonNegative && !R.NonNegative;
10398     bool Unsigned = L.NonNegative && R.NonNegative;
10399     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10400                     Unsigned);
10401   }
10402 
10403   /// Return the range of a remainder operation between the two ranges.
10404   static IntRange rem(IntRange L, IntRange R) {
10405     // The result of a remainder can't be larger than the result of
10406     // either side. The sign of the result is the sign of the LHS.
10407     bool Unsigned = L.NonNegative;
10408     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10409                     Unsigned);
10410   }
10411 };
10412 
10413 } // namespace
10414 
10415 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10416                               unsigned MaxWidth) {
10417   if (value.isSigned() && value.isNegative())
10418     return IntRange(value.getMinSignedBits(), false);
10419 
10420   if (value.getBitWidth() > MaxWidth)
10421     value = value.trunc(MaxWidth);
10422 
10423   // isNonNegative() just checks the sign bit without considering
10424   // signedness.
10425   return IntRange(value.getActiveBits(), true);
10426 }
10427 
10428 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10429                               unsigned MaxWidth) {
10430   if (result.isInt())
10431     return GetValueRange(C, result.getInt(), MaxWidth);
10432 
10433   if (result.isVector()) {
10434     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10435     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10436       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10437       R = IntRange::join(R, El);
10438     }
10439     return R;
10440   }
10441 
10442   if (result.isComplexInt()) {
10443     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10444     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10445     return IntRange::join(R, I);
10446   }
10447 
10448   // This can happen with lossless casts to intptr_t of "based" lvalues.
10449   // Assume it might use arbitrary bits.
10450   // FIXME: The only reason we need to pass the type in here is to get
10451   // the sign right on this one case.  It would be nice if APValue
10452   // preserved this.
10453   assert(result.isLValue() || result.isAddrLabelDiff());
10454   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10455 }
10456 
10457 static QualType GetExprType(const Expr *E) {
10458   QualType Ty = E->getType();
10459   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10460     Ty = AtomicRHS->getValueType();
10461   return Ty;
10462 }
10463 
10464 /// Pseudo-evaluate the given integer expression, estimating the
10465 /// range of values it might take.
10466 ///
10467 /// \param MaxWidth The width to which the value will be truncated.
10468 /// \param Approximate If \c true, return a likely range for the result: in
10469 ///        particular, assume that aritmetic on narrower types doesn't leave
10470 ///        those types. If \c false, return a range including all possible
10471 ///        result values.
10472 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10473                              bool InConstantContext, bool Approximate) {
10474   E = E->IgnoreParens();
10475 
10476   // Try a full evaluation first.
10477   Expr::EvalResult result;
10478   if (E->EvaluateAsRValue(result, C, InConstantContext))
10479     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10480 
10481   // I think we only want to look through implicit casts here; if the
10482   // user has an explicit widening cast, we should treat the value as
10483   // being of the new, wider type.
10484   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10485     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10486       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10487                           Approximate);
10488 
10489     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10490 
10491     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10492                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10493 
10494     // Assume that non-integer casts can span the full range of the type.
10495     if (!isIntegerCast)
10496       return OutputTypeRange;
10497 
10498     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10499                                      std::min(MaxWidth, OutputTypeRange.Width),
10500                                      InConstantContext, Approximate);
10501 
10502     // Bail out if the subexpr's range is as wide as the cast type.
10503     if (SubRange.Width >= OutputTypeRange.Width)
10504       return OutputTypeRange;
10505 
10506     // Otherwise, we take the smaller width, and we're non-negative if
10507     // either the output type or the subexpr is.
10508     return IntRange(SubRange.Width,
10509                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10510   }
10511 
10512   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10513     // If we can fold the condition, just take that operand.
10514     bool CondResult;
10515     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10516       return GetExprRange(C,
10517                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10518                           MaxWidth, InConstantContext, Approximate);
10519 
10520     // Otherwise, conservatively merge.
10521     // GetExprRange requires an integer expression, but a throw expression
10522     // results in a void type.
10523     Expr *E = CO->getTrueExpr();
10524     IntRange L = E->getType()->isVoidType()
10525                      ? IntRange{0, true}
10526                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10527     E = CO->getFalseExpr();
10528     IntRange R = E->getType()->isVoidType()
10529                      ? IntRange{0, true}
10530                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10531     return IntRange::join(L, R);
10532   }
10533 
10534   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10535     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10536 
10537     switch (BO->getOpcode()) {
10538     case BO_Cmp:
10539       llvm_unreachable("builtin <=> should have class type");
10540 
10541     // Boolean-valued operations are single-bit and positive.
10542     case BO_LAnd:
10543     case BO_LOr:
10544     case BO_LT:
10545     case BO_GT:
10546     case BO_LE:
10547     case BO_GE:
10548     case BO_EQ:
10549     case BO_NE:
10550       return IntRange::forBoolType();
10551 
10552     // The type of the assignments is the type of the LHS, so the RHS
10553     // is not necessarily the same type.
10554     case BO_MulAssign:
10555     case BO_DivAssign:
10556     case BO_RemAssign:
10557     case BO_AddAssign:
10558     case BO_SubAssign:
10559     case BO_XorAssign:
10560     case BO_OrAssign:
10561       // TODO: bitfields?
10562       return IntRange::forValueOfType(C, GetExprType(E));
10563 
10564     // Simple assignments just pass through the RHS, which will have
10565     // been coerced to the LHS type.
10566     case BO_Assign:
10567       // TODO: bitfields?
10568       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10569                           Approximate);
10570 
10571     // Operations with opaque sources are black-listed.
10572     case BO_PtrMemD:
10573     case BO_PtrMemI:
10574       return IntRange::forValueOfType(C, GetExprType(E));
10575 
10576     // Bitwise-and uses the *infinum* of the two source ranges.
10577     case BO_And:
10578     case BO_AndAssign:
10579       Combine = IntRange::bit_and;
10580       break;
10581 
10582     // Left shift gets black-listed based on a judgement call.
10583     case BO_Shl:
10584       // ...except that we want to treat '1 << (blah)' as logically
10585       // positive.  It's an important idiom.
10586       if (IntegerLiteral *I
10587             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10588         if (I->getValue() == 1) {
10589           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10590           return IntRange(R.Width, /*NonNegative*/ true);
10591         }
10592       }
10593       LLVM_FALLTHROUGH;
10594 
10595     case BO_ShlAssign:
10596       return IntRange::forValueOfType(C, GetExprType(E));
10597 
10598     // Right shift by a constant can narrow its left argument.
10599     case BO_Shr:
10600     case BO_ShrAssign: {
10601       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10602                                 Approximate);
10603 
10604       // If the shift amount is a positive constant, drop the width by
10605       // that much.
10606       if (Optional<llvm::APSInt> shift =
10607               BO->getRHS()->getIntegerConstantExpr(C)) {
10608         if (shift->isNonNegative()) {
10609           unsigned zext = shift->getZExtValue();
10610           if (zext >= L.Width)
10611             L.Width = (L.NonNegative ? 0 : 1);
10612           else
10613             L.Width -= zext;
10614         }
10615       }
10616 
10617       return L;
10618     }
10619 
10620     // Comma acts as its right operand.
10621     case BO_Comma:
10622       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10623                           Approximate);
10624 
10625     case BO_Add:
10626       if (!Approximate)
10627         Combine = IntRange::sum;
10628       break;
10629 
10630     case BO_Sub:
10631       if (BO->getLHS()->getType()->isPointerType())
10632         return IntRange::forValueOfType(C, GetExprType(E));
10633       if (!Approximate)
10634         Combine = IntRange::difference;
10635       break;
10636 
10637     case BO_Mul:
10638       if (!Approximate)
10639         Combine = IntRange::product;
10640       break;
10641 
10642     // The width of a division result is mostly determined by the size
10643     // of the LHS.
10644     case BO_Div: {
10645       // Don't 'pre-truncate' the operands.
10646       unsigned opWidth = C.getIntWidth(GetExprType(E));
10647       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10648                                 Approximate);
10649 
10650       // If the divisor is constant, use that.
10651       if (Optional<llvm::APSInt> divisor =
10652               BO->getRHS()->getIntegerConstantExpr(C)) {
10653         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10654         if (log2 >= L.Width)
10655           L.Width = (L.NonNegative ? 0 : 1);
10656         else
10657           L.Width = std::min(L.Width - log2, MaxWidth);
10658         return L;
10659       }
10660 
10661       // Otherwise, just use the LHS's width.
10662       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10663       // could be -1.
10664       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10665                                 Approximate);
10666       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10667     }
10668 
10669     case BO_Rem:
10670       Combine = IntRange::rem;
10671       break;
10672 
10673     // The default behavior is okay for these.
10674     case BO_Xor:
10675     case BO_Or:
10676       break;
10677     }
10678 
10679     // Combine the two ranges, but limit the result to the type in which we
10680     // performed the computation.
10681     QualType T = GetExprType(E);
10682     unsigned opWidth = C.getIntWidth(T);
10683     IntRange L =
10684         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10685     IntRange R =
10686         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10687     IntRange C = Combine(L, R);
10688     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10689     C.Width = std::min(C.Width, MaxWidth);
10690     return C;
10691   }
10692 
10693   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10694     switch (UO->getOpcode()) {
10695     // Boolean-valued operations are white-listed.
10696     case UO_LNot:
10697       return IntRange::forBoolType();
10698 
10699     // Operations with opaque sources are black-listed.
10700     case UO_Deref:
10701     case UO_AddrOf: // should be impossible
10702       return IntRange::forValueOfType(C, GetExprType(E));
10703 
10704     default:
10705       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10706                           Approximate);
10707     }
10708   }
10709 
10710   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10711     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10712                         Approximate);
10713 
10714   if (const auto *BitField = E->getSourceBitField())
10715     return IntRange(BitField->getBitWidthValue(C),
10716                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10717 
10718   return IntRange::forValueOfType(C, GetExprType(E));
10719 }
10720 
10721 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10722                              bool InConstantContext, bool Approximate) {
10723   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10724                       Approximate);
10725 }
10726 
10727 /// Checks whether the given value, which currently has the given
10728 /// source semantics, has the same value when coerced through the
10729 /// target semantics.
10730 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10731                                  const llvm::fltSemantics &Src,
10732                                  const llvm::fltSemantics &Tgt) {
10733   llvm::APFloat truncated = value;
10734 
10735   bool ignored;
10736   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10737   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10738 
10739   return truncated.bitwiseIsEqual(value);
10740 }
10741 
10742 /// Checks whether the given value, which currently has the given
10743 /// source semantics, has the same value when coerced through the
10744 /// target semantics.
10745 ///
10746 /// The value might be a vector of floats (or a complex number).
10747 static bool IsSameFloatAfterCast(const APValue &value,
10748                                  const llvm::fltSemantics &Src,
10749                                  const llvm::fltSemantics &Tgt) {
10750   if (value.isFloat())
10751     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10752 
10753   if (value.isVector()) {
10754     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10755       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10756         return false;
10757     return true;
10758   }
10759 
10760   assert(value.isComplexFloat());
10761   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10762           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10763 }
10764 
10765 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10766                                        bool IsListInit = false);
10767 
10768 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10769   // Suppress cases where we are comparing against an enum constant.
10770   if (const DeclRefExpr *DR =
10771       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10772     if (isa<EnumConstantDecl>(DR->getDecl()))
10773       return true;
10774 
10775   // Suppress cases where the value is expanded from a macro, unless that macro
10776   // is how a language represents a boolean literal. This is the case in both C
10777   // and Objective-C.
10778   SourceLocation BeginLoc = E->getBeginLoc();
10779   if (BeginLoc.isMacroID()) {
10780     StringRef MacroName = Lexer::getImmediateMacroName(
10781         BeginLoc, S.getSourceManager(), S.getLangOpts());
10782     return MacroName != "YES" && MacroName != "NO" &&
10783            MacroName != "true" && MacroName != "false";
10784   }
10785 
10786   return false;
10787 }
10788 
10789 static bool isKnownToHaveUnsignedValue(Expr *E) {
10790   return E->getType()->isIntegerType() &&
10791          (!E->getType()->isSignedIntegerType() ||
10792           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10793 }
10794 
10795 namespace {
10796 /// The promoted range of values of a type. In general this has the
10797 /// following structure:
10798 ///
10799 ///     |-----------| . . . |-----------|
10800 ///     ^           ^       ^           ^
10801 ///    Min       HoleMin  HoleMax      Max
10802 ///
10803 /// ... where there is only a hole if a signed type is promoted to unsigned
10804 /// (in which case Min and Max are the smallest and largest representable
10805 /// values).
10806 struct PromotedRange {
10807   // Min, or HoleMax if there is a hole.
10808   llvm::APSInt PromotedMin;
10809   // Max, or HoleMin if there is a hole.
10810   llvm::APSInt PromotedMax;
10811 
10812   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10813     if (R.Width == 0)
10814       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10815     else if (R.Width >= BitWidth && !Unsigned) {
10816       // Promotion made the type *narrower*. This happens when promoting
10817       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10818       // Treat all values of 'signed int' as being in range for now.
10819       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10820       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10821     } else {
10822       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10823                         .extOrTrunc(BitWidth);
10824       PromotedMin.setIsUnsigned(Unsigned);
10825 
10826       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10827                         .extOrTrunc(BitWidth);
10828       PromotedMax.setIsUnsigned(Unsigned);
10829     }
10830   }
10831 
10832   // Determine whether this range is contiguous (has no hole).
10833   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10834 
10835   // Where a constant value is within the range.
10836   enum ComparisonResult {
10837     LT = 0x1,
10838     LE = 0x2,
10839     GT = 0x4,
10840     GE = 0x8,
10841     EQ = 0x10,
10842     NE = 0x20,
10843     InRangeFlag = 0x40,
10844 
10845     Less = LE | LT | NE,
10846     Min = LE | InRangeFlag,
10847     InRange = InRangeFlag,
10848     Max = GE | InRangeFlag,
10849     Greater = GE | GT | NE,
10850 
10851     OnlyValue = LE | GE | EQ | InRangeFlag,
10852     InHole = NE
10853   };
10854 
10855   ComparisonResult compare(const llvm::APSInt &Value) const {
10856     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10857            Value.isUnsigned() == PromotedMin.isUnsigned());
10858     if (!isContiguous()) {
10859       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10860       if (Value.isMinValue()) return Min;
10861       if (Value.isMaxValue()) return Max;
10862       if (Value >= PromotedMin) return InRange;
10863       if (Value <= PromotedMax) return InRange;
10864       return InHole;
10865     }
10866 
10867     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10868     case -1: return Less;
10869     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10870     case 1:
10871       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10872       case -1: return InRange;
10873       case 0: return Max;
10874       case 1: return Greater;
10875       }
10876     }
10877 
10878     llvm_unreachable("impossible compare result");
10879   }
10880 
10881   static llvm::Optional<StringRef>
10882   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10883     if (Op == BO_Cmp) {
10884       ComparisonResult LTFlag = LT, GTFlag = GT;
10885       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10886 
10887       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10888       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10889       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10890       return llvm::None;
10891     }
10892 
10893     ComparisonResult TrueFlag, FalseFlag;
10894     if (Op == BO_EQ) {
10895       TrueFlag = EQ;
10896       FalseFlag = NE;
10897     } else if (Op == BO_NE) {
10898       TrueFlag = NE;
10899       FalseFlag = EQ;
10900     } else {
10901       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10902         TrueFlag = LT;
10903         FalseFlag = GE;
10904       } else {
10905         TrueFlag = GT;
10906         FalseFlag = LE;
10907       }
10908       if (Op == BO_GE || Op == BO_LE)
10909         std::swap(TrueFlag, FalseFlag);
10910     }
10911     if (R & TrueFlag)
10912       return StringRef("true");
10913     if (R & FalseFlag)
10914       return StringRef("false");
10915     return llvm::None;
10916   }
10917 };
10918 }
10919 
10920 static bool HasEnumType(Expr *E) {
10921   // Strip off implicit integral promotions.
10922   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10923     if (ICE->getCastKind() != CK_IntegralCast &&
10924         ICE->getCastKind() != CK_NoOp)
10925       break;
10926     E = ICE->getSubExpr();
10927   }
10928 
10929   return E->getType()->isEnumeralType();
10930 }
10931 
10932 static int classifyConstantValue(Expr *Constant) {
10933   // The values of this enumeration are used in the diagnostics
10934   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10935   enum ConstantValueKind {
10936     Miscellaneous = 0,
10937     LiteralTrue,
10938     LiteralFalse
10939   };
10940   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10941     return BL->getValue() ? ConstantValueKind::LiteralTrue
10942                           : ConstantValueKind::LiteralFalse;
10943   return ConstantValueKind::Miscellaneous;
10944 }
10945 
10946 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10947                                         Expr *Constant, Expr *Other,
10948                                         const llvm::APSInt &Value,
10949                                         bool RhsConstant) {
10950   if (S.inTemplateInstantiation())
10951     return false;
10952 
10953   Expr *OriginalOther = Other;
10954 
10955   Constant = Constant->IgnoreParenImpCasts();
10956   Other = Other->IgnoreParenImpCasts();
10957 
10958   // Suppress warnings on tautological comparisons between values of the same
10959   // enumeration type. There are only two ways we could warn on this:
10960   //  - If the constant is outside the range of representable values of
10961   //    the enumeration. In such a case, we should warn about the cast
10962   //    to enumeration type, not about the comparison.
10963   //  - If the constant is the maximum / minimum in-range value. For an
10964   //    enumeratin type, such comparisons can be meaningful and useful.
10965   if (Constant->getType()->isEnumeralType() &&
10966       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10967     return false;
10968 
10969   IntRange OtherValueRange = GetExprRange(
10970       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
10971 
10972   QualType OtherT = Other->getType();
10973   if (const auto *AT = OtherT->getAs<AtomicType>())
10974     OtherT = AT->getValueType();
10975   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
10976 
10977   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10978   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
10979   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10980                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10981                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10982 
10983   // Whether we're treating Other as being a bool because of the form of
10984   // expression despite it having another type (typically 'int' in C).
10985   bool OtherIsBooleanDespiteType =
10986       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10987   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10988     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
10989 
10990   // Check if all values in the range of possible values of this expression
10991   // lead to the same comparison outcome.
10992   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
10993                                         Value.isUnsigned());
10994   auto Cmp = OtherPromotedValueRange.compare(Value);
10995   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10996   if (!Result)
10997     return false;
10998 
10999   // Also consider the range determined by the type alone. This allows us to
11000   // classify the warning under the proper diagnostic group.
11001   bool TautologicalTypeCompare = false;
11002   {
11003     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11004                                          Value.isUnsigned());
11005     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11006     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11007                                                        RhsConstant)) {
11008       TautologicalTypeCompare = true;
11009       Cmp = TypeCmp;
11010       Result = TypeResult;
11011     }
11012   }
11013 
11014   // Don't warn if the non-constant operand actually always evaluates to the
11015   // same value.
11016   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11017     return false;
11018 
11019   // Suppress the diagnostic for an in-range comparison if the constant comes
11020   // from a macro or enumerator. We don't want to diagnose
11021   //
11022   //   some_long_value <= INT_MAX
11023   //
11024   // when sizeof(int) == sizeof(long).
11025   bool InRange = Cmp & PromotedRange::InRangeFlag;
11026   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11027     return false;
11028 
11029   // A comparison of an unsigned bit-field against 0 is really a type problem,
11030   // even though at the type level the bit-field might promote to 'signed int'.
11031   if (Other->refersToBitField() && InRange && Value == 0 &&
11032       Other->getType()->isUnsignedIntegerOrEnumerationType())
11033     TautologicalTypeCompare = true;
11034 
11035   // If this is a comparison to an enum constant, include that
11036   // constant in the diagnostic.
11037   const EnumConstantDecl *ED = nullptr;
11038   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11039     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11040 
11041   // Should be enough for uint128 (39 decimal digits)
11042   SmallString<64> PrettySourceValue;
11043   llvm::raw_svector_ostream OS(PrettySourceValue);
11044   if (ED) {
11045     OS << '\'' << *ED << "' (" << Value << ")";
11046   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11047                Constant->IgnoreParenImpCasts())) {
11048     OS << (BL->getValue() ? "YES" : "NO");
11049   } else {
11050     OS << Value;
11051   }
11052 
11053   if (!TautologicalTypeCompare) {
11054     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11055         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11056         << E->getOpcodeStr() << OS.str() << *Result
11057         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11058     return true;
11059   }
11060 
11061   if (IsObjCSignedCharBool) {
11062     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11063                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11064                               << OS.str() << *Result);
11065     return true;
11066   }
11067 
11068   // FIXME: We use a somewhat different formatting for the in-range cases and
11069   // cases involving boolean values for historical reasons. We should pick a
11070   // consistent way of presenting these diagnostics.
11071   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11072 
11073     S.DiagRuntimeBehavior(
11074         E->getOperatorLoc(), E,
11075         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11076                          : diag::warn_tautological_bool_compare)
11077             << OS.str() << classifyConstantValue(Constant) << OtherT
11078             << OtherIsBooleanDespiteType << *Result
11079             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11080   } else {
11081     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11082                         ? (HasEnumType(OriginalOther)
11083                                ? diag::warn_unsigned_enum_always_true_comparison
11084                                : diag::warn_unsigned_always_true_comparison)
11085                         : diag::warn_tautological_constant_compare;
11086 
11087     S.Diag(E->getOperatorLoc(), Diag)
11088         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11089         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11090   }
11091 
11092   return true;
11093 }
11094 
11095 /// Analyze the operands of the given comparison.  Implements the
11096 /// fallback case from AnalyzeComparison.
11097 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11098   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11099   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11100 }
11101 
11102 /// Implements -Wsign-compare.
11103 ///
11104 /// \param E the binary operator to check for warnings
11105 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11106   // The type the comparison is being performed in.
11107   QualType T = E->getLHS()->getType();
11108 
11109   // Only analyze comparison operators where both sides have been converted to
11110   // the same type.
11111   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11112     return AnalyzeImpConvsInComparison(S, E);
11113 
11114   // Don't analyze value-dependent comparisons directly.
11115   if (E->isValueDependent())
11116     return AnalyzeImpConvsInComparison(S, E);
11117 
11118   Expr *LHS = E->getLHS();
11119   Expr *RHS = E->getRHS();
11120 
11121   if (T->isIntegralType(S.Context)) {
11122     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11123     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11124 
11125     // We don't care about expressions whose result is a constant.
11126     if (RHSValue && LHSValue)
11127       return AnalyzeImpConvsInComparison(S, E);
11128 
11129     // We only care about expressions where just one side is literal
11130     if ((bool)RHSValue ^ (bool)LHSValue) {
11131       // Is the constant on the RHS or LHS?
11132       const bool RhsConstant = (bool)RHSValue;
11133       Expr *Const = RhsConstant ? RHS : LHS;
11134       Expr *Other = RhsConstant ? LHS : RHS;
11135       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11136 
11137       // Check whether an integer constant comparison results in a value
11138       // of 'true' or 'false'.
11139       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11140         return AnalyzeImpConvsInComparison(S, E);
11141     }
11142   }
11143 
11144   if (!T->hasUnsignedIntegerRepresentation()) {
11145     // We don't do anything special if this isn't an unsigned integral
11146     // comparison:  we're only interested in integral comparisons, and
11147     // signed comparisons only happen in cases we don't care to warn about.
11148     return AnalyzeImpConvsInComparison(S, E);
11149   }
11150 
11151   LHS = LHS->IgnoreParenImpCasts();
11152   RHS = RHS->IgnoreParenImpCasts();
11153 
11154   if (!S.getLangOpts().CPlusPlus) {
11155     // Avoid warning about comparison of integers with different signs when
11156     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11157     // the type of `E`.
11158     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11159       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11160     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11161       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11162   }
11163 
11164   // Check to see if one of the (unmodified) operands is of different
11165   // signedness.
11166   Expr *signedOperand, *unsignedOperand;
11167   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11168     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11169            "unsigned comparison between two signed integer expressions?");
11170     signedOperand = LHS;
11171     unsignedOperand = RHS;
11172   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11173     signedOperand = RHS;
11174     unsignedOperand = LHS;
11175   } else {
11176     return AnalyzeImpConvsInComparison(S, E);
11177   }
11178 
11179   // Otherwise, calculate the effective range of the signed operand.
11180   IntRange signedRange = GetExprRange(
11181       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11182 
11183   // Go ahead and analyze implicit conversions in the operands.  Note
11184   // that we skip the implicit conversions on both sides.
11185   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11186   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11187 
11188   // If the signed range is non-negative, -Wsign-compare won't fire.
11189   if (signedRange.NonNegative)
11190     return;
11191 
11192   // For (in)equality comparisons, if the unsigned operand is a
11193   // constant which cannot collide with a overflowed signed operand,
11194   // then reinterpreting the signed operand as unsigned will not
11195   // change the result of the comparison.
11196   if (E->isEqualityOp()) {
11197     unsigned comparisonWidth = S.Context.getIntWidth(T);
11198     IntRange unsignedRange =
11199         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11200                      /*Approximate*/ true);
11201 
11202     // We should never be unable to prove that the unsigned operand is
11203     // non-negative.
11204     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11205 
11206     if (unsignedRange.Width < comparisonWidth)
11207       return;
11208   }
11209 
11210   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11211                         S.PDiag(diag::warn_mixed_sign_comparison)
11212                             << LHS->getType() << RHS->getType()
11213                             << LHS->getSourceRange() << RHS->getSourceRange());
11214 }
11215 
11216 /// Analyzes an attempt to assign the given value to a bitfield.
11217 ///
11218 /// Returns true if there was something fishy about the attempt.
11219 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11220                                       SourceLocation InitLoc) {
11221   assert(Bitfield->isBitField());
11222   if (Bitfield->isInvalidDecl())
11223     return false;
11224 
11225   // White-list bool bitfields.
11226   QualType BitfieldType = Bitfield->getType();
11227   if (BitfieldType->isBooleanType())
11228      return false;
11229 
11230   if (BitfieldType->isEnumeralType()) {
11231     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11232     // If the underlying enum type was not explicitly specified as an unsigned
11233     // type and the enum contain only positive values, MSVC++ will cause an
11234     // inconsistency by storing this as a signed type.
11235     if (S.getLangOpts().CPlusPlus11 &&
11236         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11237         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11238         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11239       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11240           << BitfieldEnumDecl;
11241     }
11242   }
11243 
11244   if (Bitfield->getType()->isBooleanType())
11245     return false;
11246 
11247   // Ignore value- or type-dependent expressions.
11248   if (Bitfield->getBitWidth()->isValueDependent() ||
11249       Bitfield->getBitWidth()->isTypeDependent() ||
11250       Init->isValueDependent() ||
11251       Init->isTypeDependent())
11252     return false;
11253 
11254   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11255   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11256 
11257   Expr::EvalResult Result;
11258   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11259                                    Expr::SE_AllowSideEffects)) {
11260     // The RHS is not constant.  If the RHS has an enum type, make sure the
11261     // bitfield is wide enough to hold all the values of the enum without
11262     // truncation.
11263     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11264       EnumDecl *ED = EnumTy->getDecl();
11265       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11266 
11267       // Enum types are implicitly signed on Windows, so check if there are any
11268       // negative enumerators to see if the enum was intended to be signed or
11269       // not.
11270       bool SignedEnum = ED->getNumNegativeBits() > 0;
11271 
11272       // Check for surprising sign changes when assigning enum values to a
11273       // bitfield of different signedness.  If the bitfield is signed and we
11274       // have exactly the right number of bits to store this unsigned enum,
11275       // suggest changing the enum to an unsigned type. This typically happens
11276       // on Windows where unfixed enums always use an underlying type of 'int'.
11277       unsigned DiagID = 0;
11278       if (SignedEnum && !SignedBitfield) {
11279         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11280       } else if (SignedBitfield && !SignedEnum &&
11281                  ED->getNumPositiveBits() == FieldWidth) {
11282         DiagID = diag::warn_signed_bitfield_enum_conversion;
11283       }
11284 
11285       if (DiagID) {
11286         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11287         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11288         SourceRange TypeRange =
11289             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11290         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11291             << SignedEnum << TypeRange;
11292       }
11293 
11294       // Compute the required bitwidth. If the enum has negative values, we need
11295       // one more bit than the normal number of positive bits to represent the
11296       // sign bit.
11297       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11298                                                   ED->getNumNegativeBits())
11299                                        : ED->getNumPositiveBits();
11300 
11301       // Check the bitwidth.
11302       if (BitsNeeded > FieldWidth) {
11303         Expr *WidthExpr = Bitfield->getBitWidth();
11304         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11305             << Bitfield << ED;
11306         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11307             << BitsNeeded << ED << WidthExpr->getSourceRange();
11308       }
11309     }
11310 
11311     return false;
11312   }
11313 
11314   llvm::APSInt Value = Result.Val.getInt();
11315 
11316   unsigned OriginalWidth = Value.getBitWidth();
11317 
11318   if (!Value.isSigned() || Value.isNegative())
11319     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11320       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11321         OriginalWidth = Value.getMinSignedBits();
11322 
11323   if (OriginalWidth <= FieldWidth)
11324     return false;
11325 
11326   // Compute the value which the bitfield will contain.
11327   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11328   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11329 
11330   // Check whether the stored value is equal to the original value.
11331   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11332   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11333     return false;
11334 
11335   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11336   // therefore don't strictly fit into a signed bitfield of width 1.
11337   if (FieldWidth == 1 && Value == 1)
11338     return false;
11339 
11340   std::string PrettyValue = Value.toString(10);
11341   std::string PrettyTrunc = TruncatedValue.toString(10);
11342 
11343   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11344     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11345     << Init->getSourceRange();
11346 
11347   return true;
11348 }
11349 
11350 /// Analyze the given simple or compound assignment for warning-worthy
11351 /// operations.
11352 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11353   // Just recurse on the LHS.
11354   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11355 
11356   // We want to recurse on the RHS as normal unless we're assigning to
11357   // a bitfield.
11358   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11359     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11360                                   E->getOperatorLoc())) {
11361       // Recurse, ignoring any implicit conversions on the RHS.
11362       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11363                                         E->getOperatorLoc());
11364     }
11365   }
11366 
11367   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11368 
11369   // Diagnose implicitly sequentially-consistent atomic assignment.
11370   if (E->getLHS()->getType()->isAtomicType())
11371     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11372 }
11373 
11374 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11375 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11376                             SourceLocation CContext, unsigned diag,
11377                             bool pruneControlFlow = false) {
11378   if (pruneControlFlow) {
11379     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11380                           S.PDiag(diag)
11381                               << SourceType << T << E->getSourceRange()
11382                               << SourceRange(CContext));
11383     return;
11384   }
11385   S.Diag(E->getExprLoc(), diag)
11386     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11387 }
11388 
11389 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11390 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11391                             SourceLocation CContext,
11392                             unsigned diag, bool pruneControlFlow = false) {
11393   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11394 }
11395 
11396 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11397   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11398       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11399 }
11400 
11401 static void adornObjCBoolConversionDiagWithTernaryFixit(
11402     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11403   Expr *Ignored = SourceExpr->IgnoreImplicit();
11404   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11405     Ignored = OVE->getSourceExpr();
11406   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11407                      isa<BinaryOperator>(Ignored) ||
11408                      isa<CXXOperatorCallExpr>(Ignored);
11409   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11410   if (NeedsParens)
11411     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11412             << FixItHint::CreateInsertion(EndLoc, ")");
11413   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11414 }
11415 
11416 /// Diagnose an implicit cast from a floating point value to an integer value.
11417 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11418                                     SourceLocation CContext) {
11419   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11420   const bool PruneWarnings = S.inTemplateInstantiation();
11421 
11422   Expr *InnerE = E->IgnoreParenImpCasts();
11423   // We also want to warn on, e.g., "int i = -1.234"
11424   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11425     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11426       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11427 
11428   const bool IsLiteral =
11429       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11430 
11431   llvm::APFloat Value(0.0);
11432   bool IsConstant =
11433     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11434   if (!IsConstant) {
11435     if (isObjCSignedCharBool(S, T)) {
11436       return adornObjCBoolConversionDiagWithTernaryFixit(
11437           S, E,
11438           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11439               << E->getType());
11440     }
11441 
11442     return DiagnoseImpCast(S, E, T, CContext,
11443                            diag::warn_impcast_float_integer, PruneWarnings);
11444   }
11445 
11446   bool isExact = false;
11447 
11448   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11449                             T->hasUnsignedIntegerRepresentation());
11450   llvm::APFloat::opStatus Result = Value.convertToInteger(
11451       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11452 
11453   // FIXME: Force the precision of the source value down so we don't print
11454   // digits which are usually useless (we don't really care here if we
11455   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11456   // would automatically print the shortest representation, but it's a bit
11457   // tricky to implement.
11458   SmallString<16> PrettySourceValue;
11459   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11460   precision = (precision * 59 + 195) / 196;
11461   Value.toString(PrettySourceValue, precision);
11462 
11463   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11464     return adornObjCBoolConversionDiagWithTernaryFixit(
11465         S, E,
11466         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11467             << PrettySourceValue);
11468   }
11469 
11470   if (Result == llvm::APFloat::opOK && isExact) {
11471     if (IsLiteral) return;
11472     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11473                            PruneWarnings);
11474   }
11475 
11476   // Conversion of a floating-point value to a non-bool integer where the
11477   // integral part cannot be represented by the integer type is undefined.
11478   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11479     return DiagnoseImpCast(
11480         S, E, T, CContext,
11481         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11482                   : diag::warn_impcast_float_to_integer_out_of_range,
11483         PruneWarnings);
11484 
11485   unsigned DiagID = 0;
11486   if (IsLiteral) {
11487     // Warn on floating point literal to integer.
11488     DiagID = diag::warn_impcast_literal_float_to_integer;
11489   } else if (IntegerValue == 0) {
11490     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11491       return DiagnoseImpCast(S, E, T, CContext,
11492                              diag::warn_impcast_float_integer, PruneWarnings);
11493     }
11494     // Warn on non-zero to zero conversion.
11495     DiagID = diag::warn_impcast_float_to_integer_zero;
11496   } else {
11497     if (IntegerValue.isUnsigned()) {
11498       if (!IntegerValue.isMaxValue()) {
11499         return DiagnoseImpCast(S, E, T, CContext,
11500                                diag::warn_impcast_float_integer, PruneWarnings);
11501       }
11502     } else {  // IntegerValue.isSigned()
11503       if (!IntegerValue.isMaxSignedValue() &&
11504           !IntegerValue.isMinSignedValue()) {
11505         return DiagnoseImpCast(S, E, T, CContext,
11506                                diag::warn_impcast_float_integer, PruneWarnings);
11507       }
11508     }
11509     // Warn on evaluatable floating point expression to integer conversion.
11510     DiagID = diag::warn_impcast_float_to_integer;
11511   }
11512 
11513   SmallString<16> PrettyTargetValue;
11514   if (IsBool)
11515     PrettyTargetValue = Value.isZero() ? "false" : "true";
11516   else
11517     IntegerValue.toString(PrettyTargetValue);
11518 
11519   if (PruneWarnings) {
11520     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11521                           S.PDiag(DiagID)
11522                               << E->getType() << T.getUnqualifiedType()
11523                               << PrettySourceValue << PrettyTargetValue
11524                               << E->getSourceRange() << SourceRange(CContext));
11525   } else {
11526     S.Diag(E->getExprLoc(), DiagID)
11527         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11528         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11529   }
11530 }
11531 
11532 /// Analyze the given compound assignment for the possible losing of
11533 /// floating-point precision.
11534 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11535   assert(isa<CompoundAssignOperator>(E) &&
11536          "Must be compound assignment operation");
11537   // Recurse on the LHS and RHS in here
11538   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11539   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11540 
11541   if (E->getLHS()->getType()->isAtomicType())
11542     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11543 
11544   // Now check the outermost expression
11545   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11546   const auto *RBT = cast<CompoundAssignOperator>(E)
11547                         ->getComputationResultType()
11548                         ->getAs<BuiltinType>();
11549 
11550   // The below checks assume source is floating point.
11551   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11552 
11553   // If source is floating point but target is an integer.
11554   if (ResultBT->isInteger())
11555     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11556                            E->getExprLoc(), diag::warn_impcast_float_integer);
11557 
11558   if (!ResultBT->isFloatingPoint())
11559     return;
11560 
11561   // If both source and target are floating points, warn about losing precision.
11562   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11563       QualType(ResultBT, 0), QualType(RBT, 0));
11564   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11565     // warn about dropping FP rank.
11566     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11567                     diag::warn_impcast_float_result_precision);
11568 }
11569 
11570 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11571                                       IntRange Range) {
11572   if (!Range.Width) return "0";
11573 
11574   llvm::APSInt ValueInRange = Value;
11575   ValueInRange.setIsSigned(!Range.NonNegative);
11576   ValueInRange = ValueInRange.trunc(Range.Width);
11577   return ValueInRange.toString(10);
11578 }
11579 
11580 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11581   if (!isa<ImplicitCastExpr>(Ex))
11582     return false;
11583 
11584   Expr *InnerE = Ex->IgnoreParenImpCasts();
11585   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11586   const Type *Source =
11587     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11588   if (Target->isDependentType())
11589     return false;
11590 
11591   const BuiltinType *FloatCandidateBT =
11592     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11593   const Type *BoolCandidateType = ToBool ? Target : Source;
11594 
11595   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11596           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11597 }
11598 
11599 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11600                                              SourceLocation CC) {
11601   unsigned NumArgs = TheCall->getNumArgs();
11602   for (unsigned i = 0; i < NumArgs; ++i) {
11603     Expr *CurrA = TheCall->getArg(i);
11604     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11605       continue;
11606 
11607     bool IsSwapped = ((i > 0) &&
11608         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11609     IsSwapped |= ((i < (NumArgs - 1)) &&
11610         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11611     if (IsSwapped) {
11612       // Warn on this floating-point to bool conversion.
11613       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11614                       CurrA->getType(), CC,
11615                       diag::warn_impcast_floating_point_to_bool);
11616     }
11617   }
11618 }
11619 
11620 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11621                                    SourceLocation CC) {
11622   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11623                         E->getExprLoc()))
11624     return;
11625 
11626   // Don't warn on functions which have return type nullptr_t.
11627   if (isa<CallExpr>(E))
11628     return;
11629 
11630   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11631   const Expr::NullPointerConstantKind NullKind =
11632       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11633   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11634     return;
11635 
11636   // Return if target type is a safe conversion.
11637   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11638       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11639     return;
11640 
11641   SourceLocation Loc = E->getSourceRange().getBegin();
11642 
11643   // Venture through the macro stacks to get to the source of macro arguments.
11644   // The new location is a better location than the complete location that was
11645   // passed in.
11646   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11647   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11648 
11649   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11650   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11651     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11652         Loc, S.SourceMgr, S.getLangOpts());
11653     if (MacroName == "NULL")
11654       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11655   }
11656 
11657   // Only warn if the null and context location are in the same macro expansion.
11658   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11659     return;
11660 
11661   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11662       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11663       << FixItHint::CreateReplacement(Loc,
11664                                       S.getFixItZeroLiteralForType(T, Loc));
11665 }
11666 
11667 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11668                                   ObjCArrayLiteral *ArrayLiteral);
11669 
11670 static void
11671 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11672                            ObjCDictionaryLiteral *DictionaryLiteral);
11673 
11674 /// Check a single element within a collection literal against the
11675 /// target element type.
11676 static void checkObjCCollectionLiteralElement(Sema &S,
11677                                               QualType TargetElementType,
11678                                               Expr *Element,
11679                                               unsigned ElementKind) {
11680   // Skip a bitcast to 'id' or qualified 'id'.
11681   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11682     if (ICE->getCastKind() == CK_BitCast &&
11683         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11684       Element = ICE->getSubExpr();
11685   }
11686 
11687   QualType ElementType = Element->getType();
11688   ExprResult ElementResult(Element);
11689   if (ElementType->getAs<ObjCObjectPointerType>() &&
11690       S.CheckSingleAssignmentConstraints(TargetElementType,
11691                                          ElementResult,
11692                                          false, false)
11693         != Sema::Compatible) {
11694     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11695         << ElementType << ElementKind << TargetElementType
11696         << Element->getSourceRange();
11697   }
11698 
11699   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11700     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11701   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11702     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11703 }
11704 
11705 /// Check an Objective-C array literal being converted to the given
11706 /// target type.
11707 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11708                                   ObjCArrayLiteral *ArrayLiteral) {
11709   if (!S.NSArrayDecl)
11710     return;
11711 
11712   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11713   if (!TargetObjCPtr)
11714     return;
11715 
11716   if (TargetObjCPtr->isUnspecialized() ||
11717       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11718         != S.NSArrayDecl->getCanonicalDecl())
11719     return;
11720 
11721   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11722   if (TypeArgs.size() != 1)
11723     return;
11724 
11725   QualType TargetElementType = TypeArgs[0];
11726   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11727     checkObjCCollectionLiteralElement(S, TargetElementType,
11728                                       ArrayLiteral->getElement(I),
11729                                       0);
11730   }
11731 }
11732 
11733 /// Check an Objective-C dictionary literal being converted to the given
11734 /// target type.
11735 static void
11736 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11737                            ObjCDictionaryLiteral *DictionaryLiteral) {
11738   if (!S.NSDictionaryDecl)
11739     return;
11740 
11741   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11742   if (!TargetObjCPtr)
11743     return;
11744 
11745   if (TargetObjCPtr->isUnspecialized() ||
11746       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11747         != S.NSDictionaryDecl->getCanonicalDecl())
11748     return;
11749 
11750   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11751   if (TypeArgs.size() != 2)
11752     return;
11753 
11754   QualType TargetKeyType = TypeArgs[0];
11755   QualType TargetObjectType = TypeArgs[1];
11756   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11757     auto Element = DictionaryLiteral->getKeyValueElement(I);
11758     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11759     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11760   }
11761 }
11762 
11763 // Helper function to filter out cases for constant width constant conversion.
11764 // Don't warn on char array initialization or for non-decimal values.
11765 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11766                                           SourceLocation CC) {
11767   // If initializing from a constant, and the constant starts with '0',
11768   // then it is a binary, octal, or hexadecimal.  Allow these constants
11769   // to fill all the bits, even if there is a sign change.
11770   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11771     const char FirstLiteralCharacter =
11772         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11773     if (FirstLiteralCharacter == '0')
11774       return false;
11775   }
11776 
11777   // If the CC location points to a '{', and the type is char, then assume
11778   // assume it is an array initialization.
11779   if (CC.isValid() && T->isCharType()) {
11780     const char FirstContextCharacter =
11781         S.getSourceManager().getCharacterData(CC)[0];
11782     if (FirstContextCharacter == '{')
11783       return false;
11784   }
11785 
11786   return true;
11787 }
11788 
11789 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11790   const auto *IL = dyn_cast<IntegerLiteral>(E);
11791   if (!IL) {
11792     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11793       if (UO->getOpcode() == UO_Minus)
11794         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11795     }
11796   }
11797 
11798   return IL;
11799 }
11800 
11801 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11802   E = E->IgnoreParenImpCasts();
11803   SourceLocation ExprLoc = E->getExprLoc();
11804 
11805   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11806     BinaryOperator::Opcode Opc = BO->getOpcode();
11807     Expr::EvalResult Result;
11808     // Do not diagnose unsigned shifts.
11809     if (Opc == BO_Shl) {
11810       const auto *LHS = getIntegerLiteral(BO->getLHS());
11811       const auto *RHS = getIntegerLiteral(BO->getRHS());
11812       if (LHS && LHS->getValue() == 0)
11813         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11814       else if (!E->isValueDependent() && LHS && RHS &&
11815                RHS->getValue().isNonNegative() &&
11816                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11817         S.Diag(ExprLoc, diag::warn_left_shift_always)
11818             << (Result.Val.getInt() != 0);
11819       else if (E->getType()->isSignedIntegerType())
11820         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11821     }
11822   }
11823 
11824   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11825     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11826     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11827     if (!LHS || !RHS)
11828       return;
11829     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11830         (RHS->getValue() == 0 || RHS->getValue() == 1))
11831       // Do not diagnose common idioms.
11832       return;
11833     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11834       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11835   }
11836 }
11837 
11838 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11839                                     SourceLocation CC,
11840                                     bool *ICContext = nullptr,
11841                                     bool IsListInit = false) {
11842   if (E->isTypeDependent() || E->isValueDependent()) return;
11843 
11844   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11845   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11846   if (Source == Target) return;
11847   if (Target->isDependentType()) return;
11848 
11849   // If the conversion context location is invalid don't complain. We also
11850   // don't want to emit a warning if the issue occurs from the expansion of
11851   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11852   // delay this check as long as possible. Once we detect we are in that
11853   // scenario, we just return.
11854   if (CC.isInvalid())
11855     return;
11856 
11857   if (Source->isAtomicType())
11858     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11859 
11860   // Diagnose implicit casts to bool.
11861   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11862     if (isa<StringLiteral>(E))
11863       // Warn on string literal to bool.  Checks for string literals in logical
11864       // and expressions, for instance, assert(0 && "error here"), are
11865       // prevented by a check in AnalyzeImplicitConversions().
11866       return DiagnoseImpCast(S, E, T, CC,
11867                              diag::warn_impcast_string_literal_to_bool);
11868     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11869         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11870       // This covers the literal expressions that evaluate to Objective-C
11871       // objects.
11872       return DiagnoseImpCast(S, E, T, CC,
11873                              diag::warn_impcast_objective_c_literal_to_bool);
11874     }
11875     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11876       // Warn on pointer to bool conversion that is always true.
11877       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11878                                      SourceRange(CC));
11879     }
11880   }
11881 
11882   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11883   // is a typedef for signed char (macOS), then that constant value has to be 1
11884   // or 0.
11885   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11886     Expr::EvalResult Result;
11887     if (E->EvaluateAsInt(Result, S.getASTContext(),
11888                          Expr::SE_AllowSideEffects)) {
11889       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11890         adornObjCBoolConversionDiagWithTernaryFixit(
11891             S, E,
11892             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11893                 << Result.Val.getInt().toString(10));
11894       }
11895       return;
11896     }
11897   }
11898 
11899   // Check implicit casts from Objective-C collection literals to specialized
11900   // collection types, e.g., NSArray<NSString *> *.
11901   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11902     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11903   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11904     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11905 
11906   // Strip vector types.
11907   if (isa<VectorType>(Source)) {
11908     if (!isa<VectorType>(Target)) {
11909       if (S.SourceMgr.isInSystemMacro(CC))
11910         return;
11911       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11912     }
11913 
11914     // If the vector cast is cast between two vectors of the same size, it is
11915     // a bitcast, not a conversion.
11916     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11917       return;
11918 
11919     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11920     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11921   }
11922   if (auto VecTy = dyn_cast<VectorType>(Target))
11923     Target = VecTy->getElementType().getTypePtr();
11924 
11925   // Strip complex types.
11926   if (isa<ComplexType>(Source)) {
11927     if (!isa<ComplexType>(Target)) {
11928       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11929         return;
11930 
11931       return DiagnoseImpCast(S, E, T, CC,
11932                              S.getLangOpts().CPlusPlus
11933                                  ? diag::err_impcast_complex_scalar
11934                                  : diag::warn_impcast_complex_scalar);
11935     }
11936 
11937     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11938     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11939   }
11940 
11941   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11942   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11943 
11944   // If the source is floating point...
11945   if (SourceBT && SourceBT->isFloatingPoint()) {
11946     // ...and the target is floating point...
11947     if (TargetBT && TargetBT->isFloatingPoint()) {
11948       // ...then warn if we're dropping FP rank.
11949 
11950       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11951           QualType(SourceBT, 0), QualType(TargetBT, 0));
11952       if (Order > 0) {
11953         // Don't warn about float constants that are precisely
11954         // representable in the target type.
11955         Expr::EvalResult result;
11956         if (E->EvaluateAsRValue(result, S.Context)) {
11957           // Value might be a float, a float vector, or a float complex.
11958           if (IsSameFloatAfterCast(result.Val,
11959                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11960                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11961             return;
11962         }
11963 
11964         if (S.SourceMgr.isInSystemMacro(CC))
11965           return;
11966 
11967         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11968       }
11969       // ... or possibly if we're increasing rank, too
11970       else if (Order < 0) {
11971         if (S.SourceMgr.isInSystemMacro(CC))
11972           return;
11973 
11974         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11975       }
11976       return;
11977     }
11978 
11979     // If the target is integral, always warn.
11980     if (TargetBT && TargetBT->isInteger()) {
11981       if (S.SourceMgr.isInSystemMacro(CC))
11982         return;
11983 
11984       DiagnoseFloatingImpCast(S, E, T, CC);
11985     }
11986 
11987     // Detect the case where a call result is converted from floating-point to
11988     // to bool, and the final argument to the call is converted from bool, to
11989     // discover this typo:
11990     //
11991     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11992     //
11993     // FIXME: This is an incredibly special case; is there some more general
11994     // way to detect this class of misplaced-parentheses bug?
11995     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11996       // Check last argument of function call to see if it is an
11997       // implicit cast from a type matching the type the result
11998       // is being cast to.
11999       CallExpr *CEx = cast<CallExpr>(E);
12000       if (unsigned NumArgs = CEx->getNumArgs()) {
12001         Expr *LastA = CEx->getArg(NumArgs - 1);
12002         Expr *InnerE = LastA->IgnoreParenImpCasts();
12003         if (isa<ImplicitCastExpr>(LastA) &&
12004             InnerE->getType()->isBooleanType()) {
12005           // Warn on this floating-point to bool conversion
12006           DiagnoseImpCast(S, E, T, CC,
12007                           diag::warn_impcast_floating_point_to_bool);
12008         }
12009       }
12010     }
12011     return;
12012   }
12013 
12014   // Valid casts involving fixed point types should be accounted for here.
12015   if (Source->isFixedPointType()) {
12016     if (Target->isUnsaturatedFixedPointType()) {
12017       Expr::EvalResult Result;
12018       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12019                                   S.isConstantEvaluated())) {
12020         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12021         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12022         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12023         if (Value > MaxVal || Value < MinVal) {
12024           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12025                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12026                                     << Value.toString() << T
12027                                     << E->getSourceRange()
12028                                     << clang::SourceRange(CC));
12029           return;
12030         }
12031       }
12032     } else if (Target->isIntegerType()) {
12033       Expr::EvalResult Result;
12034       if (!S.isConstantEvaluated() &&
12035           E->EvaluateAsFixedPoint(Result, S.Context,
12036                                   Expr::SE_AllowSideEffects)) {
12037         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12038 
12039         bool Overflowed;
12040         llvm::APSInt IntResult = FXResult.convertToInt(
12041             S.Context.getIntWidth(T),
12042             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12043 
12044         if (Overflowed) {
12045           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12046                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12047                                     << FXResult.toString() << T
12048                                     << E->getSourceRange()
12049                                     << clang::SourceRange(CC));
12050           return;
12051         }
12052       }
12053     }
12054   } else if (Target->isUnsaturatedFixedPointType()) {
12055     if (Source->isIntegerType()) {
12056       Expr::EvalResult Result;
12057       if (!S.isConstantEvaluated() &&
12058           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12059         llvm::APSInt Value = Result.Val.getInt();
12060 
12061         bool Overflowed;
12062         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12063             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12064 
12065         if (Overflowed) {
12066           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12067                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12068                                     << Value.toString(/*Radix=*/10) << T
12069                                     << E->getSourceRange()
12070                                     << clang::SourceRange(CC));
12071           return;
12072         }
12073       }
12074     }
12075   }
12076 
12077   // If we are casting an integer type to a floating point type without
12078   // initialization-list syntax, we might lose accuracy if the floating
12079   // point type has a narrower significand than the integer type.
12080   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12081       TargetBT->isFloatingType() && !IsListInit) {
12082     // Determine the number of precision bits in the source integer type.
12083     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12084                                         /*Approximate*/ true);
12085     unsigned int SourcePrecision = SourceRange.Width;
12086 
12087     // Determine the number of precision bits in the
12088     // target floating point type.
12089     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12090         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12091 
12092     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12093         SourcePrecision > TargetPrecision) {
12094 
12095       if (Optional<llvm::APSInt> SourceInt =
12096               E->getIntegerConstantExpr(S.Context)) {
12097         // If the source integer is a constant, convert it to the target
12098         // floating point type. Issue a warning if the value changes
12099         // during the whole conversion.
12100         llvm::APFloat TargetFloatValue(
12101             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12102         llvm::APFloat::opStatus ConversionStatus =
12103             TargetFloatValue.convertFromAPInt(
12104                 *SourceInt, SourceBT->isSignedInteger(),
12105                 llvm::APFloat::rmNearestTiesToEven);
12106 
12107         if (ConversionStatus != llvm::APFloat::opOK) {
12108           std::string PrettySourceValue = SourceInt->toString(10);
12109           SmallString<32> PrettyTargetValue;
12110           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12111 
12112           S.DiagRuntimeBehavior(
12113               E->getExprLoc(), E,
12114               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12115                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12116                   << E->getSourceRange() << clang::SourceRange(CC));
12117         }
12118       } else {
12119         // Otherwise, the implicit conversion may lose precision.
12120         DiagnoseImpCast(S, E, T, CC,
12121                         diag::warn_impcast_integer_float_precision);
12122       }
12123     }
12124   }
12125 
12126   DiagnoseNullConversion(S, E, T, CC);
12127 
12128   S.DiscardMisalignedMemberAddress(Target, E);
12129 
12130   if (Target->isBooleanType())
12131     DiagnoseIntInBoolContext(S, E);
12132 
12133   if (!Source->isIntegerType() || !Target->isIntegerType())
12134     return;
12135 
12136   // TODO: remove this early return once the false positives for constant->bool
12137   // in templates, macros, etc, are reduced or removed.
12138   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12139     return;
12140 
12141   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12142       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12143     return adornObjCBoolConversionDiagWithTernaryFixit(
12144         S, E,
12145         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12146             << E->getType());
12147   }
12148 
12149   IntRange SourceTypeRange =
12150       IntRange::forTargetOfCanonicalType(S.Context, Source);
12151   IntRange LikelySourceRange =
12152       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12153   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12154 
12155   if (LikelySourceRange.Width > TargetRange.Width) {
12156     // If the source is a constant, use a default-on diagnostic.
12157     // TODO: this should happen for bitfield stores, too.
12158     Expr::EvalResult Result;
12159     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12160                          S.isConstantEvaluated())) {
12161       llvm::APSInt Value(32);
12162       Value = Result.Val.getInt();
12163 
12164       if (S.SourceMgr.isInSystemMacro(CC))
12165         return;
12166 
12167       std::string PrettySourceValue = Value.toString(10);
12168       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12169 
12170       S.DiagRuntimeBehavior(
12171           E->getExprLoc(), E,
12172           S.PDiag(diag::warn_impcast_integer_precision_constant)
12173               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12174               << E->getSourceRange() << SourceRange(CC));
12175       return;
12176     }
12177 
12178     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12179     if (S.SourceMgr.isInSystemMacro(CC))
12180       return;
12181 
12182     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12183       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12184                              /* pruneControlFlow */ true);
12185     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12186   }
12187 
12188   if (TargetRange.Width > SourceTypeRange.Width) {
12189     if (auto *UO = dyn_cast<UnaryOperator>(E))
12190       if (UO->getOpcode() == UO_Minus)
12191         if (Source->isUnsignedIntegerType()) {
12192           if (Target->isUnsignedIntegerType())
12193             return DiagnoseImpCast(S, E, T, CC,
12194                                    diag::warn_impcast_high_order_zero_bits);
12195           if (Target->isSignedIntegerType())
12196             return DiagnoseImpCast(S, E, T, CC,
12197                                    diag::warn_impcast_nonnegative_result);
12198         }
12199   }
12200 
12201   if (TargetRange.Width == LikelySourceRange.Width &&
12202       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12203       Source->isSignedIntegerType()) {
12204     // Warn when doing a signed to signed conversion, warn if the positive
12205     // source value is exactly the width of the target type, which will
12206     // cause a negative value to be stored.
12207 
12208     Expr::EvalResult Result;
12209     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12210         !S.SourceMgr.isInSystemMacro(CC)) {
12211       llvm::APSInt Value = Result.Val.getInt();
12212       if (isSameWidthConstantConversion(S, E, T, CC)) {
12213         std::string PrettySourceValue = Value.toString(10);
12214         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12215 
12216         S.DiagRuntimeBehavior(
12217             E->getExprLoc(), E,
12218             S.PDiag(diag::warn_impcast_integer_precision_constant)
12219                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12220                 << E->getSourceRange() << SourceRange(CC));
12221         return;
12222       }
12223     }
12224 
12225     // Fall through for non-constants to give a sign conversion warning.
12226   }
12227 
12228   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12229       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12230        LikelySourceRange.Width == TargetRange.Width)) {
12231     if (S.SourceMgr.isInSystemMacro(CC))
12232       return;
12233 
12234     unsigned DiagID = diag::warn_impcast_integer_sign;
12235 
12236     // Traditionally, gcc has warned about this under -Wsign-compare.
12237     // We also want to warn about it in -Wconversion.
12238     // So if -Wconversion is off, use a completely identical diagnostic
12239     // in the sign-compare group.
12240     // The conditional-checking code will
12241     if (ICContext) {
12242       DiagID = diag::warn_impcast_integer_sign_conditional;
12243       *ICContext = true;
12244     }
12245 
12246     return DiagnoseImpCast(S, E, T, CC, DiagID);
12247   }
12248 
12249   // Diagnose conversions between different enumeration types.
12250   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12251   // type, to give us better diagnostics.
12252   QualType SourceType = E->getType();
12253   if (!S.getLangOpts().CPlusPlus) {
12254     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12255       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12256         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12257         SourceType = S.Context.getTypeDeclType(Enum);
12258         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12259       }
12260   }
12261 
12262   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12263     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12264       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12265           TargetEnum->getDecl()->hasNameForLinkage() &&
12266           SourceEnum != TargetEnum) {
12267         if (S.SourceMgr.isInSystemMacro(CC))
12268           return;
12269 
12270         return DiagnoseImpCast(S, E, SourceType, T, CC,
12271                                diag::warn_impcast_different_enum_types);
12272       }
12273 }
12274 
12275 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12276                                      SourceLocation CC, QualType T);
12277 
12278 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12279                                     SourceLocation CC, bool &ICContext) {
12280   E = E->IgnoreParenImpCasts();
12281 
12282   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12283     return CheckConditionalOperator(S, CO, CC, T);
12284 
12285   AnalyzeImplicitConversions(S, E, CC);
12286   if (E->getType() != T)
12287     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12288 }
12289 
12290 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12291                                      SourceLocation CC, QualType T) {
12292   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12293 
12294   Expr *TrueExpr = E->getTrueExpr();
12295   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12296     TrueExpr = BCO->getCommon();
12297 
12298   bool Suspicious = false;
12299   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12300   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12301 
12302   if (T->isBooleanType())
12303     DiagnoseIntInBoolContext(S, E);
12304 
12305   // If -Wconversion would have warned about either of the candidates
12306   // for a signedness conversion to the context type...
12307   if (!Suspicious) return;
12308 
12309   // ...but it's currently ignored...
12310   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12311     return;
12312 
12313   // ...then check whether it would have warned about either of the
12314   // candidates for a signedness conversion to the condition type.
12315   if (E->getType() == T) return;
12316 
12317   Suspicious = false;
12318   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12319                           E->getType(), CC, &Suspicious);
12320   if (!Suspicious)
12321     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12322                             E->getType(), CC, &Suspicious);
12323 }
12324 
12325 /// Check conversion of given expression to boolean.
12326 /// Input argument E is a logical expression.
12327 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12328   if (S.getLangOpts().Bool)
12329     return;
12330   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12331     return;
12332   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12333 }
12334 
12335 namespace {
12336 struct AnalyzeImplicitConversionsWorkItem {
12337   Expr *E;
12338   SourceLocation CC;
12339   bool IsListInit;
12340 };
12341 }
12342 
12343 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12344 /// that should be visited are added to WorkList.
12345 static void AnalyzeImplicitConversions(
12346     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12347     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12348   Expr *OrigE = Item.E;
12349   SourceLocation CC = Item.CC;
12350 
12351   QualType T = OrigE->getType();
12352   Expr *E = OrigE->IgnoreParenImpCasts();
12353 
12354   // Propagate whether we are in a C++ list initialization expression.
12355   // If so, we do not issue warnings for implicit int-float conversion
12356   // precision loss, because C++11 narrowing already handles it.
12357   bool IsListInit = Item.IsListInit ||
12358                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12359 
12360   if (E->isTypeDependent() || E->isValueDependent())
12361     return;
12362 
12363   Expr *SourceExpr = E;
12364   // Examine, but don't traverse into the source expression of an
12365   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12366   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12367   // evaluate it in the context of checking the specific conversion to T though.
12368   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12369     if (auto *Src = OVE->getSourceExpr())
12370       SourceExpr = Src;
12371 
12372   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12373     if (UO->getOpcode() == UO_Not &&
12374         UO->getSubExpr()->isKnownToHaveBooleanValue())
12375       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12376           << OrigE->getSourceRange() << T->isBooleanType()
12377           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12378 
12379   // For conditional operators, we analyze the arguments as if they
12380   // were being fed directly into the output.
12381   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12382     CheckConditionalOperator(S, CO, CC, T);
12383     return;
12384   }
12385 
12386   // Check implicit argument conversions for function calls.
12387   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12388     CheckImplicitArgumentConversions(S, Call, CC);
12389 
12390   // Go ahead and check any implicit conversions we might have skipped.
12391   // The non-canonical typecheck is just an optimization;
12392   // CheckImplicitConversion will filter out dead implicit conversions.
12393   if (SourceExpr->getType() != T)
12394     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12395 
12396   // Now continue drilling into this expression.
12397 
12398   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12399     // The bound subexpressions in a PseudoObjectExpr are not reachable
12400     // as transitive children.
12401     // FIXME: Use a more uniform representation for this.
12402     for (auto *SE : POE->semantics())
12403       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12404         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12405   }
12406 
12407   // Skip past explicit casts.
12408   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12409     E = CE->getSubExpr()->IgnoreParenImpCasts();
12410     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12411       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12412     WorkList.push_back({E, CC, IsListInit});
12413     return;
12414   }
12415 
12416   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12417     // Do a somewhat different check with comparison operators.
12418     if (BO->isComparisonOp())
12419       return AnalyzeComparison(S, BO);
12420 
12421     // And with simple assignments.
12422     if (BO->getOpcode() == BO_Assign)
12423       return AnalyzeAssignment(S, BO);
12424     // And with compound assignments.
12425     if (BO->isAssignmentOp())
12426       return AnalyzeCompoundAssignment(S, BO);
12427   }
12428 
12429   // These break the otherwise-useful invariant below.  Fortunately,
12430   // we don't really need to recurse into them, because any internal
12431   // expressions should have been analyzed already when they were
12432   // built into statements.
12433   if (isa<StmtExpr>(E)) return;
12434 
12435   // Don't descend into unevaluated contexts.
12436   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12437 
12438   // Now just recurse over the expression's children.
12439   CC = E->getExprLoc();
12440   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12441   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12442   for (Stmt *SubStmt : E->children()) {
12443     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12444     if (!ChildExpr)
12445       continue;
12446 
12447     if (IsLogicalAndOperator &&
12448         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12449       // Ignore checking string literals that are in logical and operators.
12450       // This is a common pattern for asserts.
12451       continue;
12452     WorkList.push_back({ChildExpr, CC, IsListInit});
12453   }
12454 
12455   if (BO && BO->isLogicalOp()) {
12456     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12457     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12458       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12459 
12460     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12461     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12462       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12463   }
12464 
12465   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12466     if (U->getOpcode() == UO_LNot) {
12467       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12468     } else if (U->getOpcode() != UO_AddrOf) {
12469       if (U->getSubExpr()->getType()->isAtomicType())
12470         S.Diag(U->getSubExpr()->getBeginLoc(),
12471                diag::warn_atomic_implicit_seq_cst);
12472     }
12473   }
12474 }
12475 
12476 /// AnalyzeImplicitConversions - Find and report any interesting
12477 /// implicit conversions in the given expression.  There are a couple
12478 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12479 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12480                                        bool IsListInit/*= false*/) {
12481   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12482   WorkList.push_back({OrigE, CC, IsListInit});
12483   while (!WorkList.empty())
12484     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12485 }
12486 
12487 /// Diagnose integer type and any valid implicit conversion to it.
12488 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12489   // Taking into account implicit conversions,
12490   // allow any integer.
12491   if (!E->getType()->isIntegerType()) {
12492     S.Diag(E->getBeginLoc(),
12493            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12494     return true;
12495   }
12496   // Potentially emit standard warnings for implicit conversions if enabled
12497   // using -Wconversion.
12498   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12499   return false;
12500 }
12501 
12502 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12503 // Returns true when emitting a warning about taking the address of a reference.
12504 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12505                               const PartialDiagnostic &PD) {
12506   E = E->IgnoreParenImpCasts();
12507 
12508   const FunctionDecl *FD = nullptr;
12509 
12510   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12511     if (!DRE->getDecl()->getType()->isReferenceType())
12512       return false;
12513   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12514     if (!M->getMemberDecl()->getType()->isReferenceType())
12515       return false;
12516   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12517     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12518       return false;
12519     FD = Call->getDirectCallee();
12520   } else {
12521     return false;
12522   }
12523 
12524   SemaRef.Diag(E->getExprLoc(), PD);
12525 
12526   // If possible, point to location of function.
12527   if (FD) {
12528     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12529   }
12530 
12531   return true;
12532 }
12533 
12534 // Returns true if the SourceLocation is expanded from any macro body.
12535 // Returns false if the SourceLocation is invalid, is from not in a macro
12536 // expansion, or is from expanded from a top-level macro argument.
12537 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12538   if (Loc.isInvalid())
12539     return false;
12540 
12541   while (Loc.isMacroID()) {
12542     if (SM.isMacroBodyExpansion(Loc))
12543       return true;
12544     Loc = SM.getImmediateMacroCallerLoc(Loc);
12545   }
12546 
12547   return false;
12548 }
12549 
12550 /// Diagnose pointers that are always non-null.
12551 /// \param E the expression containing the pointer
12552 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12553 /// compared to a null pointer
12554 /// \param IsEqual True when the comparison is equal to a null pointer
12555 /// \param Range Extra SourceRange to highlight in the diagnostic
12556 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12557                                         Expr::NullPointerConstantKind NullKind,
12558                                         bool IsEqual, SourceRange Range) {
12559   if (!E)
12560     return;
12561 
12562   // Don't warn inside macros.
12563   if (E->getExprLoc().isMacroID()) {
12564     const SourceManager &SM = getSourceManager();
12565     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12566         IsInAnyMacroBody(SM, Range.getBegin()))
12567       return;
12568   }
12569   E = E->IgnoreImpCasts();
12570 
12571   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12572 
12573   if (isa<CXXThisExpr>(E)) {
12574     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12575                                 : diag::warn_this_bool_conversion;
12576     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12577     return;
12578   }
12579 
12580   bool IsAddressOf = false;
12581 
12582   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12583     if (UO->getOpcode() != UO_AddrOf)
12584       return;
12585     IsAddressOf = true;
12586     E = UO->getSubExpr();
12587   }
12588 
12589   if (IsAddressOf) {
12590     unsigned DiagID = IsCompare
12591                           ? diag::warn_address_of_reference_null_compare
12592                           : diag::warn_address_of_reference_bool_conversion;
12593     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12594                                          << IsEqual;
12595     if (CheckForReference(*this, E, PD)) {
12596       return;
12597     }
12598   }
12599 
12600   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12601     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12602     std::string Str;
12603     llvm::raw_string_ostream S(Str);
12604     E->printPretty(S, nullptr, getPrintingPolicy());
12605     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12606                                 : diag::warn_cast_nonnull_to_bool;
12607     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12608       << E->getSourceRange() << Range << IsEqual;
12609     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12610   };
12611 
12612   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12613   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12614     if (auto *Callee = Call->getDirectCallee()) {
12615       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12616         ComplainAboutNonnullParamOrCall(A);
12617         return;
12618       }
12619     }
12620   }
12621 
12622   // Expect to find a single Decl.  Skip anything more complicated.
12623   ValueDecl *D = nullptr;
12624   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12625     D = R->getDecl();
12626   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12627     D = M->getMemberDecl();
12628   }
12629 
12630   // Weak Decls can be null.
12631   if (!D || D->isWeak())
12632     return;
12633 
12634   // Check for parameter decl with nonnull attribute
12635   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12636     if (getCurFunction() &&
12637         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12638       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12639         ComplainAboutNonnullParamOrCall(A);
12640         return;
12641       }
12642 
12643       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12644         // Skip function template not specialized yet.
12645         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12646           return;
12647         auto ParamIter = llvm::find(FD->parameters(), PV);
12648         assert(ParamIter != FD->param_end());
12649         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12650 
12651         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12652           if (!NonNull->args_size()) {
12653               ComplainAboutNonnullParamOrCall(NonNull);
12654               return;
12655           }
12656 
12657           for (const ParamIdx &ArgNo : NonNull->args()) {
12658             if (ArgNo.getASTIndex() == ParamNo) {
12659               ComplainAboutNonnullParamOrCall(NonNull);
12660               return;
12661             }
12662           }
12663         }
12664       }
12665     }
12666   }
12667 
12668   QualType T = D->getType();
12669   const bool IsArray = T->isArrayType();
12670   const bool IsFunction = T->isFunctionType();
12671 
12672   // Address of function is used to silence the function warning.
12673   if (IsAddressOf && IsFunction) {
12674     return;
12675   }
12676 
12677   // Found nothing.
12678   if (!IsAddressOf && !IsFunction && !IsArray)
12679     return;
12680 
12681   // Pretty print the expression for the diagnostic.
12682   std::string Str;
12683   llvm::raw_string_ostream S(Str);
12684   E->printPretty(S, nullptr, getPrintingPolicy());
12685 
12686   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12687                               : diag::warn_impcast_pointer_to_bool;
12688   enum {
12689     AddressOf,
12690     FunctionPointer,
12691     ArrayPointer
12692   } DiagType;
12693   if (IsAddressOf)
12694     DiagType = AddressOf;
12695   else if (IsFunction)
12696     DiagType = FunctionPointer;
12697   else if (IsArray)
12698     DiagType = ArrayPointer;
12699   else
12700     llvm_unreachable("Could not determine diagnostic.");
12701   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12702                                 << Range << IsEqual;
12703 
12704   if (!IsFunction)
12705     return;
12706 
12707   // Suggest '&' to silence the function warning.
12708   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12709       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12710 
12711   // Check to see if '()' fixit should be emitted.
12712   QualType ReturnType;
12713   UnresolvedSet<4> NonTemplateOverloads;
12714   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12715   if (ReturnType.isNull())
12716     return;
12717 
12718   if (IsCompare) {
12719     // There are two cases here.  If there is null constant, the only suggest
12720     // for a pointer return type.  If the null is 0, then suggest if the return
12721     // type is a pointer or an integer type.
12722     if (!ReturnType->isPointerType()) {
12723       if (NullKind == Expr::NPCK_ZeroExpression ||
12724           NullKind == Expr::NPCK_ZeroLiteral) {
12725         if (!ReturnType->isIntegerType())
12726           return;
12727       } else {
12728         return;
12729       }
12730     }
12731   } else { // !IsCompare
12732     // For function to bool, only suggest if the function pointer has bool
12733     // return type.
12734     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12735       return;
12736   }
12737   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12738       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12739 }
12740 
12741 /// Diagnoses "dangerous" implicit conversions within the given
12742 /// expression (which is a full expression).  Implements -Wconversion
12743 /// and -Wsign-compare.
12744 ///
12745 /// \param CC the "context" location of the implicit conversion, i.e.
12746 ///   the most location of the syntactic entity requiring the implicit
12747 ///   conversion
12748 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12749   // Don't diagnose in unevaluated contexts.
12750   if (isUnevaluatedContext())
12751     return;
12752 
12753   // Don't diagnose for value- or type-dependent expressions.
12754   if (E->isTypeDependent() || E->isValueDependent())
12755     return;
12756 
12757   // Check for array bounds violations in cases where the check isn't triggered
12758   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12759   // ArraySubscriptExpr is on the RHS of a variable initialization.
12760   CheckArrayAccess(E);
12761 
12762   // This is not the right CC for (e.g.) a variable initialization.
12763   AnalyzeImplicitConversions(*this, E, CC);
12764 }
12765 
12766 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12767 /// Input argument E is a logical expression.
12768 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12769   ::CheckBoolLikeConversion(*this, E, CC);
12770 }
12771 
12772 /// Diagnose when expression is an integer constant expression and its evaluation
12773 /// results in integer overflow
12774 void Sema::CheckForIntOverflow (Expr *E) {
12775   // Use a work list to deal with nested struct initializers.
12776   SmallVector<Expr *, 2> Exprs(1, E);
12777 
12778   do {
12779     Expr *OriginalE = Exprs.pop_back_val();
12780     Expr *E = OriginalE->IgnoreParenCasts();
12781 
12782     if (isa<BinaryOperator>(E)) {
12783       E->EvaluateForOverflow(Context);
12784       continue;
12785     }
12786 
12787     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12788       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12789     else if (isa<ObjCBoxedExpr>(OriginalE))
12790       E->EvaluateForOverflow(Context);
12791     else if (auto Call = dyn_cast<CallExpr>(E))
12792       Exprs.append(Call->arg_begin(), Call->arg_end());
12793     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12794       Exprs.append(Message->arg_begin(), Message->arg_end());
12795   } while (!Exprs.empty());
12796 }
12797 
12798 namespace {
12799 
12800 /// Visitor for expressions which looks for unsequenced operations on the
12801 /// same object.
12802 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12803   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12804 
12805   /// A tree of sequenced regions within an expression. Two regions are
12806   /// unsequenced if one is an ancestor or a descendent of the other. When we
12807   /// finish processing an expression with sequencing, such as a comma
12808   /// expression, we fold its tree nodes into its parent, since they are
12809   /// unsequenced with respect to nodes we will visit later.
12810   class SequenceTree {
12811     struct Value {
12812       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12813       unsigned Parent : 31;
12814       unsigned Merged : 1;
12815     };
12816     SmallVector<Value, 8> Values;
12817 
12818   public:
12819     /// A region within an expression which may be sequenced with respect
12820     /// to some other region.
12821     class Seq {
12822       friend class SequenceTree;
12823 
12824       unsigned Index;
12825 
12826       explicit Seq(unsigned N) : Index(N) {}
12827 
12828     public:
12829       Seq() : Index(0) {}
12830     };
12831 
12832     SequenceTree() { Values.push_back(Value(0)); }
12833     Seq root() const { return Seq(0); }
12834 
12835     /// Create a new sequence of operations, which is an unsequenced
12836     /// subset of \p Parent. This sequence of operations is sequenced with
12837     /// respect to other children of \p Parent.
12838     Seq allocate(Seq Parent) {
12839       Values.push_back(Value(Parent.Index));
12840       return Seq(Values.size() - 1);
12841     }
12842 
12843     /// Merge a sequence of operations into its parent.
12844     void merge(Seq S) {
12845       Values[S.Index].Merged = true;
12846     }
12847 
12848     /// Determine whether two operations are unsequenced. This operation
12849     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12850     /// should have been merged into its parent as appropriate.
12851     bool isUnsequenced(Seq Cur, Seq Old) {
12852       unsigned C = representative(Cur.Index);
12853       unsigned Target = representative(Old.Index);
12854       while (C >= Target) {
12855         if (C == Target)
12856           return true;
12857         C = Values[C].Parent;
12858       }
12859       return false;
12860     }
12861 
12862   private:
12863     /// Pick a representative for a sequence.
12864     unsigned representative(unsigned K) {
12865       if (Values[K].Merged)
12866         // Perform path compression as we go.
12867         return Values[K].Parent = representative(Values[K].Parent);
12868       return K;
12869     }
12870   };
12871 
12872   /// An object for which we can track unsequenced uses.
12873   using Object = const NamedDecl *;
12874 
12875   /// Different flavors of object usage which we track. We only track the
12876   /// least-sequenced usage of each kind.
12877   enum UsageKind {
12878     /// A read of an object. Multiple unsequenced reads are OK.
12879     UK_Use,
12880 
12881     /// A modification of an object which is sequenced before the value
12882     /// computation of the expression, such as ++n in C++.
12883     UK_ModAsValue,
12884 
12885     /// A modification of an object which is not sequenced before the value
12886     /// computation of the expression, such as n++.
12887     UK_ModAsSideEffect,
12888 
12889     UK_Count = UK_ModAsSideEffect + 1
12890   };
12891 
12892   /// Bundle together a sequencing region and the expression corresponding
12893   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12894   struct Usage {
12895     const Expr *UsageExpr;
12896     SequenceTree::Seq Seq;
12897 
12898     Usage() : UsageExpr(nullptr), Seq() {}
12899   };
12900 
12901   struct UsageInfo {
12902     Usage Uses[UK_Count];
12903 
12904     /// Have we issued a diagnostic for this object already?
12905     bool Diagnosed;
12906 
12907     UsageInfo() : Uses(), Diagnosed(false) {}
12908   };
12909   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12910 
12911   Sema &SemaRef;
12912 
12913   /// Sequenced regions within the expression.
12914   SequenceTree Tree;
12915 
12916   /// Declaration modifications and references which we have seen.
12917   UsageInfoMap UsageMap;
12918 
12919   /// The region we are currently within.
12920   SequenceTree::Seq Region;
12921 
12922   /// Filled in with declarations which were modified as a side-effect
12923   /// (that is, post-increment operations).
12924   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12925 
12926   /// Expressions to check later. We defer checking these to reduce
12927   /// stack usage.
12928   SmallVectorImpl<const Expr *> &WorkList;
12929 
12930   /// RAII object wrapping the visitation of a sequenced subexpression of an
12931   /// expression. At the end of this process, the side-effects of the evaluation
12932   /// become sequenced with respect to the value computation of the result, so
12933   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12934   /// UK_ModAsValue.
12935   struct SequencedSubexpression {
12936     SequencedSubexpression(SequenceChecker &Self)
12937       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12938       Self.ModAsSideEffect = &ModAsSideEffect;
12939     }
12940 
12941     ~SequencedSubexpression() {
12942       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12943         // Add a new usage with usage kind UK_ModAsValue, and then restore
12944         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12945         // the previous one was empty).
12946         UsageInfo &UI = Self.UsageMap[M.first];
12947         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12948         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12949         SideEffectUsage = M.second;
12950       }
12951       Self.ModAsSideEffect = OldModAsSideEffect;
12952     }
12953 
12954     SequenceChecker &Self;
12955     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12956     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12957   };
12958 
12959   /// RAII object wrapping the visitation of a subexpression which we might
12960   /// choose to evaluate as a constant. If any subexpression is evaluated and
12961   /// found to be non-constant, this allows us to suppress the evaluation of
12962   /// the outer expression.
12963   class EvaluationTracker {
12964   public:
12965     EvaluationTracker(SequenceChecker &Self)
12966         : Self(Self), Prev(Self.EvalTracker) {
12967       Self.EvalTracker = this;
12968     }
12969 
12970     ~EvaluationTracker() {
12971       Self.EvalTracker = Prev;
12972       if (Prev)
12973         Prev->EvalOK &= EvalOK;
12974     }
12975 
12976     bool evaluate(const Expr *E, bool &Result) {
12977       if (!EvalOK || E->isValueDependent())
12978         return false;
12979       EvalOK = E->EvaluateAsBooleanCondition(
12980           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12981       return EvalOK;
12982     }
12983 
12984   private:
12985     SequenceChecker &Self;
12986     EvaluationTracker *Prev;
12987     bool EvalOK = true;
12988   } *EvalTracker = nullptr;
12989 
12990   /// Find the object which is produced by the specified expression,
12991   /// if any.
12992   Object getObject(const Expr *E, bool Mod) const {
12993     E = E->IgnoreParenCasts();
12994     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12995       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12996         return getObject(UO->getSubExpr(), Mod);
12997     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12998       if (BO->getOpcode() == BO_Comma)
12999         return getObject(BO->getRHS(), Mod);
13000       if (Mod && BO->isAssignmentOp())
13001         return getObject(BO->getLHS(), Mod);
13002     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13003       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13004       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13005         return ME->getMemberDecl();
13006     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13007       // FIXME: If this is a reference, map through to its value.
13008       return DRE->getDecl();
13009     return nullptr;
13010   }
13011 
13012   /// Note that an object \p O was modified or used by an expression
13013   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13014   /// the object \p O as obtained via the \p UsageMap.
13015   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13016     // Get the old usage for the given object and usage kind.
13017     Usage &U = UI.Uses[UK];
13018     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13019       // If we have a modification as side effect and are in a sequenced
13020       // subexpression, save the old Usage so that we can restore it later
13021       // in SequencedSubexpression::~SequencedSubexpression.
13022       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13023         ModAsSideEffect->push_back(std::make_pair(O, U));
13024       // Then record the new usage with the current sequencing region.
13025       U.UsageExpr = UsageExpr;
13026       U.Seq = Region;
13027     }
13028   }
13029 
13030   /// Check whether a modification or use of an object \p O in an expression
13031   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13032   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13033   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13034   /// usage and false we are checking for a mod-use unsequenced usage.
13035   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13036                   UsageKind OtherKind, bool IsModMod) {
13037     if (UI.Diagnosed)
13038       return;
13039 
13040     const Usage &U = UI.Uses[OtherKind];
13041     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13042       return;
13043 
13044     const Expr *Mod = U.UsageExpr;
13045     const Expr *ModOrUse = UsageExpr;
13046     if (OtherKind == UK_Use)
13047       std::swap(Mod, ModOrUse);
13048 
13049     SemaRef.DiagRuntimeBehavior(
13050         Mod->getExprLoc(), {Mod, ModOrUse},
13051         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13052                                : diag::warn_unsequenced_mod_use)
13053             << O << SourceRange(ModOrUse->getExprLoc()));
13054     UI.Diagnosed = true;
13055   }
13056 
13057   // A note on note{Pre, Post}{Use, Mod}:
13058   //
13059   // (It helps to follow the algorithm with an expression such as
13060   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13061   //  operations before C++17 and both are well-defined in C++17).
13062   //
13063   // When visiting a node which uses/modify an object we first call notePreUse
13064   // or notePreMod before visiting its sub-expression(s). At this point the
13065   // children of the current node have not yet been visited and so the eventual
13066   // uses/modifications resulting from the children of the current node have not
13067   // been recorded yet.
13068   //
13069   // We then visit the children of the current node. After that notePostUse or
13070   // notePostMod is called. These will 1) detect an unsequenced modification
13071   // as side effect (as in "k++ + k") and 2) add a new usage with the
13072   // appropriate usage kind.
13073   //
13074   // We also have to be careful that some operation sequences modification as
13075   // side effect as well (for example: || or ,). To account for this we wrap
13076   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13077   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13078   // which record usages which are modifications as side effect, and then
13079   // downgrade them (or more accurately restore the previous usage which was a
13080   // modification as side effect) when exiting the scope of the sequenced
13081   // subexpression.
13082 
13083   void notePreUse(Object O, const Expr *UseExpr) {
13084     UsageInfo &UI = UsageMap[O];
13085     // Uses conflict with other modifications.
13086     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13087   }
13088 
13089   void notePostUse(Object O, const Expr *UseExpr) {
13090     UsageInfo &UI = UsageMap[O];
13091     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13092                /*IsModMod=*/false);
13093     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13094   }
13095 
13096   void notePreMod(Object O, const Expr *ModExpr) {
13097     UsageInfo &UI = UsageMap[O];
13098     // Modifications conflict with other modifications and with uses.
13099     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13100     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13101   }
13102 
13103   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13104     UsageInfo &UI = UsageMap[O];
13105     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13106                /*IsModMod=*/true);
13107     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13108   }
13109 
13110 public:
13111   SequenceChecker(Sema &S, const Expr *E,
13112                   SmallVectorImpl<const Expr *> &WorkList)
13113       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13114     Visit(E);
13115     // Silence a -Wunused-private-field since WorkList is now unused.
13116     // TODO: Evaluate if it can be used, and if not remove it.
13117     (void)this->WorkList;
13118   }
13119 
13120   void VisitStmt(const Stmt *S) {
13121     // Skip all statements which aren't expressions for now.
13122   }
13123 
13124   void VisitExpr(const Expr *E) {
13125     // By default, just recurse to evaluated subexpressions.
13126     Base::VisitStmt(E);
13127   }
13128 
13129   void VisitCastExpr(const CastExpr *E) {
13130     Object O = Object();
13131     if (E->getCastKind() == CK_LValueToRValue)
13132       O = getObject(E->getSubExpr(), false);
13133 
13134     if (O)
13135       notePreUse(O, E);
13136     VisitExpr(E);
13137     if (O)
13138       notePostUse(O, E);
13139   }
13140 
13141   void VisitSequencedExpressions(const Expr *SequencedBefore,
13142                                  const Expr *SequencedAfter) {
13143     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13144     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13145     SequenceTree::Seq OldRegion = Region;
13146 
13147     {
13148       SequencedSubexpression SeqBefore(*this);
13149       Region = BeforeRegion;
13150       Visit(SequencedBefore);
13151     }
13152 
13153     Region = AfterRegion;
13154     Visit(SequencedAfter);
13155 
13156     Region = OldRegion;
13157 
13158     Tree.merge(BeforeRegion);
13159     Tree.merge(AfterRegion);
13160   }
13161 
13162   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13163     // C++17 [expr.sub]p1:
13164     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13165     //   expression E1 is sequenced before the expression E2.
13166     if (SemaRef.getLangOpts().CPlusPlus17)
13167       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13168     else {
13169       Visit(ASE->getLHS());
13170       Visit(ASE->getRHS());
13171     }
13172   }
13173 
13174   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13175   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13176   void VisitBinPtrMem(const BinaryOperator *BO) {
13177     // C++17 [expr.mptr.oper]p4:
13178     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13179     //  the expression E1 is sequenced before the expression E2.
13180     if (SemaRef.getLangOpts().CPlusPlus17)
13181       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13182     else {
13183       Visit(BO->getLHS());
13184       Visit(BO->getRHS());
13185     }
13186   }
13187 
13188   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13189   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13190   void VisitBinShlShr(const BinaryOperator *BO) {
13191     // C++17 [expr.shift]p4:
13192     //  The expression E1 is sequenced before the expression E2.
13193     if (SemaRef.getLangOpts().CPlusPlus17)
13194       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13195     else {
13196       Visit(BO->getLHS());
13197       Visit(BO->getRHS());
13198     }
13199   }
13200 
13201   void VisitBinComma(const BinaryOperator *BO) {
13202     // C++11 [expr.comma]p1:
13203     //   Every value computation and side effect associated with the left
13204     //   expression is sequenced before every value computation and side
13205     //   effect associated with the right expression.
13206     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13207   }
13208 
13209   void VisitBinAssign(const BinaryOperator *BO) {
13210     SequenceTree::Seq RHSRegion;
13211     SequenceTree::Seq LHSRegion;
13212     if (SemaRef.getLangOpts().CPlusPlus17) {
13213       RHSRegion = Tree.allocate(Region);
13214       LHSRegion = Tree.allocate(Region);
13215     } else {
13216       RHSRegion = Region;
13217       LHSRegion = Region;
13218     }
13219     SequenceTree::Seq OldRegion = Region;
13220 
13221     // C++11 [expr.ass]p1:
13222     //  [...] the assignment is sequenced after the value computation
13223     //  of the right and left operands, [...]
13224     //
13225     // so check it before inspecting the operands and update the
13226     // map afterwards.
13227     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13228     if (O)
13229       notePreMod(O, BO);
13230 
13231     if (SemaRef.getLangOpts().CPlusPlus17) {
13232       // C++17 [expr.ass]p1:
13233       //  [...] The right operand is sequenced before the left operand. [...]
13234       {
13235         SequencedSubexpression SeqBefore(*this);
13236         Region = RHSRegion;
13237         Visit(BO->getRHS());
13238       }
13239 
13240       Region = LHSRegion;
13241       Visit(BO->getLHS());
13242 
13243       if (O && isa<CompoundAssignOperator>(BO))
13244         notePostUse(O, BO);
13245 
13246     } else {
13247       // C++11 does not specify any sequencing between the LHS and RHS.
13248       Region = LHSRegion;
13249       Visit(BO->getLHS());
13250 
13251       if (O && isa<CompoundAssignOperator>(BO))
13252         notePostUse(O, BO);
13253 
13254       Region = RHSRegion;
13255       Visit(BO->getRHS());
13256     }
13257 
13258     // C++11 [expr.ass]p1:
13259     //  the assignment is sequenced [...] before the value computation of the
13260     //  assignment expression.
13261     // C11 6.5.16/3 has no such rule.
13262     Region = OldRegion;
13263     if (O)
13264       notePostMod(O, BO,
13265                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13266                                                   : UK_ModAsSideEffect);
13267     if (SemaRef.getLangOpts().CPlusPlus17) {
13268       Tree.merge(RHSRegion);
13269       Tree.merge(LHSRegion);
13270     }
13271   }
13272 
13273   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13274     VisitBinAssign(CAO);
13275   }
13276 
13277   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13278   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13279   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13280     Object O = getObject(UO->getSubExpr(), true);
13281     if (!O)
13282       return VisitExpr(UO);
13283 
13284     notePreMod(O, UO);
13285     Visit(UO->getSubExpr());
13286     // C++11 [expr.pre.incr]p1:
13287     //   the expression ++x is equivalent to x+=1
13288     notePostMod(O, UO,
13289                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13290                                                 : UK_ModAsSideEffect);
13291   }
13292 
13293   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13294   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13295   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13296     Object O = getObject(UO->getSubExpr(), true);
13297     if (!O)
13298       return VisitExpr(UO);
13299 
13300     notePreMod(O, UO);
13301     Visit(UO->getSubExpr());
13302     notePostMod(O, UO, UK_ModAsSideEffect);
13303   }
13304 
13305   void VisitBinLOr(const BinaryOperator *BO) {
13306     // C++11 [expr.log.or]p2:
13307     //  If the second expression is evaluated, every value computation and
13308     //  side effect associated with the first expression is sequenced before
13309     //  every value computation and side effect associated with the
13310     //  second expression.
13311     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13312     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13313     SequenceTree::Seq OldRegion = Region;
13314 
13315     EvaluationTracker Eval(*this);
13316     {
13317       SequencedSubexpression Sequenced(*this);
13318       Region = LHSRegion;
13319       Visit(BO->getLHS());
13320     }
13321 
13322     // C++11 [expr.log.or]p1:
13323     //  [...] the second operand is not evaluated if the first operand
13324     //  evaluates to true.
13325     bool EvalResult = false;
13326     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13327     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13328     if (ShouldVisitRHS) {
13329       Region = RHSRegion;
13330       Visit(BO->getRHS());
13331     }
13332 
13333     Region = OldRegion;
13334     Tree.merge(LHSRegion);
13335     Tree.merge(RHSRegion);
13336   }
13337 
13338   void VisitBinLAnd(const BinaryOperator *BO) {
13339     // C++11 [expr.log.and]p2:
13340     //  If the second expression is evaluated, every value computation and
13341     //  side effect associated with the first expression is sequenced before
13342     //  every value computation and side effect associated with the
13343     //  second expression.
13344     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13345     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13346     SequenceTree::Seq OldRegion = Region;
13347 
13348     EvaluationTracker Eval(*this);
13349     {
13350       SequencedSubexpression Sequenced(*this);
13351       Region = LHSRegion;
13352       Visit(BO->getLHS());
13353     }
13354 
13355     // C++11 [expr.log.and]p1:
13356     //  [...] the second operand is not evaluated if the first operand is false.
13357     bool EvalResult = false;
13358     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13359     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13360     if (ShouldVisitRHS) {
13361       Region = RHSRegion;
13362       Visit(BO->getRHS());
13363     }
13364 
13365     Region = OldRegion;
13366     Tree.merge(LHSRegion);
13367     Tree.merge(RHSRegion);
13368   }
13369 
13370   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13371     // C++11 [expr.cond]p1:
13372     //  [...] Every value computation and side effect associated with the first
13373     //  expression is sequenced before every value computation and side effect
13374     //  associated with the second or third expression.
13375     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13376 
13377     // No sequencing is specified between the true and false expression.
13378     // However since exactly one of both is going to be evaluated we can
13379     // consider them to be sequenced. This is needed to avoid warning on
13380     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13381     // both the true and false expressions because we can't evaluate x.
13382     // This will still allow us to detect an expression like (pre C++17)
13383     // "(x ? y += 1 : y += 2) = y".
13384     //
13385     // We don't wrap the visitation of the true and false expression with
13386     // SequencedSubexpression because we don't want to downgrade modifications
13387     // as side effect in the true and false expressions after the visition
13388     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13389     // not warn between the two "y++", but we should warn between the "y++"
13390     // and the "y".
13391     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13392     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13393     SequenceTree::Seq OldRegion = Region;
13394 
13395     EvaluationTracker Eval(*this);
13396     {
13397       SequencedSubexpression Sequenced(*this);
13398       Region = ConditionRegion;
13399       Visit(CO->getCond());
13400     }
13401 
13402     // C++11 [expr.cond]p1:
13403     // [...] The first expression is contextually converted to bool (Clause 4).
13404     // It is evaluated and if it is true, the result of the conditional
13405     // expression is the value of the second expression, otherwise that of the
13406     // third expression. Only one of the second and third expressions is
13407     // evaluated. [...]
13408     bool EvalResult = false;
13409     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13410     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13411     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13412     if (ShouldVisitTrueExpr) {
13413       Region = TrueRegion;
13414       Visit(CO->getTrueExpr());
13415     }
13416     if (ShouldVisitFalseExpr) {
13417       Region = FalseRegion;
13418       Visit(CO->getFalseExpr());
13419     }
13420 
13421     Region = OldRegion;
13422     Tree.merge(ConditionRegion);
13423     Tree.merge(TrueRegion);
13424     Tree.merge(FalseRegion);
13425   }
13426 
13427   void VisitCallExpr(const CallExpr *CE) {
13428     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13429 
13430     if (CE->isUnevaluatedBuiltinCall(Context))
13431       return;
13432 
13433     // C++11 [intro.execution]p15:
13434     //   When calling a function [...], every value computation and side effect
13435     //   associated with any argument expression, or with the postfix expression
13436     //   designating the called function, is sequenced before execution of every
13437     //   expression or statement in the body of the function [and thus before
13438     //   the value computation of its result].
13439     SequencedSubexpression Sequenced(*this);
13440     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13441       // C++17 [expr.call]p5
13442       //   The postfix-expression is sequenced before each expression in the
13443       //   expression-list and any default argument. [...]
13444       SequenceTree::Seq CalleeRegion;
13445       SequenceTree::Seq OtherRegion;
13446       if (SemaRef.getLangOpts().CPlusPlus17) {
13447         CalleeRegion = Tree.allocate(Region);
13448         OtherRegion = Tree.allocate(Region);
13449       } else {
13450         CalleeRegion = Region;
13451         OtherRegion = Region;
13452       }
13453       SequenceTree::Seq OldRegion = Region;
13454 
13455       // Visit the callee expression first.
13456       Region = CalleeRegion;
13457       if (SemaRef.getLangOpts().CPlusPlus17) {
13458         SequencedSubexpression Sequenced(*this);
13459         Visit(CE->getCallee());
13460       } else {
13461         Visit(CE->getCallee());
13462       }
13463 
13464       // Then visit the argument expressions.
13465       Region = OtherRegion;
13466       for (const Expr *Argument : CE->arguments())
13467         Visit(Argument);
13468 
13469       Region = OldRegion;
13470       if (SemaRef.getLangOpts().CPlusPlus17) {
13471         Tree.merge(CalleeRegion);
13472         Tree.merge(OtherRegion);
13473       }
13474     });
13475   }
13476 
13477   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13478     // C++17 [over.match.oper]p2:
13479     //   [...] the operator notation is first transformed to the equivalent
13480     //   function-call notation as summarized in Table 12 (where @ denotes one
13481     //   of the operators covered in the specified subclause). However, the
13482     //   operands are sequenced in the order prescribed for the built-in
13483     //   operator (Clause 8).
13484     //
13485     // From the above only overloaded binary operators and overloaded call
13486     // operators have sequencing rules in C++17 that we need to handle
13487     // separately.
13488     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13489         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13490       return VisitCallExpr(CXXOCE);
13491 
13492     enum {
13493       NoSequencing,
13494       LHSBeforeRHS,
13495       RHSBeforeLHS,
13496       LHSBeforeRest
13497     } SequencingKind;
13498     switch (CXXOCE->getOperator()) {
13499     case OO_Equal:
13500     case OO_PlusEqual:
13501     case OO_MinusEqual:
13502     case OO_StarEqual:
13503     case OO_SlashEqual:
13504     case OO_PercentEqual:
13505     case OO_CaretEqual:
13506     case OO_AmpEqual:
13507     case OO_PipeEqual:
13508     case OO_LessLessEqual:
13509     case OO_GreaterGreaterEqual:
13510       SequencingKind = RHSBeforeLHS;
13511       break;
13512 
13513     case OO_LessLess:
13514     case OO_GreaterGreater:
13515     case OO_AmpAmp:
13516     case OO_PipePipe:
13517     case OO_Comma:
13518     case OO_ArrowStar:
13519     case OO_Subscript:
13520       SequencingKind = LHSBeforeRHS;
13521       break;
13522 
13523     case OO_Call:
13524       SequencingKind = LHSBeforeRest;
13525       break;
13526 
13527     default:
13528       SequencingKind = NoSequencing;
13529       break;
13530     }
13531 
13532     if (SequencingKind == NoSequencing)
13533       return VisitCallExpr(CXXOCE);
13534 
13535     // This is a call, so all subexpressions are sequenced before the result.
13536     SequencedSubexpression Sequenced(*this);
13537 
13538     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13539       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13540              "Should only get there with C++17 and above!");
13541       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13542              "Should only get there with an overloaded binary operator"
13543              " or an overloaded call operator!");
13544 
13545       if (SequencingKind == LHSBeforeRest) {
13546         assert(CXXOCE->getOperator() == OO_Call &&
13547                "We should only have an overloaded call operator here!");
13548 
13549         // This is very similar to VisitCallExpr, except that we only have the
13550         // C++17 case. The postfix-expression is the first argument of the
13551         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13552         // are in the following arguments.
13553         //
13554         // Note that we intentionally do not visit the callee expression since
13555         // it is just a decayed reference to a function.
13556         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13557         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13558         SequenceTree::Seq OldRegion = Region;
13559 
13560         assert(CXXOCE->getNumArgs() >= 1 &&
13561                "An overloaded call operator must have at least one argument"
13562                " for the postfix-expression!");
13563         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13564         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13565                                           CXXOCE->getNumArgs() - 1);
13566 
13567         // Visit the postfix-expression first.
13568         {
13569           Region = PostfixExprRegion;
13570           SequencedSubexpression Sequenced(*this);
13571           Visit(PostfixExpr);
13572         }
13573 
13574         // Then visit the argument expressions.
13575         Region = ArgsRegion;
13576         for (const Expr *Arg : Args)
13577           Visit(Arg);
13578 
13579         Region = OldRegion;
13580         Tree.merge(PostfixExprRegion);
13581         Tree.merge(ArgsRegion);
13582       } else {
13583         assert(CXXOCE->getNumArgs() == 2 &&
13584                "Should only have two arguments here!");
13585         assert((SequencingKind == LHSBeforeRHS ||
13586                 SequencingKind == RHSBeforeLHS) &&
13587                "Unexpected sequencing kind!");
13588 
13589         // We do not visit the callee expression since it is just a decayed
13590         // reference to a function.
13591         const Expr *E1 = CXXOCE->getArg(0);
13592         const Expr *E2 = CXXOCE->getArg(1);
13593         if (SequencingKind == RHSBeforeLHS)
13594           std::swap(E1, E2);
13595 
13596         return VisitSequencedExpressions(E1, E2);
13597       }
13598     });
13599   }
13600 
13601   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13602     // This is a call, so all subexpressions are sequenced before the result.
13603     SequencedSubexpression Sequenced(*this);
13604 
13605     if (!CCE->isListInitialization())
13606       return VisitExpr(CCE);
13607 
13608     // In C++11, list initializations are sequenced.
13609     SmallVector<SequenceTree::Seq, 32> Elts;
13610     SequenceTree::Seq Parent = Region;
13611     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13612                                               E = CCE->arg_end();
13613          I != E; ++I) {
13614       Region = Tree.allocate(Parent);
13615       Elts.push_back(Region);
13616       Visit(*I);
13617     }
13618 
13619     // Forget that the initializers are sequenced.
13620     Region = Parent;
13621     for (unsigned I = 0; I < Elts.size(); ++I)
13622       Tree.merge(Elts[I]);
13623   }
13624 
13625   void VisitInitListExpr(const InitListExpr *ILE) {
13626     if (!SemaRef.getLangOpts().CPlusPlus11)
13627       return VisitExpr(ILE);
13628 
13629     // In C++11, list initializations are sequenced.
13630     SmallVector<SequenceTree::Seq, 32> Elts;
13631     SequenceTree::Seq Parent = Region;
13632     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13633       const Expr *E = ILE->getInit(I);
13634       if (!E)
13635         continue;
13636       Region = Tree.allocate(Parent);
13637       Elts.push_back(Region);
13638       Visit(E);
13639     }
13640 
13641     // Forget that the initializers are sequenced.
13642     Region = Parent;
13643     for (unsigned I = 0; I < Elts.size(); ++I)
13644       Tree.merge(Elts[I]);
13645   }
13646 };
13647 
13648 } // namespace
13649 
13650 void Sema::CheckUnsequencedOperations(const Expr *E) {
13651   SmallVector<const Expr *, 8> WorkList;
13652   WorkList.push_back(E);
13653   while (!WorkList.empty()) {
13654     const Expr *Item = WorkList.pop_back_val();
13655     SequenceChecker(*this, Item, WorkList);
13656   }
13657 }
13658 
13659 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13660                               bool IsConstexpr) {
13661   llvm::SaveAndRestore<bool> ConstantContext(
13662       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13663   CheckImplicitConversions(E, CheckLoc);
13664   if (!E->isInstantiationDependent())
13665     CheckUnsequencedOperations(E);
13666   if (!IsConstexpr && !E->isValueDependent())
13667     CheckForIntOverflow(E);
13668   DiagnoseMisalignedMembers();
13669 }
13670 
13671 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13672                                        FieldDecl *BitField,
13673                                        Expr *Init) {
13674   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13675 }
13676 
13677 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13678                                          SourceLocation Loc) {
13679   if (!PType->isVariablyModifiedType())
13680     return;
13681   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13682     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13683     return;
13684   }
13685   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13686     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13687     return;
13688   }
13689   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13690     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13691     return;
13692   }
13693 
13694   const ArrayType *AT = S.Context.getAsArrayType(PType);
13695   if (!AT)
13696     return;
13697 
13698   if (AT->getSizeModifier() != ArrayType::Star) {
13699     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13700     return;
13701   }
13702 
13703   S.Diag(Loc, diag::err_array_star_in_function_definition);
13704 }
13705 
13706 /// CheckParmsForFunctionDef - Check that the parameters of the given
13707 /// function are appropriate for the definition of a function. This
13708 /// takes care of any checks that cannot be performed on the
13709 /// declaration itself, e.g., that the types of each of the function
13710 /// parameters are complete.
13711 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13712                                     bool CheckParameterNames) {
13713   bool HasInvalidParm = false;
13714   for (ParmVarDecl *Param : Parameters) {
13715     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13716     // function declarator that is part of a function definition of
13717     // that function shall not have incomplete type.
13718     //
13719     // This is also C++ [dcl.fct]p6.
13720     if (!Param->isInvalidDecl() &&
13721         RequireCompleteType(Param->getLocation(), Param->getType(),
13722                             diag::err_typecheck_decl_incomplete_type)) {
13723       Param->setInvalidDecl();
13724       HasInvalidParm = true;
13725     }
13726 
13727     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13728     // declaration of each parameter shall include an identifier.
13729     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13730         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13731       // Diagnose this as an extension in C17 and earlier.
13732       if (!getLangOpts().C2x)
13733         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13734     }
13735 
13736     // C99 6.7.5.3p12:
13737     //   If the function declarator is not part of a definition of that
13738     //   function, parameters may have incomplete type and may use the [*]
13739     //   notation in their sequences of declarator specifiers to specify
13740     //   variable length array types.
13741     QualType PType = Param->getOriginalType();
13742     // FIXME: This diagnostic should point the '[*]' if source-location
13743     // information is added for it.
13744     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13745 
13746     // If the parameter is a c++ class type and it has to be destructed in the
13747     // callee function, declare the destructor so that it can be called by the
13748     // callee function. Do not perform any direct access check on the dtor here.
13749     if (!Param->isInvalidDecl()) {
13750       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13751         if (!ClassDecl->isInvalidDecl() &&
13752             !ClassDecl->hasIrrelevantDestructor() &&
13753             !ClassDecl->isDependentContext() &&
13754             ClassDecl->isParamDestroyedInCallee()) {
13755           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13756           MarkFunctionReferenced(Param->getLocation(), Destructor);
13757           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13758         }
13759       }
13760     }
13761 
13762     // Parameters with the pass_object_size attribute only need to be marked
13763     // constant at function definitions. Because we lack information about
13764     // whether we're on a declaration or definition when we're instantiating the
13765     // attribute, we need to check for constness here.
13766     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13767       if (!Param->getType().isConstQualified())
13768         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13769             << Attr->getSpelling() << 1;
13770 
13771     // Check for parameter names shadowing fields from the class.
13772     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13773       // The owning context for the parameter should be the function, but we
13774       // want to see if this function's declaration context is a record.
13775       DeclContext *DC = Param->getDeclContext();
13776       if (DC && DC->isFunctionOrMethod()) {
13777         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13778           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13779                                      RD, /*DeclIsField*/ false);
13780       }
13781     }
13782   }
13783 
13784   return HasInvalidParm;
13785 }
13786 
13787 Optional<std::pair<CharUnits, CharUnits>>
13788 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13789 
13790 /// Compute the alignment and offset of the base class object given the
13791 /// derived-to-base cast expression and the alignment and offset of the derived
13792 /// class object.
13793 static std::pair<CharUnits, CharUnits>
13794 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13795                                    CharUnits BaseAlignment, CharUnits Offset,
13796                                    ASTContext &Ctx) {
13797   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13798        ++PathI) {
13799     const CXXBaseSpecifier *Base = *PathI;
13800     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13801     if (Base->isVirtual()) {
13802       // The complete object may have a lower alignment than the non-virtual
13803       // alignment of the base, in which case the base may be misaligned. Choose
13804       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13805       // conservative lower bound of the complete object alignment.
13806       CharUnits NonVirtualAlignment =
13807           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13808       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13809       Offset = CharUnits::Zero();
13810     } else {
13811       const ASTRecordLayout &RL =
13812           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13813       Offset += RL.getBaseClassOffset(BaseDecl);
13814     }
13815     DerivedType = Base->getType();
13816   }
13817 
13818   return std::make_pair(BaseAlignment, Offset);
13819 }
13820 
13821 /// Compute the alignment and offset of a binary additive operator.
13822 static Optional<std::pair<CharUnits, CharUnits>>
13823 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13824                                      bool IsSub, ASTContext &Ctx) {
13825   QualType PointeeType = PtrE->getType()->getPointeeType();
13826 
13827   if (!PointeeType->isConstantSizeType())
13828     return llvm::None;
13829 
13830   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13831 
13832   if (!P)
13833     return llvm::None;
13834 
13835   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13836   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13837     CharUnits Offset = EltSize * IdxRes->getExtValue();
13838     if (IsSub)
13839       Offset = -Offset;
13840     return std::make_pair(P->first, P->second + Offset);
13841   }
13842 
13843   // If the integer expression isn't a constant expression, compute the lower
13844   // bound of the alignment using the alignment and offset of the pointer
13845   // expression and the element size.
13846   return std::make_pair(
13847       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13848       CharUnits::Zero());
13849 }
13850 
13851 /// This helper function takes an lvalue expression and returns the alignment of
13852 /// a VarDecl and a constant offset from the VarDecl.
13853 Optional<std::pair<CharUnits, CharUnits>>
13854 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13855   E = E->IgnoreParens();
13856   switch (E->getStmtClass()) {
13857   default:
13858     break;
13859   case Stmt::CStyleCastExprClass:
13860   case Stmt::CXXStaticCastExprClass:
13861   case Stmt::ImplicitCastExprClass: {
13862     auto *CE = cast<CastExpr>(E);
13863     const Expr *From = CE->getSubExpr();
13864     switch (CE->getCastKind()) {
13865     default:
13866       break;
13867     case CK_NoOp:
13868       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13869     case CK_UncheckedDerivedToBase:
13870     case CK_DerivedToBase: {
13871       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13872       if (!P)
13873         break;
13874       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13875                                                 P->second, Ctx);
13876     }
13877     }
13878     break;
13879   }
13880   case Stmt::ArraySubscriptExprClass: {
13881     auto *ASE = cast<ArraySubscriptExpr>(E);
13882     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13883                                                 false, Ctx);
13884   }
13885   case Stmt::DeclRefExprClass: {
13886     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13887       // FIXME: If VD is captured by copy or is an escaping __block variable,
13888       // use the alignment of VD's type.
13889       if (!VD->getType()->isReferenceType())
13890         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13891       if (VD->hasInit())
13892         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13893     }
13894     break;
13895   }
13896   case Stmt::MemberExprClass: {
13897     auto *ME = cast<MemberExpr>(E);
13898     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13899     if (!FD || FD->getType()->isReferenceType())
13900       break;
13901     Optional<std::pair<CharUnits, CharUnits>> P;
13902     if (ME->isArrow())
13903       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
13904     else
13905       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13906     if (!P)
13907       break;
13908     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13909     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13910     return std::make_pair(P->first,
13911                           P->second + CharUnits::fromQuantity(Offset));
13912   }
13913   case Stmt::UnaryOperatorClass: {
13914     auto *UO = cast<UnaryOperator>(E);
13915     switch (UO->getOpcode()) {
13916     default:
13917       break;
13918     case UO_Deref:
13919       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13920     }
13921     break;
13922   }
13923   case Stmt::BinaryOperatorClass: {
13924     auto *BO = cast<BinaryOperator>(E);
13925     auto Opcode = BO->getOpcode();
13926     switch (Opcode) {
13927     default:
13928       break;
13929     case BO_Comma:
13930       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13931     }
13932     break;
13933   }
13934   }
13935   return llvm::None;
13936 }
13937 
13938 /// This helper function takes a pointer expression and returns the alignment of
13939 /// a VarDecl and a constant offset from the VarDecl.
13940 Optional<std::pair<CharUnits, CharUnits>>
13941 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13942   E = E->IgnoreParens();
13943   switch (E->getStmtClass()) {
13944   default:
13945     break;
13946   case Stmt::CStyleCastExprClass:
13947   case Stmt::CXXStaticCastExprClass:
13948   case Stmt::ImplicitCastExprClass: {
13949     auto *CE = cast<CastExpr>(E);
13950     const Expr *From = CE->getSubExpr();
13951     switch (CE->getCastKind()) {
13952     default:
13953       break;
13954     case CK_NoOp:
13955       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13956     case CK_ArrayToPointerDecay:
13957       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13958     case CK_UncheckedDerivedToBase:
13959     case CK_DerivedToBase: {
13960       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13961       if (!P)
13962         break;
13963       return getDerivedToBaseAlignmentAndOffset(
13964           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13965     }
13966     }
13967     break;
13968   }
13969   case Stmt::CXXThisExprClass: {
13970     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13971     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
13972     return std::make_pair(Alignment, CharUnits::Zero());
13973   }
13974   case Stmt::UnaryOperatorClass: {
13975     auto *UO = cast<UnaryOperator>(E);
13976     if (UO->getOpcode() == UO_AddrOf)
13977       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13978     break;
13979   }
13980   case Stmt::BinaryOperatorClass: {
13981     auto *BO = cast<BinaryOperator>(E);
13982     auto Opcode = BO->getOpcode();
13983     switch (Opcode) {
13984     default:
13985       break;
13986     case BO_Add:
13987     case BO_Sub: {
13988       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13989       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13990         std::swap(LHS, RHS);
13991       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13992                                                   Ctx);
13993     }
13994     case BO_Comma:
13995       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13996     }
13997     break;
13998   }
13999   }
14000   return llvm::None;
14001 }
14002 
14003 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14004   // See if we can compute the alignment of a VarDecl and an offset from it.
14005   Optional<std::pair<CharUnits, CharUnits>> P =
14006       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14007 
14008   if (P)
14009     return P->first.alignmentAtOffset(P->second);
14010 
14011   // If that failed, return the type's alignment.
14012   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14013 }
14014 
14015 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14016 /// pointer cast increases the alignment requirements.
14017 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14018   // This is actually a lot of work to potentially be doing on every
14019   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14020   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14021     return;
14022 
14023   // Ignore dependent types.
14024   if (T->isDependentType() || Op->getType()->isDependentType())
14025     return;
14026 
14027   // Require that the destination be a pointer type.
14028   const PointerType *DestPtr = T->getAs<PointerType>();
14029   if (!DestPtr) return;
14030 
14031   // If the destination has alignment 1, we're done.
14032   QualType DestPointee = DestPtr->getPointeeType();
14033   if (DestPointee->isIncompleteType()) return;
14034   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14035   if (DestAlign.isOne()) return;
14036 
14037   // Require that the source be a pointer type.
14038   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14039   if (!SrcPtr) return;
14040   QualType SrcPointee = SrcPtr->getPointeeType();
14041 
14042   // Explicitly allow casts from cv void*.  We already implicitly
14043   // allowed casts to cv void*, since they have alignment 1.
14044   // Also allow casts involving incomplete types, which implicitly
14045   // includes 'void'.
14046   if (SrcPointee->isIncompleteType()) return;
14047 
14048   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14049 
14050   if (SrcAlign >= DestAlign) return;
14051 
14052   Diag(TRange.getBegin(), diag::warn_cast_align)
14053     << Op->getType() << T
14054     << static_cast<unsigned>(SrcAlign.getQuantity())
14055     << static_cast<unsigned>(DestAlign.getQuantity())
14056     << TRange << Op->getSourceRange();
14057 }
14058 
14059 /// Check whether this array fits the idiom of a size-one tail padded
14060 /// array member of a struct.
14061 ///
14062 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14063 /// commonly used to emulate flexible arrays in C89 code.
14064 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14065                                     const NamedDecl *ND) {
14066   if (Size != 1 || !ND) return false;
14067 
14068   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14069   if (!FD) return false;
14070 
14071   // Don't consider sizes resulting from macro expansions or template argument
14072   // substitution to form C89 tail-padded arrays.
14073 
14074   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14075   while (TInfo) {
14076     TypeLoc TL = TInfo->getTypeLoc();
14077     // Look through typedefs.
14078     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14079       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14080       TInfo = TDL->getTypeSourceInfo();
14081       continue;
14082     }
14083     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14084       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14085       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14086         return false;
14087     }
14088     break;
14089   }
14090 
14091   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14092   if (!RD) return false;
14093   if (RD->isUnion()) return false;
14094   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14095     if (!CRD->isStandardLayout()) return false;
14096   }
14097 
14098   // See if this is the last field decl in the record.
14099   const Decl *D = FD;
14100   while ((D = D->getNextDeclInContext()))
14101     if (isa<FieldDecl>(D))
14102       return false;
14103   return true;
14104 }
14105 
14106 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14107                             const ArraySubscriptExpr *ASE,
14108                             bool AllowOnePastEnd, bool IndexNegated) {
14109   // Already diagnosed by the constant evaluator.
14110   if (isConstantEvaluated())
14111     return;
14112 
14113   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14114   if (IndexExpr->isValueDependent())
14115     return;
14116 
14117   const Type *EffectiveType =
14118       BaseExpr->getType()->getPointeeOrArrayElementType();
14119   BaseExpr = BaseExpr->IgnoreParenCasts();
14120   const ConstantArrayType *ArrayTy =
14121       Context.getAsConstantArrayType(BaseExpr->getType());
14122 
14123   if (!ArrayTy)
14124     return;
14125 
14126   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14127   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14128     return;
14129 
14130   Expr::EvalResult Result;
14131   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14132     return;
14133 
14134   llvm::APSInt index = Result.Val.getInt();
14135   if (IndexNegated)
14136     index = -index;
14137 
14138   const NamedDecl *ND = nullptr;
14139   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14140     ND = DRE->getDecl();
14141   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14142     ND = ME->getMemberDecl();
14143 
14144   if (index.isUnsigned() || !index.isNegative()) {
14145     // It is possible that the type of the base expression after
14146     // IgnoreParenCasts is incomplete, even though the type of the base
14147     // expression before IgnoreParenCasts is complete (see PR39746 for an
14148     // example). In this case we have no information about whether the array
14149     // access exceeds the array bounds. However we can still diagnose an array
14150     // access which precedes the array bounds.
14151     if (BaseType->isIncompleteType())
14152       return;
14153 
14154     llvm::APInt size = ArrayTy->getSize();
14155     if (!size.isStrictlyPositive())
14156       return;
14157 
14158     if (BaseType != EffectiveType) {
14159       // Make sure we're comparing apples to apples when comparing index to size
14160       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14161       uint64_t array_typesize = Context.getTypeSize(BaseType);
14162       // Handle ptrarith_typesize being zero, such as when casting to void*
14163       if (!ptrarith_typesize) ptrarith_typesize = 1;
14164       if (ptrarith_typesize != array_typesize) {
14165         // There's a cast to a different size type involved
14166         uint64_t ratio = array_typesize / ptrarith_typesize;
14167         // TODO: Be smarter about handling cases where array_typesize is not a
14168         // multiple of ptrarith_typesize
14169         if (ptrarith_typesize * ratio == array_typesize)
14170           size *= llvm::APInt(size.getBitWidth(), ratio);
14171       }
14172     }
14173 
14174     if (size.getBitWidth() > index.getBitWidth())
14175       index = index.zext(size.getBitWidth());
14176     else if (size.getBitWidth() < index.getBitWidth())
14177       size = size.zext(index.getBitWidth());
14178 
14179     // For array subscripting the index must be less than size, but for pointer
14180     // arithmetic also allow the index (offset) to be equal to size since
14181     // computing the next address after the end of the array is legal and
14182     // commonly done e.g. in C++ iterators and range-based for loops.
14183     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14184       return;
14185 
14186     // Also don't warn for arrays of size 1 which are members of some
14187     // structure. These are often used to approximate flexible arrays in C89
14188     // code.
14189     if (IsTailPaddedMemberArray(*this, size, ND))
14190       return;
14191 
14192     // Suppress the warning if the subscript expression (as identified by the
14193     // ']' location) and the index expression are both from macro expansions
14194     // within a system header.
14195     if (ASE) {
14196       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14197           ASE->getRBracketLoc());
14198       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14199         SourceLocation IndexLoc =
14200             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14201         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14202           return;
14203       }
14204     }
14205 
14206     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14207     if (ASE)
14208       DiagID = diag::warn_array_index_exceeds_bounds;
14209 
14210     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14211                         PDiag(DiagID) << index.toString(10, true)
14212                                       << size.toString(10, true)
14213                                       << (unsigned)size.getLimitedValue(~0U)
14214                                       << IndexExpr->getSourceRange());
14215   } else {
14216     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14217     if (!ASE) {
14218       DiagID = diag::warn_ptr_arith_precedes_bounds;
14219       if (index.isNegative()) index = -index;
14220     }
14221 
14222     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14223                         PDiag(DiagID) << index.toString(10, true)
14224                                       << IndexExpr->getSourceRange());
14225   }
14226 
14227   if (!ND) {
14228     // Try harder to find a NamedDecl to point at in the note.
14229     while (const ArraySubscriptExpr *ASE =
14230            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14231       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14232     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14233       ND = DRE->getDecl();
14234     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14235       ND = ME->getMemberDecl();
14236   }
14237 
14238   if (ND)
14239     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14240                         PDiag(diag::note_array_declared_here) << ND);
14241 }
14242 
14243 void Sema::CheckArrayAccess(const Expr *expr) {
14244   int AllowOnePastEnd = 0;
14245   while (expr) {
14246     expr = expr->IgnoreParenImpCasts();
14247     switch (expr->getStmtClass()) {
14248       case Stmt::ArraySubscriptExprClass: {
14249         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14250         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14251                          AllowOnePastEnd > 0);
14252         expr = ASE->getBase();
14253         break;
14254       }
14255       case Stmt::MemberExprClass: {
14256         expr = cast<MemberExpr>(expr)->getBase();
14257         break;
14258       }
14259       case Stmt::OMPArraySectionExprClass: {
14260         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14261         if (ASE->getLowerBound())
14262           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14263                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14264         return;
14265       }
14266       case Stmt::UnaryOperatorClass: {
14267         // Only unwrap the * and & unary operators
14268         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14269         expr = UO->getSubExpr();
14270         switch (UO->getOpcode()) {
14271           case UO_AddrOf:
14272             AllowOnePastEnd++;
14273             break;
14274           case UO_Deref:
14275             AllowOnePastEnd--;
14276             break;
14277           default:
14278             return;
14279         }
14280         break;
14281       }
14282       case Stmt::ConditionalOperatorClass: {
14283         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14284         if (const Expr *lhs = cond->getLHS())
14285           CheckArrayAccess(lhs);
14286         if (const Expr *rhs = cond->getRHS())
14287           CheckArrayAccess(rhs);
14288         return;
14289       }
14290       case Stmt::CXXOperatorCallExprClass: {
14291         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14292         for (const auto *Arg : OCE->arguments())
14293           CheckArrayAccess(Arg);
14294         return;
14295       }
14296       default:
14297         return;
14298     }
14299   }
14300 }
14301 
14302 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14303 
14304 namespace {
14305 
14306 struct RetainCycleOwner {
14307   VarDecl *Variable = nullptr;
14308   SourceRange Range;
14309   SourceLocation Loc;
14310   bool Indirect = false;
14311 
14312   RetainCycleOwner() = default;
14313 
14314   void setLocsFrom(Expr *e) {
14315     Loc = e->getExprLoc();
14316     Range = e->getSourceRange();
14317   }
14318 };
14319 
14320 } // namespace
14321 
14322 /// Consider whether capturing the given variable can possibly lead to
14323 /// a retain cycle.
14324 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14325   // In ARC, it's captured strongly iff the variable has __strong
14326   // lifetime.  In MRR, it's captured strongly if the variable is
14327   // __block and has an appropriate type.
14328   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14329     return false;
14330 
14331   owner.Variable = var;
14332   if (ref)
14333     owner.setLocsFrom(ref);
14334   return true;
14335 }
14336 
14337 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14338   while (true) {
14339     e = e->IgnoreParens();
14340     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14341       switch (cast->getCastKind()) {
14342       case CK_BitCast:
14343       case CK_LValueBitCast:
14344       case CK_LValueToRValue:
14345       case CK_ARCReclaimReturnedObject:
14346         e = cast->getSubExpr();
14347         continue;
14348 
14349       default:
14350         return false;
14351       }
14352     }
14353 
14354     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14355       ObjCIvarDecl *ivar = ref->getDecl();
14356       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14357         return false;
14358 
14359       // Try to find a retain cycle in the base.
14360       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14361         return false;
14362 
14363       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14364       owner.Indirect = true;
14365       return true;
14366     }
14367 
14368     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14369       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14370       if (!var) return false;
14371       return considerVariable(var, ref, owner);
14372     }
14373 
14374     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14375       if (member->isArrow()) return false;
14376 
14377       // Don't count this as an indirect ownership.
14378       e = member->getBase();
14379       continue;
14380     }
14381 
14382     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14383       // Only pay attention to pseudo-objects on property references.
14384       ObjCPropertyRefExpr *pre
14385         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14386                                               ->IgnoreParens());
14387       if (!pre) return false;
14388       if (pre->isImplicitProperty()) return false;
14389       ObjCPropertyDecl *property = pre->getExplicitProperty();
14390       if (!property->isRetaining() &&
14391           !(property->getPropertyIvarDecl() &&
14392             property->getPropertyIvarDecl()->getType()
14393               .getObjCLifetime() == Qualifiers::OCL_Strong))
14394           return false;
14395 
14396       owner.Indirect = true;
14397       if (pre->isSuperReceiver()) {
14398         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14399         if (!owner.Variable)
14400           return false;
14401         owner.Loc = pre->getLocation();
14402         owner.Range = pre->getSourceRange();
14403         return true;
14404       }
14405       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14406                               ->getSourceExpr());
14407       continue;
14408     }
14409 
14410     // Array ivars?
14411 
14412     return false;
14413   }
14414 }
14415 
14416 namespace {
14417 
14418   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14419     ASTContext &Context;
14420     VarDecl *Variable;
14421     Expr *Capturer = nullptr;
14422     bool VarWillBeReased = false;
14423 
14424     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14425         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14426           Context(Context), Variable(variable) {}
14427 
14428     void VisitDeclRefExpr(DeclRefExpr *ref) {
14429       if (ref->getDecl() == Variable && !Capturer)
14430         Capturer = ref;
14431     }
14432 
14433     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14434       if (Capturer) return;
14435       Visit(ref->getBase());
14436       if (Capturer && ref->isFreeIvar())
14437         Capturer = ref;
14438     }
14439 
14440     void VisitBlockExpr(BlockExpr *block) {
14441       // Look inside nested blocks
14442       if (block->getBlockDecl()->capturesVariable(Variable))
14443         Visit(block->getBlockDecl()->getBody());
14444     }
14445 
14446     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14447       if (Capturer) return;
14448       if (OVE->getSourceExpr())
14449         Visit(OVE->getSourceExpr());
14450     }
14451 
14452     void VisitBinaryOperator(BinaryOperator *BinOp) {
14453       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14454         return;
14455       Expr *LHS = BinOp->getLHS();
14456       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14457         if (DRE->getDecl() != Variable)
14458           return;
14459         if (Expr *RHS = BinOp->getRHS()) {
14460           RHS = RHS->IgnoreParenCasts();
14461           Optional<llvm::APSInt> Value;
14462           VarWillBeReased =
14463               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14464                *Value == 0);
14465         }
14466       }
14467     }
14468   };
14469 
14470 } // namespace
14471 
14472 /// Check whether the given argument is a block which captures a
14473 /// variable.
14474 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14475   assert(owner.Variable && owner.Loc.isValid());
14476 
14477   e = e->IgnoreParenCasts();
14478 
14479   // Look through [^{...} copy] and Block_copy(^{...}).
14480   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14481     Selector Cmd = ME->getSelector();
14482     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14483       e = ME->getInstanceReceiver();
14484       if (!e)
14485         return nullptr;
14486       e = e->IgnoreParenCasts();
14487     }
14488   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14489     if (CE->getNumArgs() == 1) {
14490       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14491       if (Fn) {
14492         const IdentifierInfo *FnI = Fn->getIdentifier();
14493         if (FnI && FnI->isStr("_Block_copy")) {
14494           e = CE->getArg(0)->IgnoreParenCasts();
14495         }
14496       }
14497     }
14498   }
14499 
14500   BlockExpr *block = dyn_cast<BlockExpr>(e);
14501   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14502     return nullptr;
14503 
14504   FindCaptureVisitor visitor(S.Context, owner.Variable);
14505   visitor.Visit(block->getBlockDecl()->getBody());
14506   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14507 }
14508 
14509 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14510                                 RetainCycleOwner &owner) {
14511   assert(capturer);
14512   assert(owner.Variable && owner.Loc.isValid());
14513 
14514   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14515     << owner.Variable << capturer->getSourceRange();
14516   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14517     << owner.Indirect << owner.Range;
14518 }
14519 
14520 /// Check for a keyword selector that starts with the word 'add' or
14521 /// 'set'.
14522 static bool isSetterLikeSelector(Selector sel) {
14523   if (sel.isUnarySelector()) return false;
14524 
14525   StringRef str = sel.getNameForSlot(0);
14526   while (!str.empty() && str.front() == '_') str = str.substr(1);
14527   if (str.startswith("set"))
14528     str = str.substr(3);
14529   else if (str.startswith("add")) {
14530     // Specially allow 'addOperationWithBlock:'.
14531     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14532       return false;
14533     str = str.substr(3);
14534   }
14535   else
14536     return false;
14537 
14538   if (str.empty()) return true;
14539   return !isLowercase(str.front());
14540 }
14541 
14542 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14543                                                     ObjCMessageExpr *Message) {
14544   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14545                                                 Message->getReceiverInterface(),
14546                                                 NSAPI::ClassId_NSMutableArray);
14547   if (!IsMutableArray) {
14548     return None;
14549   }
14550 
14551   Selector Sel = Message->getSelector();
14552 
14553   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14554     S.NSAPIObj->getNSArrayMethodKind(Sel);
14555   if (!MKOpt) {
14556     return None;
14557   }
14558 
14559   NSAPI::NSArrayMethodKind MK = *MKOpt;
14560 
14561   switch (MK) {
14562     case NSAPI::NSMutableArr_addObject:
14563     case NSAPI::NSMutableArr_insertObjectAtIndex:
14564     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14565       return 0;
14566     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14567       return 1;
14568 
14569     default:
14570       return None;
14571   }
14572 
14573   return None;
14574 }
14575 
14576 static
14577 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14578                                                   ObjCMessageExpr *Message) {
14579   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14580                                             Message->getReceiverInterface(),
14581                                             NSAPI::ClassId_NSMutableDictionary);
14582   if (!IsMutableDictionary) {
14583     return None;
14584   }
14585 
14586   Selector Sel = Message->getSelector();
14587 
14588   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14589     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14590   if (!MKOpt) {
14591     return None;
14592   }
14593 
14594   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14595 
14596   switch (MK) {
14597     case NSAPI::NSMutableDict_setObjectForKey:
14598     case NSAPI::NSMutableDict_setValueForKey:
14599     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14600       return 0;
14601 
14602     default:
14603       return None;
14604   }
14605 
14606   return None;
14607 }
14608 
14609 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14610   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14611                                                 Message->getReceiverInterface(),
14612                                                 NSAPI::ClassId_NSMutableSet);
14613 
14614   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14615                                             Message->getReceiverInterface(),
14616                                             NSAPI::ClassId_NSMutableOrderedSet);
14617   if (!IsMutableSet && !IsMutableOrderedSet) {
14618     return None;
14619   }
14620 
14621   Selector Sel = Message->getSelector();
14622 
14623   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14624   if (!MKOpt) {
14625     return None;
14626   }
14627 
14628   NSAPI::NSSetMethodKind MK = *MKOpt;
14629 
14630   switch (MK) {
14631     case NSAPI::NSMutableSet_addObject:
14632     case NSAPI::NSOrderedSet_setObjectAtIndex:
14633     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14634     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14635       return 0;
14636     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14637       return 1;
14638   }
14639 
14640   return None;
14641 }
14642 
14643 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14644   if (!Message->isInstanceMessage()) {
14645     return;
14646   }
14647 
14648   Optional<int> ArgOpt;
14649 
14650   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14651       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14652       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14653     return;
14654   }
14655 
14656   int ArgIndex = *ArgOpt;
14657 
14658   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14659   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14660     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14661   }
14662 
14663   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14664     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14665       if (ArgRE->isObjCSelfExpr()) {
14666         Diag(Message->getSourceRange().getBegin(),
14667              diag::warn_objc_circular_container)
14668           << ArgRE->getDecl() << StringRef("'super'");
14669       }
14670     }
14671   } else {
14672     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14673 
14674     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14675       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14676     }
14677 
14678     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14679       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14680         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14681           ValueDecl *Decl = ReceiverRE->getDecl();
14682           Diag(Message->getSourceRange().getBegin(),
14683                diag::warn_objc_circular_container)
14684             << Decl << Decl;
14685           if (!ArgRE->isObjCSelfExpr()) {
14686             Diag(Decl->getLocation(),
14687                  diag::note_objc_circular_container_declared_here)
14688               << Decl;
14689           }
14690         }
14691       }
14692     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14693       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14694         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14695           ObjCIvarDecl *Decl = IvarRE->getDecl();
14696           Diag(Message->getSourceRange().getBegin(),
14697                diag::warn_objc_circular_container)
14698             << Decl << Decl;
14699           Diag(Decl->getLocation(),
14700                diag::note_objc_circular_container_declared_here)
14701             << Decl;
14702         }
14703       }
14704     }
14705   }
14706 }
14707 
14708 /// Check a message send to see if it's likely to cause a retain cycle.
14709 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14710   // Only check instance methods whose selector looks like a setter.
14711   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14712     return;
14713 
14714   // Try to find a variable that the receiver is strongly owned by.
14715   RetainCycleOwner owner;
14716   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14717     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14718       return;
14719   } else {
14720     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14721     owner.Variable = getCurMethodDecl()->getSelfDecl();
14722     owner.Loc = msg->getSuperLoc();
14723     owner.Range = msg->getSuperLoc();
14724   }
14725 
14726   // Check whether the receiver is captured by any of the arguments.
14727   const ObjCMethodDecl *MD = msg->getMethodDecl();
14728   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14729     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14730       // noescape blocks should not be retained by the method.
14731       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14732         continue;
14733       return diagnoseRetainCycle(*this, capturer, owner);
14734     }
14735   }
14736 }
14737 
14738 /// Check a property assign to see if it's likely to cause a retain cycle.
14739 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14740   RetainCycleOwner owner;
14741   if (!findRetainCycleOwner(*this, receiver, owner))
14742     return;
14743 
14744   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14745     diagnoseRetainCycle(*this, capturer, owner);
14746 }
14747 
14748 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14749   RetainCycleOwner Owner;
14750   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14751     return;
14752 
14753   // Because we don't have an expression for the variable, we have to set the
14754   // location explicitly here.
14755   Owner.Loc = Var->getLocation();
14756   Owner.Range = Var->getSourceRange();
14757 
14758   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14759     diagnoseRetainCycle(*this, Capturer, Owner);
14760 }
14761 
14762 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14763                                      Expr *RHS, bool isProperty) {
14764   // Check if RHS is an Objective-C object literal, which also can get
14765   // immediately zapped in a weak reference.  Note that we explicitly
14766   // allow ObjCStringLiterals, since those are designed to never really die.
14767   RHS = RHS->IgnoreParenImpCasts();
14768 
14769   // This enum needs to match with the 'select' in
14770   // warn_objc_arc_literal_assign (off-by-1).
14771   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14772   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14773     return false;
14774 
14775   S.Diag(Loc, diag::warn_arc_literal_assign)
14776     << (unsigned) Kind
14777     << (isProperty ? 0 : 1)
14778     << RHS->getSourceRange();
14779 
14780   return true;
14781 }
14782 
14783 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14784                                     Qualifiers::ObjCLifetime LT,
14785                                     Expr *RHS, bool isProperty) {
14786   // Strip off any implicit cast added to get to the one ARC-specific.
14787   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14788     if (cast->getCastKind() == CK_ARCConsumeObject) {
14789       S.Diag(Loc, diag::warn_arc_retained_assign)
14790         << (LT == Qualifiers::OCL_ExplicitNone)
14791         << (isProperty ? 0 : 1)
14792         << RHS->getSourceRange();
14793       return true;
14794     }
14795     RHS = cast->getSubExpr();
14796   }
14797 
14798   if (LT == Qualifiers::OCL_Weak &&
14799       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14800     return true;
14801 
14802   return false;
14803 }
14804 
14805 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14806                               QualType LHS, Expr *RHS) {
14807   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14808 
14809   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14810     return false;
14811 
14812   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14813     return true;
14814 
14815   return false;
14816 }
14817 
14818 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14819                               Expr *LHS, Expr *RHS) {
14820   QualType LHSType;
14821   // PropertyRef on LHS type need be directly obtained from
14822   // its declaration as it has a PseudoType.
14823   ObjCPropertyRefExpr *PRE
14824     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14825   if (PRE && !PRE->isImplicitProperty()) {
14826     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14827     if (PD)
14828       LHSType = PD->getType();
14829   }
14830 
14831   if (LHSType.isNull())
14832     LHSType = LHS->getType();
14833 
14834   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14835 
14836   if (LT == Qualifiers::OCL_Weak) {
14837     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14838       getCurFunction()->markSafeWeakUse(LHS);
14839   }
14840 
14841   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14842     return;
14843 
14844   // FIXME. Check for other life times.
14845   if (LT != Qualifiers::OCL_None)
14846     return;
14847 
14848   if (PRE) {
14849     if (PRE->isImplicitProperty())
14850       return;
14851     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14852     if (!PD)
14853       return;
14854 
14855     unsigned Attributes = PD->getPropertyAttributes();
14856     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14857       // when 'assign' attribute was not explicitly specified
14858       // by user, ignore it and rely on property type itself
14859       // for lifetime info.
14860       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14861       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14862           LHSType->isObjCRetainableType())
14863         return;
14864 
14865       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14866         if (cast->getCastKind() == CK_ARCConsumeObject) {
14867           Diag(Loc, diag::warn_arc_retained_property_assign)
14868           << RHS->getSourceRange();
14869           return;
14870         }
14871         RHS = cast->getSubExpr();
14872       }
14873     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14874       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14875         return;
14876     }
14877   }
14878 }
14879 
14880 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14881 
14882 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14883                                         SourceLocation StmtLoc,
14884                                         const NullStmt *Body) {
14885   // Do not warn if the body is a macro that expands to nothing, e.g:
14886   //
14887   // #define CALL(x)
14888   // if (condition)
14889   //   CALL(0);
14890   if (Body->hasLeadingEmptyMacro())
14891     return false;
14892 
14893   // Get line numbers of statement and body.
14894   bool StmtLineInvalid;
14895   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14896                                                       &StmtLineInvalid);
14897   if (StmtLineInvalid)
14898     return false;
14899 
14900   bool BodyLineInvalid;
14901   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14902                                                       &BodyLineInvalid);
14903   if (BodyLineInvalid)
14904     return false;
14905 
14906   // Warn if null statement and body are on the same line.
14907   if (StmtLine != BodyLine)
14908     return false;
14909 
14910   return true;
14911 }
14912 
14913 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14914                                  const Stmt *Body,
14915                                  unsigned DiagID) {
14916   // Since this is a syntactic check, don't emit diagnostic for template
14917   // instantiations, this just adds noise.
14918   if (CurrentInstantiationScope)
14919     return;
14920 
14921   // The body should be a null statement.
14922   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14923   if (!NBody)
14924     return;
14925 
14926   // Do the usual checks.
14927   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14928     return;
14929 
14930   Diag(NBody->getSemiLoc(), DiagID);
14931   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14932 }
14933 
14934 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14935                                  const Stmt *PossibleBody) {
14936   assert(!CurrentInstantiationScope); // Ensured by caller
14937 
14938   SourceLocation StmtLoc;
14939   const Stmt *Body;
14940   unsigned DiagID;
14941   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14942     StmtLoc = FS->getRParenLoc();
14943     Body = FS->getBody();
14944     DiagID = diag::warn_empty_for_body;
14945   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14946     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14947     Body = WS->getBody();
14948     DiagID = diag::warn_empty_while_body;
14949   } else
14950     return; // Neither `for' nor `while'.
14951 
14952   // The body should be a null statement.
14953   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14954   if (!NBody)
14955     return;
14956 
14957   // Skip expensive checks if diagnostic is disabled.
14958   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14959     return;
14960 
14961   // Do the usual checks.
14962   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14963     return;
14964 
14965   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14966   // noise level low, emit diagnostics only if for/while is followed by a
14967   // CompoundStmt, e.g.:
14968   //    for (int i = 0; i < n; i++);
14969   //    {
14970   //      a(i);
14971   //    }
14972   // or if for/while is followed by a statement with more indentation
14973   // than for/while itself:
14974   //    for (int i = 0; i < n; i++);
14975   //      a(i);
14976   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14977   if (!ProbableTypo) {
14978     bool BodyColInvalid;
14979     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14980         PossibleBody->getBeginLoc(), &BodyColInvalid);
14981     if (BodyColInvalid)
14982       return;
14983 
14984     bool StmtColInvalid;
14985     unsigned StmtCol =
14986         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14987     if (StmtColInvalid)
14988       return;
14989 
14990     if (BodyCol > StmtCol)
14991       ProbableTypo = true;
14992   }
14993 
14994   if (ProbableTypo) {
14995     Diag(NBody->getSemiLoc(), DiagID);
14996     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14997   }
14998 }
14999 
15000 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15001 
15002 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15003 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15004                              SourceLocation OpLoc) {
15005   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15006     return;
15007 
15008   if (inTemplateInstantiation())
15009     return;
15010 
15011   // Strip parens and casts away.
15012   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15013   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15014 
15015   // Check for a call expression
15016   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15017   if (!CE || CE->getNumArgs() != 1)
15018     return;
15019 
15020   // Check for a call to std::move
15021   if (!CE->isCallToStdMove())
15022     return;
15023 
15024   // Get argument from std::move
15025   RHSExpr = CE->getArg(0);
15026 
15027   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15028   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15029 
15030   // Two DeclRefExpr's, check that the decls are the same.
15031   if (LHSDeclRef && RHSDeclRef) {
15032     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15033       return;
15034     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15035         RHSDeclRef->getDecl()->getCanonicalDecl())
15036       return;
15037 
15038     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15039                                         << LHSExpr->getSourceRange()
15040                                         << RHSExpr->getSourceRange();
15041     return;
15042   }
15043 
15044   // Member variables require a different approach to check for self moves.
15045   // MemberExpr's are the same if every nested MemberExpr refers to the same
15046   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15047   // the base Expr's are CXXThisExpr's.
15048   const Expr *LHSBase = LHSExpr;
15049   const Expr *RHSBase = RHSExpr;
15050   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15051   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15052   if (!LHSME || !RHSME)
15053     return;
15054 
15055   while (LHSME && RHSME) {
15056     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15057         RHSME->getMemberDecl()->getCanonicalDecl())
15058       return;
15059 
15060     LHSBase = LHSME->getBase();
15061     RHSBase = RHSME->getBase();
15062     LHSME = dyn_cast<MemberExpr>(LHSBase);
15063     RHSME = dyn_cast<MemberExpr>(RHSBase);
15064   }
15065 
15066   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15067   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15068   if (LHSDeclRef && RHSDeclRef) {
15069     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15070       return;
15071     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15072         RHSDeclRef->getDecl()->getCanonicalDecl())
15073       return;
15074 
15075     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15076                                         << LHSExpr->getSourceRange()
15077                                         << RHSExpr->getSourceRange();
15078     return;
15079   }
15080 
15081   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15082     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15083                                         << LHSExpr->getSourceRange()
15084                                         << RHSExpr->getSourceRange();
15085 }
15086 
15087 //===--- Layout compatibility ----------------------------------------------//
15088 
15089 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15090 
15091 /// Check if two enumeration types are layout-compatible.
15092 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15093   // C++11 [dcl.enum] p8:
15094   // Two enumeration types are layout-compatible if they have the same
15095   // underlying type.
15096   return ED1->isComplete() && ED2->isComplete() &&
15097          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15098 }
15099 
15100 /// Check if two fields are layout-compatible.
15101 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15102                                FieldDecl *Field2) {
15103   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15104     return false;
15105 
15106   if (Field1->isBitField() != Field2->isBitField())
15107     return false;
15108 
15109   if (Field1->isBitField()) {
15110     // Make sure that the bit-fields are the same length.
15111     unsigned Bits1 = Field1->getBitWidthValue(C);
15112     unsigned Bits2 = Field2->getBitWidthValue(C);
15113 
15114     if (Bits1 != Bits2)
15115       return false;
15116   }
15117 
15118   return true;
15119 }
15120 
15121 /// Check if two standard-layout structs are layout-compatible.
15122 /// (C++11 [class.mem] p17)
15123 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15124                                      RecordDecl *RD2) {
15125   // If both records are C++ classes, check that base classes match.
15126   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15127     // If one of records is a CXXRecordDecl we are in C++ mode,
15128     // thus the other one is a CXXRecordDecl, too.
15129     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15130     // Check number of base classes.
15131     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15132       return false;
15133 
15134     // Check the base classes.
15135     for (CXXRecordDecl::base_class_const_iterator
15136                Base1 = D1CXX->bases_begin(),
15137            BaseEnd1 = D1CXX->bases_end(),
15138               Base2 = D2CXX->bases_begin();
15139          Base1 != BaseEnd1;
15140          ++Base1, ++Base2) {
15141       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15142         return false;
15143     }
15144   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15145     // If only RD2 is a C++ class, it should have zero base classes.
15146     if (D2CXX->getNumBases() > 0)
15147       return false;
15148   }
15149 
15150   // Check the fields.
15151   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15152                              Field2End = RD2->field_end(),
15153                              Field1 = RD1->field_begin(),
15154                              Field1End = RD1->field_end();
15155   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15156     if (!isLayoutCompatible(C, *Field1, *Field2))
15157       return false;
15158   }
15159   if (Field1 != Field1End || Field2 != Field2End)
15160     return false;
15161 
15162   return true;
15163 }
15164 
15165 /// Check if two standard-layout unions are layout-compatible.
15166 /// (C++11 [class.mem] p18)
15167 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15168                                     RecordDecl *RD2) {
15169   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15170   for (auto *Field2 : RD2->fields())
15171     UnmatchedFields.insert(Field2);
15172 
15173   for (auto *Field1 : RD1->fields()) {
15174     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15175         I = UnmatchedFields.begin(),
15176         E = UnmatchedFields.end();
15177 
15178     for ( ; I != E; ++I) {
15179       if (isLayoutCompatible(C, Field1, *I)) {
15180         bool Result = UnmatchedFields.erase(*I);
15181         (void) Result;
15182         assert(Result);
15183         break;
15184       }
15185     }
15186     if (I == E)
15187       return false;
15188   }
15189 
15190   return UnmatchedFields.empty();
15191 }
15192 
15193 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15194                                RecordDecl *RD2) {
15195   if (RD1->isUnion() != RD2->isUnion())
15196     return false;
15197 
15198   if (RD1->isUnion())
15199     return isLayoutCompatibleUnion(C, RD1, RD2);
15200   else
15201     return isLayoutCompatibleStruct(C, RD1, RD2);
15202 }
15203 
15204 /// Check if two types are layout-compatible in C++11 sense.
15205 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15206   if (T1.isNull() || T2.isNull())
15207     return false;
15208 
15209   // C++11 [basic.types] p11:
15210   // If two types T1 and T2 are the same type, then T1 and T2 are
15211   // layout-compatible types.
15212   if (C.hasSameType(T1, T2))
15213     return true;
15214 
15215   T1 = T1.getCanonicalType().getUnqualifiedType();
15216   T2 = T2.getCanonicalType().getUnqualifiedType();
15217 
15218   const Type::TypeClass TC1 = T1->getTypeClass();
15219   const Type::TypeClass TC2 = T2->getTypeClass();
15220 
15221   if (TC1 != TC2)
15222     return false;
15223 
15224   if (TC1 == Type::Enum) {
15225     return isLayoutCompatible(C,
15226                               cast<EnumType>(T1)->getDecl(),
15227                               cast<EnumType>(T2)->getDecl());
15228   } else if (TC1 == Type::Record) {
15229     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15230       return false;
15231 
15232     return isLayoutCompatible(C,
15233                               cast<RecordType>(T1)->getDecl(),
15234                               cast<RecordType>(T2)->getDecl());
15235   }
15236 
15237   return false;
15238 }
15239 
15240 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15241 
15242 /// Given a type tag expression find the type tag itself.
15243 ///
15244 /// \param TypeExpr Type tag expression, as it appears in user's code.
15245 ///
15246 /// \param VD Declaration of an identifier that appears in a type tag.
15247 ///
15248 /// \param MagicValue Type tag magic value.
15249 ///
15250 /// \param isConstantEvaluated wether the evalaution should be performed in
15251 
15252 /// constant context.
15253 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15254                             const ValueDecl **VD, uint64_t *MagicValue,
15255                             bool isConstantEvaluated) {
15256   while(true) {
15257     if (!TypeExpr)
15258       return false;
15259 
15260     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15261 
15262     switch (TypeExpr->getStmtClass()) {
15263     case Stmt::UnaryOperatorClass: {
15264       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15265       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15266         TypeExpr = UO->getSubExpr();
15267         continue;
15268       }
15269       return false;
15270     }
15271 
15272     case Stmt::DeclRefExprClass: {
15273       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15274       *VD = DRE->getDecl();
15275       return true;
15276     }
15277 
15278     case Stmt::IntegerLiteralClass: {
15279       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15280       llvm::APInt MagicValueAPInt = IL->getValue();
15281       if (MagicValueAPInt.getActiveBits() <= 64) {
15282         *MagicValue = MagicValueAPInt.getZExtValue();
15283         return true;
15284       } else
15285         return false;
15286     }
15287 
15288     case Stmt::BinaryConditionalOperatorClass:
15289     case Stmt::ConditionalOperatorClass: {
15290       const AbstractConditionalOperator *ACO =
15291           cast<AbstractConditionalOperator>(TypeExpr);
15292       bool Result;
15293       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15294                                                      isConstantEvaluated)) {
15295         if (Result)
15296           TypeExpr = ACO->getTrueExpr();
15297         else
15298           TypeExpr = ACO->getFalseExpr();
15299         continue;
15300       }
15301       return false;
15302     }
15303 
15304     case Stmt::BinaryOperatorClass: {
15305       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15306       if (BO->getOpcode() == BO_Comma) {
15307         TypeExpr = BO->getRHS();
15308         continue;
15309       }
15310       return false;
15311     }
15312 
15313     default:
15314       return false;
15315     }
15316   }
15317 }
15318 
15319 /// Retrieve the C type corresponding to type tag TypeExpr.
15320 ///
15321 /// \param TypeExpr Expression that specifies a type tag.
15322 ///
15323 /// \param MagicValues Registered magic values.
15324 ///
15325 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15326 ///        kind.
15327 ///
15328 /// \param TypeInfo Information about the corresponding C type.
15329 ///
15330 /// \param isConstantEvaluated wether the evalaution should be performed in
15331 /// constant context.
15332 ///
15333 /// \returns true if the corresponding C type was found.
15334 static bool GetMatchingCType(
15335     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15336     const ASTContext &Ctx,
15337     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15338         *MagicValues,
15339     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15340     bool isConstantEvaluated) {
15341   FoundWrongKind = false;
15342 
15343   // Variable declaration that has type_tag_for_datatype attribute.
15344   const ValueDecl *VD = nullptr;
15345 
15346   uint64_t MagicValue;
15347 
15348   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15349     return false;
15350 
15351   if (VD) {
15352     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15353       if (I->getArgumentKind() != ArgumentKind) {
15354         FoundWrongKind = true;
15355         return false;
15356       }
15357       TypeInfo.Type = I->getMatchingCType();
15358       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15359       TypeInfo.MustBeNull = I->getMustBeNull();
15360       return true;
15361     }
15362     return false;
15363   }
15364 
15365   if (!MagicValues)
15366     return false;
15367 
15368   llvm::DenseMap<Sema::TypeTagMagicValue,
15369                  Sema::TypeTagData>::const_iterator I =
15370       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15371   if (I == MagicValues->end())
15372     return false;
15373 
15374   TypeInfo = I->second;
15375   return true;
15376 }
15377 
15378 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15379                                       uint64_t MagicValue, QualType Type,
15380                                       bool LayoutCompatible,
15381                                       bool MustBeNull) {
15382   if (!TypeTagForDatatypeMagicValues)
15383     TypeTagForDatatypeMagicValues.reset(
15384         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15385 
15386   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15387   (*TypeTagForDatatypeMagicValues)[Magic] =
15388       TypeTagData(Type, LayoutCompatible, MustBeNull);
15389 }
15390 
15391 static bool IsSameCharType(QualType T1, QualType T2) {
15392   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15393   if (!BT1)
15394     return false;
15395 
15396   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15397   if (!BT2)
15398     return false;
15399 
15400   BuiltinType::Kind T1Kind = BT1->getKind();
15401   BuiltinType::Kind T2Kind = BT2->getKind();
15402 
15403   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15404          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15405          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15406          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15407 }
15408 
15409 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15410                                     const ArrayRef<const Expr *> ExprArgs,
15411                                     SourceLocation CallSiteLoc) {
15412   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15413   bool IsPointerAttr = Attr->getIsPointer();
15414 
15415   // Retrieve the argument representing the 'type_tag'.
15416   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15417   if (TypeTagIdxAST >= ExprArgs.size()) {
15418     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15419         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15420     return;
15421   }
15422   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15423   bool FoundWrongKind;
15424   TypeTagData TypeInfo;
15425   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15426                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15427                         TypeInfo, isConstantEvaluated())) {
15428     if (FoundWrongKind)
15429       Diag(TypeTagExpr->getExprLoc(),
15430            diag::warn_type_tag_for_datatype_wrong_kind)
15431         << TypeTagExpr->getSourceRange();
15432     return;
15433   }
15434 
15435   // Retrieve the argument representing the 'arg_idx'.
15436   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15437   if (ArgumentIdxAST >= ExprArgs.size()) {
15438     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15439         << 1 << Attr->getArgumentIdx().getSourceIndex();
15440     return;
15441   }
15442   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15443   if (IsPointerAttr) {
15444     // Skip implicit cast of pointer to `void *' (as a function argument).
15445     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15446       if (ICE->getType()->isVoidPointerType() &&
15447           ICE->getCastKind() == CK_BitCast)
15448         ArgumentExpr = ICE->getSubExpr();
15449   }
15450   QualType ArgumentType = ArgumentExpr->getType();
15451 
15452   // Passing a `void*' pointer shouldn't trigger a warning.
15453   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15454     return;
15455 
15456   if (TypeInfo.MustBeNull) {
15457     // Type tag with matching void type requires a null pointer.
15458     if (!ArgumentExpr->isNullPointerConstant(Context,
15459                                              Expr::NPC_ValueDependentIsNotNull)) {
15460       Diag(ArgumentExpr->getExprLoc(),
15461            diag::warn_type_safety_null_pointer_required)
15462           << ArgumentKind->getName()
15463           << ArgumentExpr->getSourceRange()
15464           << TypeTagExpr->getSourceRange();
15465     }
15466     return;
15467   }
15468 
15469   QualType RequiredType = TypeInfo.Type;
15470   if (IsPointerAttr)
15471     RequiredType = Context.getPointerType(RequiredType);
15472 
15473   bool mismatch = false;
15474   if (!TypeInfo.LayoutCompatible) {
15475     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15476 
15477     // C++11 [basic.fundamental] p1:
15478     // Plain char, signed char, and unsigned char are three distinct types.
15479     //
15480     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15481     // char' depending on the current char signedness mode.
15482     if (mismatch)
15483       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15484                                            RequiredType->getPointeeType())) ||
15485           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15486         mismatch = false;
15487   } else
15488     if (IsPointerAttr)
15489       mismatch = !isLayoutCompatible(Context,
15490                                      ArgumentType->getPointeeType(),
15491                                      RequiredType->getPointeeType());
15492     else
15493       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15494 
15495   if (mismatch)
15496     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15497         << ArgumentType << ArgumentKind
15498         << TypeInfo.LayoutCompatible << RequiredType
15499         << ArgumentExpr->getSourceRange()
15500         << TypeTagExpr->getSourceRange();
15501 }
15502 
15503 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15504                                          CharUnits Alignment) {
15505   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15506 }
15507 
15508 void Sema::DiagnoseMisalignedMembers() {
15509   for (MisalignedMember &m : MisalignedMembers) {
15510     const NamedDecl *ND = m.RD;
15511     if (ND->getName().empty()) {
15512       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15513         ND = TD;
15514     }
15515     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15516         << m.MD << ND << m.E->getSourceRange();
15517   }
15518   MisalignedMembers.clear();
15519 }
15520 
15521 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15522   E = E->IgnoreParens();
15523   if (!T->isPointerType() && !T->isIntegerType())
15524     return;
15525   if (isa<UnaryOperator>(E) &&
15526       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15527     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15528     if (isa<MemberExpr>(Op)) {
15529       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15530       if (MA != MisalignedMembers.end() &&
15531           (T->isIntegerType() ||
15532            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15533                                    Context.getTypeAlignInChars(
15534                                        T->getPointeeType()) <= MA->Alignment))))
15535         MisalignedMembers.erase(MA);
15536     }
15537   }
15538 }
15539 
15540 void Sema::RefersToMemberWithReducedAlignment(
15541     Expr *E,
15542     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15543         Action) {
15544   const auto *ME = dyn_cast<MemberExpr>(E);
15545   if (!ME)
15546     return;
15547 
15548   // No need to check expressions with an __unaligned-qualified type.
15549   if (E->getType().getQualifiers().hasUnaligned())
15550     return;
15551 
15552   // For a chain of MemberExpr like "a.b.c.d" this list
15553   // will keep FieldDecl's like [d, c, b].
15554   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15555   const MemberExpr *TopME = nullptr;
15556   bool AnyIsPacked = false;
15557   do {
15558     QualType BaseType = ME->getBase()->getType();
15559     if (BaseType->isDependentType())
15560       return;
15561     if (ME->isArrow())
15562       BaseType = BaseType->getPointeeType();
15563     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15564     if (RD->isInvalidDecl())
15565       return;
15566 
15567     ValueDecl *MD = ME->getMemberDecl();
15568     auto *FD = dyn_cast<FieldDecl>(MD);
15569     // We do not care about non-data members.
15570     if (!FD || FD->isInvalidDecl())
15571       return;
15572 
15573     AnyIsPacked =
15574         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15575     ReverseMemberChain.push_back(FD);
15576 
15577     TopME = ME;
15578     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15579   } while (ME);
15580   assert(TopME && "We did not compute a topmost MemberExpr!");
15581 
15582   // Not the scope of this diagnostic.
15583   if (!AnyIsPacked)
15584     return;
15585 
15586   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15587   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15588   // TODO: The innermost base of the member expression may be too complicated.
15589   // For now, just disregard these cases. This is left for future
15590   // improvement.
15591   if (!DRE && !isa<CXXThisExpr>(TopBase))
15592       return;
15593 
15594   // Alignment expected by the whole expression.
15595   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15596 
15597   // No need to do anything else with this case.
15598   if (ExpectedAlignment.isOne())
15599     return;
15600 
15601   // Synthesize offset of the whole access.
15602   CharUnits Offset;
15603   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15604        I++) {
15605     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15606   }
15607 
15608   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15609   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15610       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15611 
15612   // The base expression of the innermost MemberExpr may give
15613   // stronger guarantees than the class containing the member.
15614   if (DRE && !TopME->isArrow()) {
15615     const ValueDecl *VD = DRE->getDecl();
15616     if (!VD->getType()->isReferenceType())
15617       CompleteObjectAlignment =
15618           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15619   }
15620 
15621   // Check if the synthesized offset fulfills the alignment.
15622   if (Offset % ExpectedAlignment != 0 ||
15623       // It may fulfill the offset it but the effective alignment may still be
15624       // lower than the expected expression alignment.
15625       CompleteObjectAlignment < ExpectedAlignment) {
15626     // If this happens, we want to determine a sensible culprit of this.
15627     // Intuitively, watching the chain of member expressions from right to
15628     // left, we start with the required alignment (as required by the field
15629     // type) but some packed attribute in that chain has reduced the alignment.
15630     // It may happen that another packed structure increases it again. But if
15631     // we are here such increase has not been enough. So pointing the first
15632     // FieldDecl that either is packed or else its RecordDecl is,
15633     // seems reasonable.
15634     FieldDecl *FD = nullptr;
15635     CharUnits Alignment;
15636     for (FieldDecl *FDI : ReverseMemberChain) {
15637       if (FDI->hasAttr<PackedAttr>() ||
15638           FDI->getParent()->hasAttr<PackedAttr>()) {
15639         FD = FDI;
15640         Alignment = std::min(
15641             Context.getTypeAlignInChars(FD->getType()),
15642             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15643         break;
15644       }
15645     }
15646     assert(FD && "We did not find a packed FieldDecl!");
15647     Action(E, FD->getParent(), FD, Alignment);
15648   }
15649 }
15650 
15651 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15652   using namespace std::placeholders;
15653 
15654   RefersToMemberWithReducedAlignment(
15655       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15656                      _2, _3, _4));
15657 }
15658 
15659 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15660                                             ExprResult CallResult) {
15661   if (checkArgCount(*this, TheCall, 1))
15662     return ExprError();
15663 
15664   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15665   if (MatrixArg.isInvalid())
15666     return MatrixArg;
15667   Expr *Matrix = MatrixArg.get();
15668 
15669   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15670   if (!MType) {
15671     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15672     return ExprError();
15673   }
15674 
15675   // Create returned matrix type by swapping rows and columns of the argument
15676   // matrix type.
15677   QualType ResultType = Context.getConstantMatrixType(
15678       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15679 
15680   // Change the return type to the type of the returned matrix.
15681   TheCall->setType(ResultType);
15682 
15683   // Update call argument to use the possibly converted matrix argument.
15684   TheCall->setArg(0, Matrix);
15685   return CallResult;
15686 }
15687 
15688 // Get and verify the matrix dimensions.
15689 static llvm::Optional<unsigned>
15690 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15691   SourceLocation ErrorPos;
15692   Optional<llvm::APSInt> Value =
15693       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15694   if (!Value) {
15695     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15696         << Name;
15697     return {};
15698   }
15699   uint64_t Dim = Value->getZExtValue();
15700   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15701     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15702         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15703     return {};
15704   }
15705   return Dim;
15706 }
15707 
15708 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15709                                                   ExprResult CallResult) {
15710   if (!getLangOpts().MatrixTypes) {
15711     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15712     return ExprError();
15713   }
15714 
15715   if (checkArgCount(*this, TheCall, 4))
15716     return ExprError();
15717 
15718   unsigned PtrArgIdx = 0;
15719   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15720   Expr *RowsExpr = TheCall->getArg(1);
15721   Expr *ColumnsExpr = TheCall->getArg(2);
15722   Expr *StrideExpr = TheCall->getArg(3);
15723 
15724   bool ArgError = false;
15725 
15726   // Check pointer argument.
15727   {
15728     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15729     if (PtrConv.isInvalid())
15730       return PtrConv;
15731     PtrExpr = PtrConv.get();
15732     TheCall->setArg(0, PtrExpr);
15733     if (PtrExpr->isTypeDependent()) {
15734       TheCall->setType(Context.DependentTy);
15735       return TheCall;
15736     }
15737   }
15738 
15739   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15740   QualType ElementTy;
15741   if (!PtrTy) {
15742     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15743         << PtrArgIdx + 1;
15744     ArgError = true;
15745   } else {
15746     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15747 
15748     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15749       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15750           << PtrArgIdx + 1;
15751       ArgError = true;
15752     }
15753   }
15754 
15755   // Apply default Lvalue conversions and convert the expression to size_t.
15756   auto ApplyArgumentConversions = [this](Expr *E) {
15757     ExprResult Conv = DefaultLvalueConversion(E);
15758     if (Conv.isInvalid())
15759       return Conv;
15760 
15761     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15762   };
15763 
15764   // Apply conversion to row and column expressions.
15765   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15766   if (!RowsConv.isInvalid()) {
15767     RowsExpr = RowsConv.get();
15768     TheCall->setArg(1, RowsExpr);
15769   } else
15770     RowsExpr = nullptr;
15771 
15772   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15773   if (!ColumnsConv.isInvalid()) {
15774     ColumnsExpr = ColumnsConv.get();
15775     TheCall->setArg(2, ColumnsExpr);
15776   } else
15777     ColumnsExpr = nullptr;
15778 
15779   // If any any part of the result matrix type is still pending, just use
15780   // Context.DependentTy, until all parts are resolved.
15781   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15782       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15783     TheCall->setType(Context.DependentTy);
15784     return CallResult;
15785   }
15786 
15787   // Check row and column dimenions.
15788   llvm::Optional<unsigned> MaybeRows;
15789   if (RowsExpr)
15790     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15791 
15792   llvm::Optional<unsigned> MaybeColumns;
15793   if (ColumnsExpr)
15794     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15795 
15796   // Check stride argument.
15797   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15798   if (StrideConv.isInvalid())
15799     return ExprError();
15800   StrideExpr = StrideConv.get();
15801   TheCall->setArg(3, StrideExpr);
15802 
15803   if (MaybeRows) {
15804     if (Optional<llvm::APSInt> Value =
15805             StrideExpr->getIntegerConstantExpr(Context)) {
15806       uint64_t Stride = Value->getZExtValue();
15807       if (Stride < *MaybeRows) {
15808         Diag(StrideExpr->getBeginLoc(),
15809              diag::err_builtin_matrix_stride_too_small);
15810         ArgError = true;
15811       }
15812     }
15813   }
15814 
15815   if (ArgError || !MaybeRows || !MaybeColumns)
15816     return ExprError();
15817 
15818   TheCall->setType(
15819       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15820   return CallResult;
15821 }
15822 
15823 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15824                                                    ExprResult CallResult) {
15825   if (checkArgCount(*this, TheCall, 3))
15826     return ExprError();
15827 
15828   unsigned PtrArgIdx = 1;
15829   Expr *MatrixExpr = TheCall->getArg(0);
15830   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15831   Expr *StrideExpr = TheCall->getArg(2);
15832 
15833   bool ArgError = false;
15834 
15835   {
15836     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15837     if (MatrixConv.isInvalid())
15838       return MatrixConv;
15839     MatrixExpr = MatrixConv.get();
15840     TheCall->setArg(0, MatrixExpr);
15841   }
15842   if (MatrixExpr->isTypeDependent()) {
15843     TheCall->setType(Context.DependentTy);
15844     return TheCall;
15845   }
15846 
15847   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15848   if (!MatrixTy) {
15849     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15850     ArgError = true;
15851   }
15852 
15853   {
15854     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15855     if (PtrConv.isInvalid())
15856       return PtrConv;
15857     PtrExpr = PtrConv.get();
15858     TheCall->setArg(1, PtrExpr);
15859     if (PtrExpr->isTypeDependent()) {
15860       TheCall->setType(Context.DependentTy);
15861       return TheCall;
15862     }
15863   }
15864 
15865   // Check pointer argument.
15866   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15867   if (!PtrTy) {
15868     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15869         << PtrArgIdx + 1;
15870     ArgError = true;
15871   } else {
15872     QualType ElementTy = PtrTy->getPointeeType();
15873     if (ElementTy.isConstQualified()) {
15874       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15875       ArgError = true;
15876     }
15877     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15878     if (MatrixTy &&
15879         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15880       Diag(PtrExpr->getBeginLoc(),
15881            diag::err_builtin_matrix_pointer_arg_mismatch)
15882           << ElementTy << MatrixTy->getElementType();
15883       ArgError = true;
15884     }
15885   }
15886 
15887   // Apply default Lvalue conversions and convert the stride expression to
15888   // size_t.
15889   {
15890     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15891     if (StrideConv.isInvalid())
15892       return StrideConv;
15893 
15894     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15895     if (StrideConv.isInvalid())
15896       return StrideConv;
15897     StrideExpr = StrideConv.get();
15898     TheCall->setArg(2, StrideExpr);
15899   }
15900 
15901   // Check stride argument.
15902   if (MatrixTy) {
15903     if (Optional<llvm::APSInt> Value =
15904             StrideExpr->getIntegerConstantExpr(Context)) {
15905       uint64_t Stride = Value->getZExtValue();
15906       if (Stride < MatrixTy->getNumRows()) {
15907         Diag(StrideExpr->getBeginLoc(),
15908              diag::err_builtin_matrix_stride_too_small);
15909         ArgError = true;
15910       }
15911     }
15912   }
15913 
15914   if (ArgError)
15915     return ExprError();
15916 
15917   return CallResult;
15918 }
15919