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 CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10111                                  const UnaryOperator *UnaryExpr) {
10112   if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
10113     return;
10114 
10115   const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr());
10116   if (Lvalue == nullptr)
10117     return;
10118 
10119   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10120   if (Var == nullptr)
10121     return;
10122 
10123   StorageClass Class = Var->getStorageClass();
10124   if (Class == StorageClass::SC_Extern ||
10125       Class == StorageClass::SC_PrivateExtern ||
10126       Var->getType()->isReferenceType())
10127     return;
10128 
10129   S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10130       << CalleeName << Var;
10131 }
10132 
10133 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10134                                   const DeclRefExpr *Lvalue) {
10135   if (!Lvalue->getType()->isArrayType())
10136     return;
10137 
10138   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10139   if (Var == nullptr)
10140     return;
10141 
10142   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10143       << CalleeName << Var;
10144 }
10145 } // namespace
10146 
10147 /// Alerts the user that they are attempting to free a non-malloc'd object.
10148 void Sema::CheckFreeArguments(const CallExpr *E) {
10149   const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10150   const std::string CalleeName =
10151       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10152 
10153   if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10154     return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10155 
10156   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10157     return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10158 }
10159 
10160 void
10161 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10162                          SourceLocation ReturnLoc,
10163                          bool isObjCMethod,
10164                          const AttrVec *Attrs,
10165                          const FunctionDecl *FD) {
10166   // Check if the return value is null but should not be.
10167   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10168        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10169       CheckNonNullExpr(*this, RetValExp))
10170     Diag(ReturnLoc, diag::warn_null_ret)
10171       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10172 
10173   // C++11 [basic.stc.dynamic.allocation]p4:
10174   //   If an allocation function declared with a non-throwing
10175   //   exception-specification fails to allocate storage, it shall return
10176   //   a null pointer. Any other allocation function that fails to allocate
10177   //   storage shall indicate failure only by throwing an exception [...]
10178   if (FD) {
10179     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10180     if (Op == OO_New || Op == OO_Array_New) {
10181       const FunctionProtoType *Proto
10182         = FD->getType()->castAs<FunctionProtoType>();
10183       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10184           CheckNonNullExpr(*this, RetValExp))
10185         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10186           << FD << getLangOpts().CPlusPlus11;
10187     }
10188   }
10189 }
10190 
10191 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10192 
10193 /// Check for comparisons of floating point operands using != and ==.
10194 /// Issue a warning if these are no self-comparisons, as they are not likely
10195 /// to do what the programmer intended.
10196 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10197   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10198   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10199 
10200   // Special case: check for x == x (which is OK).
10201   // Do not emit warnings for such cases.
10202   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10203     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10204       if (DRL->getDecl() == DRR->getDecl())
10205         return;
10206 
10207   // Special case: check for comparisons against literals that can be exactly
10208   //  represented by APFloat.  In such cases, do not emit a warning.  This
10209   //  is a heuristic: often comparison against such literals are used to
10210   //  detect if a value in a variable has not changed.  This clearly can
10211   //  lead to false negatives.
10212   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10213     if (FLL->isExact())
10214       return;
10215   } else
10216     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10217       if (FLR->isExact())
10218         return;
10219 
10220   // Check for comparisons with builtin types.
10221   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10222     if (CL->getBuiltinCallee())
10223       return;
10224 
10225   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10226     if (CR->getBuiltinCallee())
10227       return;
10228 
10229   // Emit the diagnostic.
10230   Diag(Loc, diag::warn_floatingpoint_eq)
10231     << LHS->getSourceRange() << RHS->getSourceRange();
10232 }
10233 
10234 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10235 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10236 
10237 namespace {
10238 
10239 /// Structure recording the 'active' range of an integer-valued
10240 /// expression.
10241 struct IntRange {
10242   /// The number of bits active in the int. Note that this includes exactly one
10243   /// sign bit if !NonNegative.
10244   unsigned Width;
10245 
10246   /// True if the int is known not to have negative values. If so, all leading
10247   /// bits before Width are known zero, otherwise they are known to be the
10248   /// same as the MSB within Width.
10249   bool NonNegative;
10250 
10251   IntRange(unsigned Width, bool NonNegative)
10252       : Width(Width), NonNegative(NonNegative) {}
10253 
10254   /// Number of bits excluding the sign bit.
10255   unsigned valueBits() const {
10256     return NonNegative ? Width : Width - 1;
10257   }
10258 
10259   /// Returns the range of the bool type.
10260   static IntRange forBoolType() {
10261     return IntRange(1, true);
10262   }
10263 
10264   /// Returns the range of an opaque value of the given integral type.
10265   static IntRange forValueOfType(ASTContext &C, QualType T) {
10266     return forValueOfCanonicalType(C,
10267                           T->getCanonicalTypeInternal().getTypePtr());
10268   }
10269 
10270   /// Returns the range of an opaque value of a canonical integral type.
10271   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10272     assert(T->isCanonicalUnqualified());
10273 
10274     if (const VectorType *VT = dyn_cast<VectorType>(T))
10275       T = VT->getElementType().getTypePtr();
10276     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10277       T = CT->getElementType().getTypePtr();
10278     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10279       T = AT->getValueType().getTypePtr();
10280 
10281     if (!C.getLangOpts().CPlusPlus) {
10282       // For enum types in C code, use the underlying datatype.
10283       if (const EnumType *ET = dyn_cast<EnumType>(T))
10284         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10285     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10286       // For enum types in C++, use the known bit width of the enumerators.
10287       EnumDecl *Enum = ET->getDecl();
10288       // In C++11, enums can have a fixed underlying type. Use this type to
10289       // compute the range.
10290       if (Enum->isFixed()) {
10291         return IntRange(C.getIntWidth(QualType(T, 0)),
10292                         !ET->isSignedIntegerOrEnumerationType());
10293       }
10294 
10295       unsigned NumPositive = Enum->getNumPositiveBits();
10296       unsigned NumNegative = Enum->getNumNegativeBits();
10297 
10298       if (NumNegative == 0)
10299         return IntRange(NumPositive, true/*NonNegative*/);
10300       else
10301         return IntRange(std::max(NumPositive + 1, NumNegative),
10302                         false/*NonNegative*/);
10303     }
10304 
10305     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10306       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10307 
10308     const BuiltinType *BT = cast<BuiltinType>(T);
10309     assert(BT->isInteger());
10310 
10311     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10312   }
10313 
10314   /// Returns the "target" range of a canonical integral type, i.e.
10315   /// the range of values expressible in the type.
10316   ///
10317   /// This matches forValueOfCanonicalType except that enums have the
10318   /// full range of their type, not the range of their enumerators.
10319   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10320     assert(T->isCanonicalUnqualified());
10321 
10322     if (const VectorType *VT = dyn_cast<VectorType>(T))
10323       T = VT->getElementType().getTypePtr();
10324     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10325       T = CT->getElementType().getTypePtr();
10326     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10327       T = AT->getValueType().getTypePtr();
10328     if (const EnumType *ET = dyn_cast<EnumType>(T))
10329       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10330 
10331     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10332       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10333 
10334     const BuiltinType *BT = cast<BuiltinType>(T);
10335     assert(BT->isInteger());
10336 
10337     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10338   }
10339 
10340   /// Returns the supremum of two ranges: i.e. their conservative merge.
10341   static IntRange join(IntRange L, IntRange R) {
10342     bool Unsigned = L.NonNegative && R.NonNegative;
10343     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10344                     L.NonNegative && R.NonNegative);
10345   }
10346 
10347   /// Return the range of a bitwise-AND of the two ranges.
10348   static IntRange bit_and(IntRange L, IntRange R) {
10349     unsigned Bits = std::max(L.Width, R.Width);
10350     bool NonNegative = false;
10351     if (L.NonNegative) {
10352       Bits = std::min(Bits, L.Width);
10353       NonNegative = true;
10354     }
10355     if (R.NonNegative) {
10356       Bits = std::min(Bits, R.Width);
10357       NonNegative = true;
10358     }
10359     return IntRange(Bits, NonNegative);
10360   }
10361 
10362   /// Return the range of a sum of the two ranges.
10363   static IntRange sum(IntRange L, IntRange R) {
10364     bool Unsigned = L.NonNegative && R.NonNegative;
10365     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10366                     Unsigned);
10367   }
10368 
10369   /// Return the range of a difference of the two ranges.
10370   static IntRange difference(IntRange L, IntRange R) {
10371     // We need a 1-bit-wider range if:
10372     //   1) LHS can be negative: least value can be reduced.
10373     //   2) RHS can be negative: greatest value can be increased.
10374     bool CanWiden = !L.NonNegative || !R.NonNegative;
10375     bool Unsigned = L.NonNegative && R.Width == 0;
10376     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10377                         !Unsigned,
10378                     Unsigned);
10379   }
10380 
10381   /// Return the range of a product of the two ranges.
10382   static IntRange product(IntRange L, IntRange R) {
10383     // If both LHS and RHS can be negative, we can form
10384     //   -2^L * -2^R = 2^(L + R)
10385     // which requires L + R + 1 value bits to represent.
10386     bool CanWiden = !L.NonNegative && !R.NonNegative;
10387     bool Unsigned = L.NonNegative && R.NonNegative;
10388     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10389                     Unsigned);
10390   }
10391 
10392   /// Return the range of a remainder operation between the two ranges.
10393   static IntRange rem(IntRange L, IntRange R) {
10394     // The result of a remainder can't be larger than the result of
10395     // either side. The sign of the result is the sign of the LHS.
10396     bool Unsigned = L.NonNegative;
10397     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10398                     Unsigned);
10399   }
10400 };
10401 
10402 } // namespace
10403 
10404 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10405                               unsigned MaxWidth) {
10406   if (value.isSigned() && value.isNegative())
10407     return IntRange(value.getMinSignedBits(), false);
10408 
10409   if (value.getBitWidth() > MaxWidth)
10410     value = value.trunc(MaxWidth);
10411 
10412   // isNonNegative() just checks the sign bit without considering
10413   // signedness.
10414   return IntRange(value.getActiveBits(), true);
10415 }
10416 
10417 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10418                               unsigned MaxWidth) {
10419   if (result.isInt())
10420     return GetValueRange(C, result.getInt(), MaxWidth);
10421 
10422   if (result.isVector()) {
10423     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10424     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10425       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10426       R = IntRange::join(R, El);
10427     }
10428     return R;
10429   }
10430 
10431   if (result.isComplexInt()) {
10432     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10433     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10434     return IntRange::join(R, I);
10435   }
10436 
10437   // This can happen with lossless casts to intptr_t of "based" lvalues.
10438   // Assume it might use arbitrary bits.
10439   // FIXME: The only reason we need to pass the type in here is to get
10440   // the sign right on this one case.  It would be nice if APValue
10441   // preserved this.
10442   assert(result.isLValue() || result.isAddrLabelDiff());
10443   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10444 }
10445 
10446 static QualType GetExprType(const Expr *E) {
10447   QualType Ty = E->getType();
10448   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10449     Ty = AtomicRHS->getValueType();
10450   return Ty;
10451 }
10452 
10453 /// Pseudo-evaluate the given integer expression, estimating the
10454 /// range of values it might take.
10455 ///
10456 /// \param MaxWidth The width to which the value will be truncated.
10457 /// \param Approximate If \c true, return a likely range for the result: in
10458 ///        particular, assume that aritmetic on narrower types doesn't leave
10459 ///        those types. If \c false, return a range including all possible
10460 ///        result values.
10461 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10462                              bool InConstantContext, bool Approximate) {
10463   E = E->IgnoreParens();
10464 
10465   // Try a full evaluation first.
10466   Expr::EvalResult result;
10467   if (E->EvaluateAsRValue(result, C, InConstantContext))
10468     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10469 
10470   // I think we only want to look through implicit casts here; if the
10471   // user has an explicit widening cast, we should treat the value as
10472   // being of the new, wider type.
10473   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10474     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10475       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10476                           Approximate);
10477 
10478     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10479 
10480     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10481                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10482 
10483     // Assume that non-integer casts can span the full range of the type.
10484     if (!isIntegerCast)
10485       return OutputTypeRange;
10486 
10487     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10488                                      std::min(MaxWidth, OutputTypeRange.Width),
10489                                      InConstantContext, Approximate);
10490 
10491     // Bail out if the subexpr's range is as wide as the cast type.
10492     if (SubRange.Width >= OutputTypeRange.Width)
10493       return OutputTypeRange;
10494 
10495     // Otherwise, we take the smaller width, and we're non-negative if
10496     // either the output type or the subexpr is.
10497     return IntRange(SubRange.Width,
10498                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10499   }
10500 
10501   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10502     // If we can fold the condition, just take that operand.
10503     bool CondResult;
10504     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10505       return GetExprRange(C,
10506                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10507                           MaxWidth, InConstantContext, Approximate);
10508 
10509     // Otherwise, conservatively merge.
10510     // GetExprRange requires an integer expression, but a throw expression
10511     // results in a void type.
10512     Expr *E = CO->getTrueExpr();
10513     IntRange L = E->getType()->isVoidType()
10514                      ? IntRange{0, true}
10515                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10516     E = CO->getFalseExpr();
10517     IntRange R = E->getType()->isVoidType()
10518                      ? IntRange{0, true}
10519                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10520     return IntRange::join(L, R);
10521   }
10522 
10523   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10524     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10525 
10526     switch (BO->getOpcode()) {
10527     case BO_Cmp:
10528       llvm_unreachable("builtin <=> should have class type");
10529 
10530     // Boolean-valued operations are single-bit and positive.
10531     case BO_LAnd:
10532     case BO_LOr:
10533     case BO_LT:
10534     case BO_GT:
10535     case BO_LE:
10536     case BO_GE:
10537     case BO_EQ:
10538     case BO_NE:
10539       return IntRange::forBoolType();
10540 
10541     // The type of the assignments is the type of the LHS, so the RHS
10542     // is not necessarily the same type.
10543     case BO_MulAssign:
10544     case BO_DivAssign:
10545     case BO_RemAssign:
10546     case BO_AddAssign:
10547     case BO_SubAssign:
10548     case BO_XorAssign:
10549     case BO_OrAssign:
10550       // TODO: bitfields?
10551       return IntRange::forValueOfType(C, GetExprType(E));
10552 
10553     // Simple assignments just pass through the RHS, which will have
10554     // been coerced to the LHS type.
10555     case BO_Assign:
10556       // TODO: bitfields?
10557       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10558                           Approximate);
10559 
10560     // Operations with opaque sources are black-listed.
10561     case BO_PtrMemD:
10562     case BO_PtrMemI:
10563       return IntRange::forValueOfType(C, GetExprType(E));
10564 
10565     // Bitwise-and uses the *infinum* of the two source ranges.
10566     case BO_And:
10567     case BO_AndAssign:
10568       Combine = IntRange::bit_and;
10569       break;
10570 
10571     // Left shift gets black-listed based on a judgement call.
10572     case BO_Shl:
10573       // ...except that we want to treat '1 << (blah)' as logically
10574       // positive.  It's an important idiom.
10575       if (IntegerLiteral *I
10576             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10577         if (I->getValue() == 1) {
10578           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10579           return IntRange(R.Width, /*NonNegative*/ true);
10580         }
10581       }
10582       LLVM_FALLTHROUGH;
10583 
10584     case BO_ShlAssign:
10585       return IntRange::forValueOfType(C, GetExprType(E));
10586 
10587     // Right shift by a constant can narrow its left argument.
10588     case BO_Shr:
10589     case BO_ShrAssign: {
10590       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10591                                 Approximate);
10592 
10593       // If the shift amount is a positive constant, drop the width by
10594       // that much.
10595       if (Optional<llvm::APSInt> shift =
10596               BO->getRHS()->getIntegerConstantExpr(C)) {
10597         if (shift->isNonNegative()) {
10598           unsigned zext = shift->getZExtValue();
10599           if (zext >= L.Width)
10600             L.Width = (L.NonNegative ? 0 : 1);
10601           else
10602             L.Width -= zext;
10603         }
10604       }
10605 
10606       return L;
10607     }
10608 
10609     // Comma acts as its right operand.
10610     case BO_Comma:
10611       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10612                           Approximate);
10613 
10614     case BO_Add:
10615       if (!Approximate)
10616         Combine = IntRange::sum;
10617       break;
10618 
10619     case BO_Sub:
10620       if (BO->getLHS()->getType()->isPointerType())
10621         return IntRange::forValueOfType(C, GetExprType(E));
10622       if (!Approximate)
10623         Combine = IntRange::difference;
10624       break;
10625 
10626     case BO_Mul:
10627       if (!Approximate)
10628         Combine = IntRange::product;
10629       break;
10630 
10631     // The width of a division result is mostly determined by the size
10632     // of the LHS.
10633     case BO_Div: {
10634       // Don't 'pre-truncate' the operands.
10635       unsigned opWidth = C.getIntWidth(GetExprType(E));
10636       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10637                                 Approximate);
10638 
10639       // If the divisor is constant, use that.
10640       if (Optional<llvm::APSInt> divisor =
10641               BO->getRHS()->getIntegerConstantExpr(C)) {
10642         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10643         if (log2 >= L.Width)
10644           L.Width = (L.NonNegative ? 0 : 1);
10645         else
10646           L.Width = std::min(L.Width - log2, MaxWidth);
10647         return L;
10648       }
10649 
10650       // Otherwise, just use the LHS's width.
10651       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10652       // could be -1.
10653       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10654                                 Approximate);
10655       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10656     }
10657 
10658     case BO_Rem:
10659       Combine = IntRange::rem;
10660       break;
10661 
10662     // The default behavior is okay for these.
10663     case BO_Xor:
10664     case BO_Or:
10665       break;
10666     }
10667 
10668     // Combine the two ranges, but limit the result to the type in which we
10669     // performed the computation.
10670     QualType T = GetExprType(E);
10671     unsigned opWidth = C.getIntWidth(T);
10672     IntRange L =
10673         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10674     IntRange R =
10675         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10676     IntRange C = Combine(L, R);
10677     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10678     C.Width = std::min(C.Width, MaxWidth);
10679     return C;
10680   }
10681 
10682   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10683     switch (UO->getOpcode()) {
10684     // Boolean-valued operations are white-listed.
10685     case UO_LNot:
10686       return IntRange::forBoolType();
10687 
10688     // Operations with opaque sources are black-listed.
10689     case UO_Deref:
10690     case UO_AddrOf: // should be impossible
10691       return IntRange::forValueOfType(C, GetExprType(E));
10692 
10693     default:
10694       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10695                           Approximate);
10696     }
10697   }
10698 
10699   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10700     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10701                         Approximate);
10702 
10703   if (const auto *BitField = E->getSourceBitField())
10704     return IntRange(BitField->getBitWidthValue(C),
10705                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10706 
10707   return IntRange::forValueOfType(C, GetExprType(E));
10708 }
10709 
10710 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10711                              bool InConstantContext, bool Approximate) {
10712   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10713                       Approximate);
10714 }
10715 
10716 /// Checks whether the given value, which currently has the given
10717 /// source semantics, has the same value when coerced through the
10718 /// target semantics.
10719 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10720                                  const llvm::fltSemantics &Src,
10721                                  const llvm::fltSemantics &Tgt) {
10722   llvm::APFloat truncated = value;
10723 
10724   bool ignored;
10725   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10726   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10727 
10728   return truncated.bitwiseIsEqual(value);
10729 }
10730 
10731 /// Checks whether the given value, which currently has the given
10732 /// source semantics, has the same value when coerced through the
10733 /// target semantics.
10734 ///
10735 /// The value might be a vector of floats (or a complex number).
10736 static bool IsSameFloatAfterCast(const APValue &value,
10737                                  const llvm::fltSemantics &Src,
10738                                  const llvm::fltSemantics &Tgt) {
10739   if (value.isFloat())
10740     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10741 
10742   if (value.isVector()) {
10743     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10744       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10745         return false;
10746     return true;
10747   }
10748 
10749   assert(value.isComplexFloat());
10750   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10751           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10752 }
10753 
10754 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10755                                        bool IsListInit = false);
10756 
10757 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10758   // Suppress cases where we are comparing against an enum constant.
10759   if (const DeclRefExpr *DR =
10760       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10761     if (isa<EnumConstantDecl>(DR->getDecl()))
10762       return true;
10763 
10764   // Suppress cases where the value is expanded from a macro, unless that macro
10765   // is how a language represents a boolean literal. This is the case in both C
10766   // and Objective-C.
10767   SourceLocation BeginLoc = E->getBeginLoc();
10768   if (BeginLoc.isMacroID()) {
10769     StringRef MacroName = Lexer::getImmediateMacroName(
10770         BeginLoc, S.getSourceManager(), S.getLangOpts());
10771     return MacroName != "YES" && MacroName != "NO" &&
10772            MacroName != "true" && MacroName != "false";
10773   }
10774 
10775   return false;
10776 }
10777 
10778 static bool isKnownToHaveUnsignedValue(Expr *E) {
10779   return E->getType()->isIntegerType() &&
10780          (!E->getType()->isSignedIntegerType() ||
10781           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10782 }
10783 
10784 namespace {
10785 /// The promoted range of values of a type. In general this has the
10786 /// following structure:
10787 ///
10788 ///     |-----------| . . . |-----------|
10789 ///     ^           ^       ^           ^
10790 ///    Min       HoleMin  HoleMax      Max
10791 ///
10792 /// ... where there is only a hole if a signed type is promoted to unsigned
10793 /// (in which case Min and Max are the smallest and largest representable
10794 /// values).
10795 struct PromotedRange {
10796   // Min, or HoleMax if there is a hole.
10797   llvm::APSInt PromotedMin;
10798   // Max, or HoleMin if there is a hole.
10799   llvm::APSInt PromotedMax;
10800 
10801   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10802     if (R.Width == 0)
10803       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10804     else if (R.Width >= BitWidth && !Unsigned) {
10805       // Promotion made the type *narrower*. This happens when promoting
10806       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10807       // Treat all values of 'signed int' as being in range for now.
10808       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10809       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10810     } else {
10811       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10812                         .extOrTrunc(BitWidth);
10813       PromotedMin.setIsUnsigned(Unsigned);
10814 
10815       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10816                         .extOrTrunc(BitWidth);
10817       PromotedMax.setIsUnsigned(Unsigned);
10818     }
10819   }
10820 
10821   // Determine whether this range is contiguous (has no hole).
10822   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10823 
10824   // Where a constant value is within the range.
10825   enum ComparisonResult {
10826     LT = 0x1,
10827     LE = 0x2,
10828     GT = 0x4,
10829     GE = 0x8,
10830     EQ = 0x10,
10831     NE = 0x20,
10832     InRangeFlag = 0x40,
10833 
10834     Less = LE | LT | NE,
10835     Min = LE | InRangeFlag,
10836     InRange = InRangeFlag,
10837     Max = GE | InRangeFlag,
10838     Greater = GE | GT | NE,
10839 
10840     OnlyValue = LE | GE | EQ | InRangeFlag,
10841     InHole = NE
10842   };
10843 
10844   ComparisonResult compare(const llvm::APSInt &Value) const {
10845     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10846            Value.isUnsigned() == PromotedMin.isUnsigned());
10847     if (!isContiguous()) {
10848       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10849       if (Value.isMinValue()) return Min;
10850       if (Value.isMaxValue()) return Max;
10851       if (Value >= PromotedMin) return InRange;
10852       if (Value <= PromotedMax) return InRange;
10853       return InHole;
10854     }
10855 
10856     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10857     case -1: return Less;
10858     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10859     case 1:
10860       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10861       case -1: return InRange;
10862       case 0: return Max;
10863       case 1: return Greater;
10864       }
10865     }
10866 
10867     llvm_unreachable("impossible compare result");
10868   }
10869 
10870   static llvm::Optional<StringRef>
10871   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10872     if (Op == BO_Cmp) {
10873       ComparisonResult LTFlag = LT, GTFlag = GT;
10874       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10875 
10876       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10877       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10878       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10879       return llvm::None;
10880     }
10881 
10882     ComparisonResult TrueFlag, FalseFlag;
10883     if (Op == BO_EQ) {
10884       TrueFlag = EQ;
10885       FalseFlag = NE;
10886     } else if (Op == BO_NE) {
10887       TrueFlag = NE;
10888       FalseFlag = EQ;
10889     } else {
10890       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10891         TrueFlag = LT;
10892         FalseFlag = GE;
10893       } else {
10894         TrueFlag = GT;
10895         FalseFlag = LE;
10896       }
10897       if (Op == BO_GE || Op == BO_LE)
10898         std::swap(TrueFlag, FalseFlag);
10899     }
10900     if (R & TrueFlag)
10901       return StringRef("true");
10902     if (R & FalseFlag)
10903       return StringRef("false");
10904     return llvm::None;
10905   }
10906 };
10907 }
10908 
10909 static bool HasEnumType(Expr *E) {
10910   // Strip off implicit integral promotions.
10911   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10912     if (ICE->getCastKind() != CK_IntegralCast &&
10913         ICE->getCastKind() != CK_NoOp)
10914       break;
10915     E = ICE->getSubExpr();
10916   }
10917 
10918   return E->getType()->isEnumeralType();
10919 }
10920 
10921 static int classifyConstantValue(Expr *Constant) {
10922   // The values of this enumeration are used in the diagnostics
10923   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10924   enum ConstantValueKind {
10925     Miscellaneous = 0,
10926     LiteralTrue,
10927     LiteralFalse
10928   };
10929   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10930     return BL->getValue() ? ConstantValueKind::LiteralTrue
10931                           : ConstantValueKind::LiteralFalse;
10932   return ConstantValueKind::Miscellaneous;
10933 }
10934 
10935 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10936                                         Expr *Constant, Expr *Other,
10937                                         const llvm::APSInt &Value,
10938                                         bool RhsConstant) {
10939   if (S.inTemplateInstantiation())
10940     return false;
10941 
10942   Expr *OriginalOther = Other;
10943 
10944   Constant = Constant->IgnoreParenImpCasts();
10945   Other = Other->IgnoreParenImpCasts();
10946 
10947   // Suppress warnings on tautological comparisons between values of the same
10948   // enumeration type. There are only two ways we could warn on this:
10949   //  - If the constant is outside the range of representable values of
10950   //    the enumeration. In such a case, we should warn about the cast
10951   //    to enumeration type, not about the comparison.
10952   //  - If the constant is the maximum / minimum in-range value. For an
10953   //    enumeratin type, such comparisons can be meaningful and useful.
10954   if (Constant->getType()->isEnumeralType() &&
10955       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10956     return false;
10957 
10958   IntRange OtherValueRange = GetExprRange(
10959       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
10960 
10961   QualType OtherT = Other->getType();
10962   if (const auto *AT = OtherT->getAs<AtomicType>())
10963     OtherT = AT->getValueType();
10964   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
10965 
10966   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10967   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
10968   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10969                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10970                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10971 
10972   // Whether we're treating Other as being a bool because of the form of
10973   // expression despite it having another type (typically 'int' in C).
10974   bool OtherIsBooleanDespiteType =
10975       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10976   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10977     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
10978 
10979   // Check if all values in the range of possible values of this expression
10980   // lead to the same comparison outcome.
10981   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
10982                                         Value.isUnsigned());
10983   auto Cmp = OtherPromotedValueRange.compare(Value);
10984   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10985   if (!Result)
10986     return false;
10987 
10988   // Also consider the range determined by the type alone. This allows us to
10989   // classify the warning under the proper diagnostic group.
10990   bool TautologicalTypeCompare = false;
10991   {
10992     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
10993                                          Value.isUnsigned());
10994     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
10995     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
10996                                                        RhsConstant)) {
10997       TautologicalTypeCompare = true;
10998       Cmp = TypeCmp;
10999       Result = TypeResult;
11000     }
11001   }
11002 
11003   // Don't warn if the non-constant operand actually always evaluates to the
11004   // same value.
11005   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11006     return false;
11007 
11008   // Suppress the diagnostic for an in-range comparison if the constant comes
11009   // from a macro or enumerator. We don't want to diagnose
11010   //
11011   //   some_long_value <= INT_MAX
11012   //
11013   // when sizeof(int) == sizeof(long).
11014   bool InRange = Cmp & PromotedRange::InRangeFlag;
11015   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11016     return false;
11017 
11018   // A comparison of an unsigned bit-field against 0 is really a type problem,
11019   // even though at the type level the bit-field might promote to 'signed int'.
11020   if (Other->refersToBitField() && InRange && Value == 0 &&
11021       Other->getType()->isUnsignedIntegerOrEnumerationType())
11022     TautologicalTypeCompare = true;
11023 
11024   // If this is a comparison to an enum constant, include that
11025   // constant in the diagnostic.
11026   const EnumConstantDecl *ED = nullptr;
11027   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11028     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11029 
11030   // Should be enough for uint128 (39 decimal digits)
11031   SmallString<64> PrettySourceValue;
11032   llvm::raw_svector_ostream OS(PrettySourceValue);
11033   if (ED) {
11034     OS << '\'' << *ED << "' (" << Value << ")";
11035   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11036                Constant->IgnoreParenImpCasts())) {
11037     OS << (BL->getValue() ? "YES" : "NO");
11038   } else {
11039     OS << Value;
11040   }
11041 
11042   if (!TautologicalTypeCompare) {
11043     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11044         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11045         << E->getOpcodeStr() << OS.str() << *Result
11046         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11047     return true;
11048   }
11049 
11050   if (IsObjCSignedCharBool) {
11051     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11052                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11053                               << OS.str() << *Result);
11054     return true;
11055   }
11056 
11057   // FIXME: We use a somewhat different formatting for the in-range cases and
11058   // cases involving boolean values for historical reasons. We should pick a
11059   // consistent way of presenting these diagnostics.
11060   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11061 
11062     S.DiagRuntimeBehavior(
11063         E->getOperatorLoc(), E,
11064         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11065                          : diag::warn_tautological_bool_compare)
11066             << OS.str() << classifyConstantValue(Constant) << OtherT
11067             << OtherIsBooleanDespiteType << *Result
11068             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11069   } else {
11070     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11071                         ? (HasEnumType(OriginalOther)
11072                                ? diag::warn_unsigned_enum_always_true_comparison
11073                                : diag::warn_unsigned_always_true_comparison)
11074                         : diag::warn_tautological_constant_compare;
11075 
11076     S.Diag(E->getOperatorLoc(), Diag)
11077         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11078         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11079   }
11080 
11081   return true;
11082 }
11083 
11084 /// Analyze the operands of the given comparison.  Implements the
11085 /// fallback case from AnalyzeComparison.
11086 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11087   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11088   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11089 }
11090 
11091 /// Implements -Wsign-compare.
11092 ///
11093 /// \param E the binary operator to check for warnings
11094 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11095   // The type the comparison is being performed in.
11096   QualType T = E->getLHS()->getType();
11097 
11098   // Only analyze comparison operators where both sides have been converted to
11099   // the same type.
11100   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11101     return AnalyzeImpConvsInComparison(S, E);
11102 
11103   // Don't analyze value-dependent comparisons directly.
11104   if (E->isValueDependent())
11105     return AnalyzeImpConvsInComparison(S, E);
11106 
11107   Expr *LHS = E->getLHS();
11108   Expr *RHS = E->getRHS();
11109 
11110   if (T->isIntegralType(S.Context)) {
11111     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11112     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11113 
11114     // We don't care about expressions whose result is a constant.
11115     if (RHSValue && LHSValue)
11116       return AnalyzeImpConvsInComparison(S, E);
11117 
11118     // We only care about expressions where just one side is literal
11119     if ((bool)RHSValue ^ (bool)LHSValue) {
11120       // Is the constant on the RHS or LHS?
11121       const bool RhsConstant = (bool)RHSValue;
11122       Expr *Const = RhsConstant ? RHS : LHS;
11123       Expr *Other = RhsConstant ? LHS : RHS;
11124       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11125 
11126       // Check whether an integer constant comparison results in a value
11127       // of 'true' or 'false'.
11128       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11129         return AnalyzeImpConvsInComparison(S, E);
11130     }
11131   }
11132 
11133   if (!T->hasUnsignedIntegerRepresentation()) {
11134     // We don't do anything special if this isn't an unsigned integral
11135     // comparison:  we're only interested in integral comparisons, and
11136     // signed comparisons only happen in cases we don't care to warn about.
11137     return AnalyzeImpConvsInComparison(S, E);
11138   }
11139 
11140   LHS = LHS->IgnoreParenImpCasts();
11141   RHS = RHS->IgnoreParenImpCasts();
11142 
11143   if (!S.getLangOpts().CPlusPlus) {
11144     // Avoid warning about comparison of integers with different signs when
11145     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11146     // the type of `E`.
11147     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11148       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11149     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11150       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11151   }
11152 
11153   // Check to see if one of the (unmodified) operands is of different
11154   // signedness.
11155   Expr *signedOperand, *unsignedOperand;
11156   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11157     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11158            "unsigned comparison between two signed integer expressions?");
11159     signedOperand = LHS;
11160     unsignedOperand = RHS;
11161   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11162     signedOperand = RHS;
11163     unsignedOperand = LHS;
11164   } else {
11165     return AnalyzeImpConvsInComparison(S, E);
11166   }
11167 
11168   // Otherwise, calculate the effective range of the signed operand.
11169   IntRange signedRange = GetExprRange(
11170       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11171 
11172   // Go ahead and analyze implicit conversions in the operands.  Note
11173   // that we skip the implicit conversions on both sides.
11174   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11175   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11176 
11177   // If the signed range is non-negative, -Wsign-compare won't fire.
11178   if (signedRange.NonNegative)
11179     return;
11180 
11181   // For (in)equality comparisons, if the unsigned operand is a
11182   // constant which cannot collide with a overflowed signed operand,
11183   // then reinterpreting the signed operand as unsigned will not
11184   // change the result of the comparison.
11185   if (E->isEqualityOp()) {
11186     unsigned comparisonWidth = S.Context.getIntWidth(T);
11187     IntRange unsignedRange =
11188         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11189                      /*Approximate*/ true);
11190 
11191     // We should never be unable to prove that the unsigned operand is
11192     // non-negative.
11193     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11194 
11195     if (unsignedRange.Width < comparisonWidth)
11196       return;
11197   }
11198 
11199   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11200                         S.PDiag(diag::warn_mixed_sign_comparison)
11201                             << LHS->getType() << RHS->getType()
11202                             << LHS->getSourceRange() << RHS->getSourceRange());
11203 }
11204 
11205 /// Analyzes an attempt to assign the given value to a bitfield.
11206 ///
11207 /// Returns true if there was something fishy about the attempt.
11208 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11209                                       SourceLocation InitLoc) {
11210   assert(Bitfield->isBitField());
11211   if (Bitfield->isInvalidDecl())
11212     return false;
11213 
11214   // White-list bool bitfields.
11215   QualType BitfieldType = Bitfield->getType();
11216   if (BitfieldType->isBooleanType())
11217      return false;
11218 
11219   if (BitfieldType->isEnumeralType()) {
11220     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11221     // If the underlying enum type was not explicitly specified as an unsigned
11222     // type and the enum contain only positive values, MSVC++ will cause an
11223     // inconsistency by storing this as a signed type.
11224     if (S.getLangOpts().CPlusPlus11 &&
11225         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11226         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11227         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11228       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11229           << BitfieldEnumDecl;
11230     }
11231   }
11232 
11233   if (Bitfield->getType()->isBooleanType())
11234     return false;
11235 
11236   // Ignore value- or type-dependent expressions.
11237   if (Bitfield->getBitWidth()->isValueDependent() ||
11238       Bitfield->getBitWidth()->isTypeDependent() ||
11239       Init->isValueDependent() ||
11240       Init->isTypeDependent())
11241     return false;
11242 
11243   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11244   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11245 
11246   Expr::EvalResult Result;
11247   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11248                                    Expr::SE_AllowSideEffects)) {
11249     // The RHS is not constant.  If the RHS has an enum type, make sure the
11250     // bitfield is wide enough to hold all the values of the enum without
11251     // truncation.
11252     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11253       EnumDecl *ED = EnumTy->getDecl();
11254       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11255 
11256       // Enum types are implicitly signed on Windows, so check if there are any
11257       // negative enumerators to see if the enum was intended to be signed or
11258       // not.
11259       bool SignedEnum = ED->getNumNegativeBits() > 0;
11260 
11261       // Check for surprising sign changes when assigning enum values to a
11262       // bitfield of different signedness.  If the bitfield is signed and we
11263       // have exactly the right number of bits to store this unsigned enum,
11264       // suggest changing the enum to an unsigned type. This typically happens
11265       // on Windows where unfixed enums always use an underlying type of 'int'.
11266       unsigned DiagID = 0;
11267       if (SignedEnum && !SignedBitfield) {
11268         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11269       } else if (SignedBitfield && !SignedEnum &&
11270                  ED->getNumPositiveBits() == FieldWidth) {
11271         DiagID = diag::warn_signed_bitfield_enum_conversion;
11272       }
11273 
11274       if (DiagID) {
11275         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11276         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11277         SourceRange TypeRange =
11278             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11279         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11280             << SignedEnum << TypeRange;
11281       }
11282 
11283       // Compute the required bitwidth. If the enum has negative values, we need
11284       // one more bit than the normal number of positive bits to represent the
11285       // sign bit.
11286       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11287                                                   ED->getNumNegativeBits())
11288                                        : ED->getNumPositiveBits();
11289 
11290       // Check the bitwidth.
11291       if (BitsNeeded > FieldWidth) {
11292         Expr *WidthExpr = Bitfield->getBitWidth();
11293         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11294             << Bitfield << ED;
11295         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11296             << BitsNeeded << ED << WidthExpr->getSourceRange();
11297       }
11298     }
11299 
11300     return false;
11301   }
11302 
11303   llvm::APSInt Value = Result.Val.getInt();
11304 
11305   unsigned OriginalWidth = Value.getBitWidth();
11306 
11307   if (!Value.isSigned() || Value.isNegative())
11308     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11309       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11310         OriginalWidth = Value.getMinSignedBits();
11311 
11312   if (OriginalWidth <= FieldWidth)
11313     return false;
11314 
11315   // Compute the value which the bitfield will contain.
11316   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11317   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11318 
11319   // Check whether the stored value is equal to the original value.
11320   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11321   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11322     return false;
11323 
11324   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11325   // therefore don't strictly fit into a signed bitfield of width 1.
11326   if (FieldWidth == 1 && Value == 1)
11327     return false;
11328 
11329   std::string PrettyValue = Value.toString(10);
11330   std::string PrettyTrunc = TruncatedValue.toString(10);
11331 
11332   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11333     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11334     << Init->getSourceRange();
11335 
11336   return true;
11337 }
11338 
11339 /// Analyze the given simple or compound assignment for warning-worthy
11340 /// operations.
11341 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11342   // Just recurse on the LHS.
11343   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11344 
11345   // We want to recurse on the RHS as normal unless we're assigning to
11346   // a bitfield.
11347   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11348     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11349                                   E->getOperatorLoc())) {
11350       // Recurse, ignoring any implicit conversions on the RHS.
11351       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11352                                         E->getOperatorLoc());
11353     }
11354   }
11355 
11356   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11357 
11358   // Diagnose implicitly sequentially-consistent atomic assignment.
11359   if (E->getLHS()->getType()->isAtomicType())
11360     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11361 }
11362 
11363 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11364 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11365                             SourceLocation CContext, unsigned diag,
11366                             bool pruneControlFlow = false) {
11367   if (pruneControlFlow) {
11368     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11369                           S.PDiag(diag)
11370                               << SourceType << T << E->getSourceRange()
11371                               << SourceRange(CContext));
11372     return;
11373   }
11374   S.Diag(E->getExprLoc(), diag)
11375     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11376 }
11377 
11378 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11379 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11380                             SourceLocation CContext,
11381                             unsigned diag, bool pruneControlFlow = false) {
11382   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11383 }
11384 
11385 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11386   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11387       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11388 }
11389 
11390 static void adornObjCBoolConversionDiagWithTernaryFixit(
11391     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11392   Expr *Ignored = SourceExpr->IgnoreImplicit();
11393   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11394     Ignored = OVE->getSourceExpr();
11395   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11396                      isa<BinaryOperator>(Ignored) ||
11397                      isa<CXXOperatorCallExpr>(Ignored);
11398   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11399   if (NeedsParens)
11400     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11401             << FixItHint::CreateInsertion(EndLoc, ")");
11402   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11403 }
11404 
11405 /// Diagnose an implicit cast from a floating point value to an integer value.
11406 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11407                                     SourceLocation CContext) {
11408   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11409   const bool PruneWarnings = S.inTemplateInstantiation();
11410 
11411   Expr *InnerE = E->IgnoreParenImpCasts();
11412   // We also want to warn on, e.g., "int i = -1.234"
11413   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11414     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11415       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11416 
11417   const bool IsLiteral =
11418       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11419 
11420   llvm::APFloat Value(0.0);
11421   bool IsConstant =
11422     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11423   if (!IsConstant) {
11424     if (isObjCSignedCharBool(S, T)) {
11425       return adornObjCBoolConversionDiagWithTernaryFixit(
11426           S, E,
11427           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11428               << E->getType());
11429     }
11430 
11431     return DiagnoseImpCast(S, E, T, CContext,
11432                            diag::warn_impcast_float_integer, PruneWarnings);
11433   }
11434 
11435   bool isExact = false;
11436 
11437   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11438                             T->hasUnsignedIntegerRepresentation());
11439   llvm::APFloat::opStatus Result = Value.convertToInteger(
11440       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11441 
11442   // FIXME: Force the precision of the source value down so we don't print
11443   // digits which are usually useless (we don't really care here if we
11444   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11445   // would automatically print the shortest representation, but it's a bit
11446   // tricky to implement.
11447   SmallString<16> PrettySourceValue;
11448   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11449   precision = (precision * 59 + 195) / 196;
11450   Value.toString(PrettySourceValue, precision);
11451 
11452   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11453     return adornObjCBoolConversionDiagWithTernaryFixit(
11454         S, E,
11455         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11456             << PrettySourceValue);
11457   }
11458 
11459   if (Result == llvm::APFloat::opOK && isExact) {
11460     if (IsLiteral) return;
11461     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11462                            PruneWarnings);
11463   }
11464 
11465   // Conversion of a floating-point value to a non-bool integer where the
11466   // integral part cannot be represented by the integer type is undefined.
11467   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11468     return DiagnoseImpCast(
11469         S, E, T, CContext,
11470         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11471                   : diag::warn_impcast_float_to_integer_out_of_range,
11472         PruneWarnings);
11473 
11474   unsigned DiagID = 0;
11475   if (IsLiteral) {
11476     // Warn on floating point literal to integer.
11477     DiagID = diag::warn_impcast_literal_float_to_integer;
11478   } else if (IntegerValue == 0) {
11479     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11480       return DiagnoseImpCast(S, E, T, CContext,
11481                              diag::warn_impcast_float_integer, PruneWarnings);
11482     }
11483     // Warn on non-zero to zero conversion.
11484     DiagID = diag::warn_impcast_float_to_integer_zero;
11485   } else {
11486     if (IntegerValue.isUnsigned()) {
11487       if (!IntegerValue.isMaxValue()) {
11488         return DiagnoseImpCast(S, E, T, CContext,
11489                                diag::warn_impcast_float_integer, PruneWarnings);
11490       }
11491     } else {  // IntegerValue.isSigned()
11492       if (!IntegerValue.isMaxSignedValue() &&
11493           !IntegerValue.isMinSignedValue()) {
11494         return DiagnoseImpCast(S, E, T, CContext,
11495                                diag::warn_impcast_float_integer, PruneWarnings);
11496       }
11497     }
11498     // Warn on evaluatable floating point expression to integer conversion.
11499     DiagID = diag::warn_impcast_float_to_integer;
11500   }
11501 
11502   SmallString<16> PrettyTargetValue;
11503   if (IsBool)
11504     PrettyTargetValue = Value.isZero() ? "false" : "true";
11505   else
11506     IntegerValue.toString(PrettyTargetValue);
11507 
11508   if (PruneWarnings) {
11509     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11510                           S.PDiag(DiagID)
11511                               << E->getType() << T.getUnqualifiedType()
11512                               << PrettySourceValue << PrettyTargetValue
11513                               << E->getSourceRange() << SourceRange(CContext));
11514   } else {
11515     S.Diag(E->getExprLoc(), DiagID)
11516         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11517         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11518   }
11519 }
11520 
11521 /// Analyze the given compound assignment for the possible losing of
11522 /// floating-point precision.
11523 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11524   assert(isa<CompoundAssignOperator>(E) &&
11525          "Must be compound assignment operation");
11526   // Recurse on the LHS and RHS in here
11527   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11528   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11529 
11530   if (E->getLHS()->getType()->isAtomicType())
11531     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11532 
11533   // Now check the outermost expression
11534   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11535   const auto *RBT = cast<CompoundAssignOperator>(E)
11536                         ->getComputationResultType()
11537                         ->getAs<BuiltinType>();
11538 
11539   // The below checks assume source is floating point.
11540   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11541 
11542   // If source is floating point but target is an integer.
11543   if (ResultBT->isInteger())
11544     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11545                            E->getExprLoc(), diag::warn_impcast_float_integer);
11546 
11547   if (!ResultBT->isFloatingPoint())
11548     return;
11549 
11550   // If both source and target are floating points, warn about losing precision.
11551   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11552       QualType(ResultBT, 0), QualType(RBT, 0));
11553   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11554     // warn about dropping FP rank.
11555     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11556                     diag::warn_impcast_float_result_precision);
11557 }
11558 
11559 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11560                                       IntRange Range) {
11561   if (!Range.Width) return "0";
11562 
11563   llvm::APSInt ValueInRange = Value;
11564   ValueInRange.setIsSigned(!Range.NonNegative);
11565   ValueInRange = ValueInRange.trunc(Range.Width);
11566   return ValueInRange.toString(10);
11567 }
11568 
11569 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11570   if (!isa<ImplicitCastExpr>(Ex))
11571     return false;
11572 
11573   Expr *InnerE = Ex->IgnoreParenImpCasts();
11574   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11575   const Type *Source =
11576     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11577   if (Target->isDependentType())
11578     return false;
11579 
11580   const BuiltinType *FloatCandidateBT =
11581     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11582   const Type *BoolCandidateType = ToBool ? Target : Source;
11583 
11584   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11585           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11586 }
11587 
11588 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11589                                              SourceLocation CC) {
11590   unsigned NumArgs = TheCall->getNumArgs();
11591   for (unsigned i = 0; i < NumArgs; ++i) {
11592     Expr *CurrA = TheCall->getArg(i);
11593     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11594       continue;
11595 
11596     bool IsSwapped = ((i > 0) &&
11597         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11598     IsSwapped |= ((i < (NumArgs - 1)) &&
11599         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11600     if (IsSwapped) {
11601       // Warn on this floating-point to bool conversion.
11602       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11603                       CurrA->getType(), CC,
11604                       diag::warn_impcast_floating_point_to_bool);
11605     }
11606   }
11607 }
11608 
11609 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11610                                    SourceLocation CC) {
11611   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11612                         E->getExprLoc()))
11613     return;
11614 
11615   // Don't warn on functions which have return type nullptr_t.
11616   if (isa<CallExpr>(E))
11617     return;
11618 
11619   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11620   const Expr::NullPointerConstantKind NullKind =
11621       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11622   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11623     return;
11624 
11625   // Return if target type is a safe conversion.
11626   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11627       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11628     return;
11629 
11630   SourceLocation Loc = E->getSourceRange().getBegin();
11631 
11632   // Venture through the macro stacks to get to the source of macro arguments.
11633   // The new location is a better location than the complete location that was
11634   // passed in.
11635   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11636   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11637 
11638   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11639   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11640     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11641         Loc, S.SourceMgr, S.getLangOpts());
11642     if (MacroName == "NULL")
11643       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11644   }
11645 
11646   // Only warn if the null and context location are in the same macro expansion.
11647   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11648     return;
11649 
11650   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11651       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11652       << FixItHint::CreateReplacement(Loc,
11653                                       S.getFixItZeroLiteralForType(T, Loc));
11654 }
11655 
11656 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11657                                   ObjCArrayLiteral *ArrayLiteral);
11658 
11659 static void
11660 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11661                            ObjCDictionaryLiteral *DictionaryLiteral);
11662 
11663 /// Check a single element within a collection literal against the
11664 /// target element type.
11665 static void checkObjCCollectionLiteralElement(Sema &S,
11666                                               QualType TargetElementType,
11667                                               Expr *Element,
11668                                               unsigned ElementKind) {
11669   // Skip a bitcast to 'id' or qualified 'id'.
11670   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11671     if (ICE->getCastKind() == CK_BitCast &&
11672         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11673       Element = ICE->getSubExpr();
11674   }
11675 
11676   QualType ElementType = Element->getType();
11677   ExprResult ElementResult(Element);
11678   if (ElementType->getAs<ObjCObjectPointerType>() &&
11679       S.CheckSingleAssignmentConstraints(TargetElementType,
11680                                          ElementResult,
11681                                          false, false)
11682         != Sema::Compatible) {
11683     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11684         << ElementType << ElementKind << TargetElementType
11685         << Element->getSourceRange();
11686   }
11687 
11688   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11689     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11690   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11691     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11692 }
11693 
11694 /// Check an Objective-C array literal being converted to the given
11695 /// target type.
11696 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11697                                   ObjCArrayLiteral *ArrayLiteral) {
11698   if (!S.NSArrayDecl)
11699     return;
11700 
11701   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11702   if (!TargetObjCPtr)
11703     return;
11704 
11705   if (TargetObjCPtr->isUnspecialized() ||
11706       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11707         != S.NSArrayDecl->getCanonicalDecl())
11708     return;
11709 
11710   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11711   if (TypeArgs.size() != 1)
11712     return;
11713 
11714   QualType TargetElementType = TypeArgs[0];
11715   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11716     checkObjCCollectionLiteralElement(S, TargetElementType,
11717                                       ArrayLiteral->getElement(I),
11718                                       0);
11719   }
11720 }
11721 
11722 /// Check an Objective-C dictionary literal being converted to the given
11723 /// target type.
11724 static void
11725 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11726                            ObjCDictionaryLiteral *DictionaryLiteral) {
11727   if (!S.NSDictionaryDecl)
11728     return;
11729 
11730   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11731   if (!TargetObjCPtr)
11732     return;
11733 
11734   if (TargetObjCPtr->isUnspecialized() ||
11735       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11736         != S.NSDictionaryDecl->getCanonicalDecl())
11737     return;
11738 
11739   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11740   if (TypeArgs.size() != 2)
11741     return;
11742 
11743   QualType TargetKeyType = TypeArgs[0];
11744   QualType TargetObjectType = TypeArgs[1];
11745   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11746     auto Element = DictionaryLiteral->getKeyValueElement(I);
11747     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11748     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11749   }
11750 }
11751 
11752 // Helper function to filter out cases for constant width constant conversion.
11753 // Don't warn on char array initialization or for non-decimal values.
11754 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11755                                           SourceLocation CC) {
11756   // If initializing from a constant, and the constant starts with '0',
11757   // then it is a binary, octal, or hexadecimal.  Allow these constants
11758   // to fill all the bits, even if there is a sign change.
11759   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11760     const char FirstLiteralCharacter =
11761         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11762     if (FirstLiteralCharacter == '0')
11763       return false;
11764   }
11765 
11766   // If the CC location points to a '{', and the type is char, then assume
11767   // assume it is an array initialization.
11768   if (CC.isValid() && T->isCharType()) {
11769     const char FirstContextCharacter =
11770         S.getSourceManager().getCharacterData(CC)[0];
11771     if (FirstContextCharacter == '{')
11772       return false;
11773   }
11774 
11775   return true;
11776 }
11777 
11778 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11779   const auto *IL = dyn_cast<IntegerLiteral>(E);
11780   if (!IL) {
11781     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11782       if (UO->getOpcode() == UO_Minus)
11783         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11784     }
11785   }
11786 
11787   return IL;
11788 }
11789 
11790 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11791   E = E->IgnoreParenImpCasts();
11792   SourceLocation ExprLoc = E->getExprLoc();
11793 
11794   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11795     BinaryOperator::Opcode Opc = BO->getOpcode();
11796     Expr::EvalResult Result;
11797     // Do not diagnose unsigned shifts.
11798     if (Opc == BO_Shl) {
11799       const auto *LHS = getIntegerLiteral(BO->getLHS());
11800       const auto *RHS = getIntegerLiteral(BO->getRHS());
11801       if (LHS && LHS->getValue() == 0)
11802         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11803       else if (!E->isValueDependent() && LHS && RHS &&
11804                RHS->getValue().isNonNegative() &&
11805                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11806         S.Diag(ExprLoc, diag::warn_left_shift_always)
11807             << (Result.Val.getInt() != 0);
11808       else if (E->getType()->isSignedIntegerType())
11809         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11810     }
11811   }
11812 
11813   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11814     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11815     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11816     if (!LHS || !RHS)
11817       return;
11818     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11819         (RHS->getValue() == 0 || RHS->getValue() == 1))
11820       // Do not diagnose common idioms.
11821       return;
11822     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11823       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11824   }
11825 }
11826 
11827 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11828                                     SourceLocation CC,
11829                                     bool *ICContext = nullptr,
11830                                     bool IsListInit = false) {
11831   if (E->isTypeDependent() || E->isValueDependent()) return;
11832 
11833   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11834   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11835   if (Source == Target) return;
11836   if (Target->isDependentType()) return;
11837 
11838   // If the conversion context location is invalid don't complain. We also
11839   // don't want to emit a warning if the issue occurs from the expansion of
11840   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11841   // delay this check as long as possible. Once we detect we are in that
11842   // scenario, we just return.
11843   if (CC.isInvalid())
11844     return;
11845 
11846   if (Source->isAtomicType())
11847     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11848 
11849   // Diagnose implicit casts to bool.
11850   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11851     if (isa<StringLiteral>(E))
11852       // Warn on string literal to bool.  Checks for string literals in logical
11853       // and expressions, for instance, assert(0 && "error here"), are
11854       // prevented by a check in AnalyzeImplicitConversions().
11855       return DiagnoseImpCast(S, E, T, CC,
11856                              diag::warn_impcast_string_literal_to_bool);
11857     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11858         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11859       // This covers the literal expressions that evaluate to Objective-C
11860       // objects.
11861       return DiagnoseImpCast(S, E, T, CC,
11862                              diag::warn_impcast_objective_c_literal_to_bool);
11863     }
11864     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11865       // Warn on pointer to bool conversion that is always true.
11866       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11867                                      SourceRange(CC));
11868     }
11869   }
11870 
11871   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11872   // is a typedef for signed char (macOS), then that constant value has to be 1
11873   // or 0.
11874   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11875     Expr::EvalResult Result;
11876     if (E->EvaluateAsInt(Result, S.getASTContext(),
11877                          Expr::SE_AllowSideEffects)) {
11878       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11879         adornObjCBoolConversionDiagWithTernaryFixit(
11880             S, E,
11881             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11882                 << Result.Val.getInt().toString(10));
11883       }
11884       return;
11885     }
11886   }
11887 
11888   // Check implicit casts from Objective-C collection literals to specialized
11889   // collection types, e.g., NSArray<NSString *> *.
11890   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11891     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11892   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11893     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11894 
11895   // Strip vector types.
11896   if (isa<VectorType>(Source)) {
11897     if (!isa<VectorType>(Target)) {
11898       if (S.SourceMgr.isInSystemMacro(CC))
11899         return;
11900       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11901     }
11902 
11903     // If the vector cast is cast between two vectors of the same size, it is
11904     // a bitcast, not a conversion.
11905     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11906       return;
11907 
11908     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11909     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11910   }
11911   if (auto VecTy = dyn_cast<VectorType>(Target))
11912     Target = VecTy->getElementType().getTypePtr();
11913 
11914   // Strip complex types.
11915   if (isa<ComplexType>(Source)) {
11916     if (!isa<ComplexType>(Target)) {
11917       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11918         return;
11919 
11920       return DiagnoseImpCast(S, E, T, CC,
11921                              S.getLangOpts().CPlusPlus
11922                                  ? diag::err_impcast_complex_scalar
11923                                  : diag::warn_impcast_complex_scalar);
11924     }
11925 
11926     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11927     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11928   }
11929 
11930   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11931   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11932 
11933   // If the source is floating point...
11934   if (SourceBT && SourceBT->isFloatingPoint()) {
11935     // ...and the target is floating point...
11936     if (TargetBT && TargetBT->isFloatingPoint()) {
11937       // ...then warn if we're dropping FP rank.
11938 
11939       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11940           QualType(SourceBT, 0), QualType(TargetBT, 0));
11941       if (Order > 0) {
11942         // Don't warn about float constants that are precisely
11943         // representable in the target type.
11944         Expr::EvalResult result;
11945         if (E->EvaluateAsRValue(result, S.Context)) {
11946           // Value might be a float, a float vector, or a float complex.
11947           if (IsSameFloatAfterCast(result.Val,
11948                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11949                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11950             return;
11951         }
11952 
11953         if (S.SourceMgr.isInSystemMacro(CC))
11954           return;
11955 
11956         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11957       }
11958       // ... or possibly if we're increasing rank, too
11959       else if (Order < 0) {
11960         if (S.SourceMgr.isInSystemMacro(CC))
11961           return;
11962 
11963         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11964       }
11965       return;
11966     }
11967 
11968     // If the target is integral, always warn.
11969     if (TargetBT && TargetBT->isInteger()) {
11970       if (S.SourceMgr.isInSystemMacro(CC))
11971         return;
11972 
11973       DiagnoseFloatingImpCast(S, E, T, CC);
11974     }
11975 
11976     // Detect the case where a call result is converted from floating-point to
11977     // to bool, and the final argument to the call is converted from bool, to
11978     // discover this typo:
11979     //
11980     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11981     //
11982     // FIXME: This is an incredibly special case; is there some more general
11983     // way to detect this class of misplaced-parentheses bug?
11984     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11985       // Check last argument of function call to see if it is an
11986       // implicit cast from a type matching the type the result
11987       // is being cast to.
11988       CallExpr *CEx = cast<CallExpr>(E);
11989       if (unsigned NumArgs = CEx->getNumArgs()) {
11990         Expr *LastA = CEx->getArg(NumArgs - 1);
11991         Expr *InnerE = LastA->IgnoreParenImpCasts();
11992         if (isa<ImplicitCastExpr>(LastA) &&
11993             InnerE->getType()->isBooleanType()) {
11994           // Warn on this floating-point to bool conversion
11995           DiagnoseImpCast(S, E, T, CC,
11996                           diag::warn_impcast_floating_point_to_bool);
11997         }
11998       }
11999     }
12000     return;
12001   }
12002 
12003   // Valid casts involving fixed point types should be accounted for here.
12004   if (Source->isFixedPointType()) {
12005     if (Target->isUnsaturatedFixedPointType()) {
12006       Expr::EvalResult Result;
12007       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12008                                   S.isConstantEvaluated())) {
12009         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12010         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12011         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12012         if (Value > MaxVal || Value < MinVal) {
12013           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12014                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12015                                     << Value.toString() << T
12016                                     << E->getSourceRange()
12017                                     << clang::SourceRange(CC));
12018           return;
12019         }
12020       }
12021     } else if (Target->isIntegerType()) {
12022       Expr::EvalResult Result;
12023       if (!S.isConstantEvaluated() &&
12024           E->EvaluateAsFixedPoint(Result, S.Context,
12025                                   Expr::SE_AllowSideEffects)) {
12026         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12027 
12028         bool Overflowed;
12029         llvm::APSInt IntResult = FXResult.convertToInt(
12030             S.Context.getIntWidth(T),
12031             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12032 
12033         if (Overflowed) {
12034           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12035                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12036                                     << FXResult.toString() << T
12037                                     << E->getSourceRange()
12038                                     << clang::SourceRange(CC));
12039           return;
12040         }
12041       }
12042     }
12043   } else if (Target->isUnsaturatedFixedPointType()) {
12044     if (Source->isIntegerType()) {
12045       Expr::EvalResult Result;
12046       if (!S.isConstantEvaluated() &&
12047           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12048         llvm::APSInt Value = Result.Val.getInt();
12049 
12050         bool Overflowed;
12051         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12052             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12053 
12054         if (Overflowed) {
12055           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12056                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12057                                     << Value.toString(/*Radix=*/10) << T
12058                                     << E->getSourceRange()
12059                                     << clang::SourceRange(CC));
12060           return;
12061         }
12062       }
12063     }
12064   }
12065 
12066   // If we are casting an integer type to a floating point type without
12067   // initialization-list syntax, we might lose accuracy if the floating
12068   // point type has a narrower significand than the integer type.
12069   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12070       TargetBT->isFloatingType() && !IsListInit) {
12071     // Determine the number of precision bits in the source integer type.
12072     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12073                                         /*Approximate*/ true);
12074     unsigned int SourcePrecision = SourceRange.Width;
12075 
12076     // Determine the number of precision bits in the
12077     // target floating point type.
12078     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12079         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12080 
12081     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12082         SourcePrecision > TargetPrecision) {
12083 
12084       if (Optional<llvm::APSInt> SourceInt =
12085               E->getIntegerConstantExpr(S.Context)) {
12086         // If the source integer is a constant, convert it to the target
12087         // floating point type. Issue a warning if the value changes
12088         // during the whole conversion.
12089         llvm::APFloat TargetFloatValue(
12090             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12091         llvm::APFloat::opStatus ConversionStatus =
12092             TargetFloatValue.convertFromAPInt(
12093                 *SourceInt, SourceBT->isSignedInteger(),
12094                 llvm::APFloat::rmNearestTiesToEven);
12095 
12096         if (ConversionStatus != llvm::APFloat::opOK) {
12097           std::string PrettySourceValue = SourceInt->toString(10);
12098           SmallString<32> PrettyTargetValue;
12099           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12100 
12101           S.DiagRuntimeBehavior(
12102               E->getExprLoc(), E,
12103               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12104                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12105                   << E->getSourceRange() << clang::SourceRange(CC));
12106         }
12107       } else {
12108         // Otherwise, the implicit conversion may lose precision.
12109         DiagnoseImpCast(S, E, T, CC,
12110                         diag::warn_impcast_integer_float_precision);
12111       }
12112     }
12113   }
12114 
12115   DiagnoseNullConversion(S, E, T, CC);
12116 
12117   S.DiscardMisalignedMemberAddress(Target, E);
12118 
12119   if (Target->isBooleanType())
12120     DiagnoseIntInBoolContext(S, E);
12121 
12122   if (!Source->isIntegerType() || !Target->isIntegerType())
12123     return;
12124 
12125   // TODO: remove this early return once the false positives for constant->bool
12126   // in templates, macros, etc, are reduced or removed.
12127   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12128     return;
12129 
12130   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12131       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12132     return adornObjCBoolConversionDiagWithTernaryFixit(
12133         S, E,
12134         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12135             << E->getType());
12136   }
12137 
12138   IntRange SourceTypeRange =
12139       IntRange::forTargetOfCanonicalType(S.Context, Source);
12140   IntRange LikelySourceRange =
12141       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12142   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12143 
12144   if (LikelySourceRange.Width > TargetRange.Width) {
12145     // If the source is a constant, use a default-on diagnostic.
12146     // TODO: this should happen for bitfield stores, too.
12147     Expr::EvalResult Result;
12148     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12149                          S.isConstantEvaluated())) {
12150       llvm::APSInt Value(32);
12151       Value = Result.Val.getInt();
12152 
12153       if (S.SourceMgr.isInSystemMacro(CC))
12154         return;
12155 
12156       std::string PrettySourceValue = Value.toString(10);
12157       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12158 
12159       S.DiagRuntimeBehavior(
12160           E->getExprLoc(), E,
12161           S.PDiag(diag::warn_impcast_integer_precision_constant)
12162               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12163               << E->getSourceRange() << SourceRange(CC));
12164       return;
12165     }
12166 
12167     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12168     if (S.SourceMgr.isInSystemMacro(CC))
12169       return;
12170 
12171     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12172       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12173                              /* pruneControlFlow */ true);
12174     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12175   }
12176 
12177   if (TargetRange.Width > SourceTypeRange.Width) {
12178     if (auto *UO = dyn_cast<UnaryOperator>(E))
12179       if (UO->getOpcode() == UO_Minus)
12180         if (Source->isUnsignedIntegerType()) {
12181           if (Target->isUnsignedIntegerType())
12182             return DiagnoseImpCast(S, E, T, CC,
12183                                    diag::warn_impcast_high_order_zero_bits);
12184           if (Target->isSignedIntegerType())
12185             return DiagnoseImpCast(S, E, T, CC,
12186                                    diag::warn_impcast_nonnegative_result);
12187         }
12188   }
12189 
12190   if (TargetRange.Width == LikelySourceRange.Width &&
12191       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12192       Source->isSignedIntegerType()) {
12193     // Warn when doing a signed to signed conversion, warn if the positive
12194     // source value is exactly the width of the target type, which will
12195     // cause a negative value to be stored.
12196 
12197     Expr::EvalResult Result;
12198     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12199         !S.SourceMgr.isInSystemMacro(CC)) {
12200       llvm::APSInt Value = Result.Val.getInt();
12201       if (isSameWidthConstantConversion(S, E, T, CC)) {
12202         std::string PrettySourceValue = Value.toString(10);
12203         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12204 
12205         S.DiagRuntimeBehavior(
12206             E->getExprLoc(), E,
12207             S.PDiag(diag::warn_impcast_integer_precision_constant)
12208                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12209                 << E->getSourceRange() << SourceRange(CC));
12210         return;
12211       }
12212     }
12213 
12214     // Fall through for non-constants to give a sign conversion warning.
12215   }
12216 
12217   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12218       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12219        LikelySourceRange.Width == TargetRange.Width)) {
12220     if (S.SourceMgr.isInSystemMacro(CC))
12221       return;
12222 
12223     unsigned DiagID = diag::warn_impcast_integer_sign;
12224 
12225     // Traditionally, gcc has warned about this under -Wsign-compare.
12226     // We also want to warn about it in -Wconversion.
12227     // So if -Wconversion is off, use a completely identical diagnostic
12228     // in the sign-compare group.
12229     // The conditional-checking code will
12230     if (ICContext) {
12231       DiagID = diag::warn_impcast_integer_sign_conditional;
12232       *ICContext = true;
12233     }
12234 
12235     return DiagnoseImpCast(S, E, T, CC, DiagID);
12236   }
12237 
12238   // Diagnose conversions between different enumeration types.
12239   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12240   // type, to give us better diagnostics.
12241   QualType SourceType = E->getType();
12242   if (!S.getLangOpts().CPlusPlus) {
12243     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12244       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12245         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12246         SourceType = S.Context.getTypeDeclType(Enum);
12247         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12248       }
12249   }
12250 
12251   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12252     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12253       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12254           TargetEnum->getDecl()->hasNameForLinkage() &&
12255           SourceEnum != TargetEnum) {
12256         if (S.SourceMgr.isInSystemMacro(CC))
12257           return;
12258 
12259         return DiagnoseImpCast(S, E, SourceType, T, CC,
12260                                diag::warn_impcast_different_enum_types);
12261       }
12262 }
12263 
12264 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12265                                      SourceLocation CC, QualType T);
12266 
12267 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12268                                     SourceLocation CC, bool &ICContext) {
12269   E = E->IgnoreParenImpCasts();
12270 
12271   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12272     return CheckConditionalOperator(S, CO, CC, T);
12273 
12274   AnalyzeImplicitConversions(S, E, CC);
12275   if (E->getType() != T)
12276     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12277 }
12278 
12279 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12280                                      SourceLocation CC, QualType T) {
12281   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12282 
12283   Expr *TrueExpr = E->getTrueExpr();
12284   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12285     TrueExpr = BCO->getCommon();
12286 
12287   bool Suspicious = false;
12288   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12289   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12290 
12291   if (T->isBooleanType())
12292     DiagnoseIntInBoolContext(S, E);
12293 
12294   // If -Wconversion would have warned about either of the candidates
12295   // for a signedness conversion to the context type...
12296   if (!Suspicious) return;
12297 
12298   // ...but it's currently ignored...
12299   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12300     return;
12301 
12302   // ...then check whether it would have warned about either of the
12303   // candidates for a signedness conversion to the condition type.
12304   if (E->getType() == T) return;
12305 
12306   Suspicious = false;
12307   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12308                           E->getType(), CC, &Suspicious);
12309   if (!Suspicious)
12310     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12311                             E->getType(), CC, &Suspicious);
12312 }
12313 
12314 /// Check conversion of given expression to boolean.
12315 /// Input argument E is a logical expression.
12316 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12317   if (S.getLangOpts().Bool)
12318     return;
12319   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12320     return;
12321   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12322 }
12323 
12324 namespace {
12325 struct AnalyzeImplicitConversionsWorkItem {
12326   Expr *E;
12327   SourceLocation CC;
12328   bool IsListInit;
12329 };
12330 }
12331 
12332 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12333 /// that should be visited are added to WorkList.
12334 static void AnalyzeImplicitConversions(
12335     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12336     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12337   Expr *OrigE = Item.E;
12338   SourceLocation CC = Item.CC;
12339 
12340   QualType T = OrigE->getType();
12341   Expr *E = OrigE->IgnoreParenImpCasts();
12342 
12343   // Propagate whether we are in a C++ list initialization expression.
12344   // If so, we do not issue warnings for implicit int-float conversion
12345   // precision loss, because C++11 narrowing already handles it.
12346   bool IsListInit = Item.IsListInit ||
12347                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12348 
12349   if (E->isTypeDependent() || E->isValueDependent())
12350     return;
12351 
12352   Expr *SourceExpr = E;
12353   // Examine, but don't traverse into the source expression of an
12354   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12355   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12356   // evaluate it in the context of checking the specific conversion to T though.
12357   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12358     if (auto *Src = OVE->getSourceExpr())
12359       SourceExpr = Src;
12360 
12361   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12362     if (UO->getOpcode() == UO_Not &&
12363         UO->getSubExpr()->isKnownToHaveBooleanValue())
12364       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12365           << OrigE->getSourceRange() << T->isBooleanType()
12366           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12367 
12368   // For conditional operators, we analyze the arguments as if they
12369   // were being fed directly into the output.
12370   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12371     CheckConditionalOperator(S, CO, CC, T);
12372     return;
12373   }
12374 
12375   // Check implicit argument conversions for function calls.
12376   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12377     CheckImplicitArgumentConversions(S, Call, CC);
12378 
12379   // Go ahead and check any implicit conversions we might have skipped.
12380   // The non-canonical typecheck is just an optimization;
12381   // CheckImplicitConversion will filter out dead implicit conversions.
12382   if (SourceExpr->getType() != T)
12383     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12384 
12385   // Now continue drilling into this expression.
12386 
12387   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12388     // The bound subexpressions in a PseudoObjectExpr are not reachable
12389     // as transitive children.
12390     // FIXME: Use a more uniform representation for this.
12391     for (auto *SE : POE->semantics())
12392       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12393         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12394   }
12395 
12396   // Skip past explicit casts.
12397   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12398     E = CE->getSubExpr()->IgnoreParenImpCasts();
12399     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12400       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12401     WorkList.push_back({E, CC, IsListInit});
12402     return;
12403   }
12404 
12405   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12406     // Do a somewhat different check with comparison operators.
12407     if (BO->isComparisonOp())
12408       return AnalyzeComparison(S, BO);
12409 
12410     // And with simple assignments.
12411     if (BO->getOpcode() == BO_Assign)
12412       return AnalyzeAssignment(S, BO);
12413     // And with compound assignments.
12414     if (BO->isAssignmentOp())
12415       return AnalyzeCompoundAssignment(S, BO);
12416   }
12417 
12418   // These break the otherwise-useful invariant below.  Fortunately,
12419   // we don't really need to recurse into them, because any internal
12420   // expressions should have been analyzed already when they were
12421   // built into statements.
12422   if (isa<StmtExpr>(E)) return;
12423 
12424   // Don't descend into unevaluated contexts.
12425   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12426 
12427   // Now just recurse over the expression's children.
12428   CC = E->getExprLoc();
12429   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12430   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12431   for (Stmt *SubStmt : E->children()) {
12432     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12433     if (!ChildExpr)
12434       continue;
12435 
12436     if (IsLogicalAndOperator &&
12437         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12438       // Ignore checking string literals that are in logical and operators.
12439       // This is a common pattern for asserts.
12440       continue;
12441     WorkList.push_back({ChildExpr, CC, IsListInit});
12442   }
12443 
12444   if (BO && BO->isLogicalOp()) {
12445     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12446     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12447       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12448 
12449     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12450     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12451       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12452   }
12453 
12454   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12455     if (U->getOpcode() == UO_LNot) {
12456       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12457     } else if (U->getOpcode() != UO_AddrOf) {
12458       if (U->getSubExpr()->getType()->isAtomicType())
12459         S.Diag(U->getSubExpr()->getBeginLoc(),
12460                diag::warn_atomic_implicit_seq_cst);
12461     }
12462   }
12463 }
12464 
12465 /// AnalyzeImplicitConversions - Find and report any interesting
12466 /// implicit conversions in the given expression.  There are a couple
12467 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12468 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12469                                        bool IsListInit/*= false*/) {
12470   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12471   WorkList.push_back({OrigE, CC, IsListInit});
12472   while (!WorkList.empty())
12473     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12474 }
12475 
12476 /// Diagnose integer type and any valid implicit conversion to it.
12477 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12478   // Taking into account implicit conversions,
12479   // allow any integer.
12480   if (!E->getType()->isIntegerType()) {
12481     S.Diag(E->getBeginLoc(),
12482            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12483     return true;
12484   }
12485   // Potentially emit standard warnings for implicit conversions if enabled
12486   // using -Wconversion.
12487   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12488   return false;
12489 }
12490 
12491 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12492 // Returns true when emitting a warning about taking the address of a reference.
12493 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12494                               const PartialDiagnostic &PD) {
12495   E = E->IgnoreParenImpCasts();
12496 
12497   const FunctionDecl *FD = nullptr;
12498 
12499   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12500     if (!DRE->getDecl()->getType()->isReferenceType())
12501       return false;
12502   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12503     if (!M->getMemberDecl()->getType()->isReferenceType())
12504       return false;
12505   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12506     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12507       return false;
12508     FD = Call->getDirectCallee();
12509   } else {
12510     return false;
12511   }
12512 
12513   SemaRef.Diag(E->getExprLoc(), PD);
12514 
12515   // If possible, point to location of function.
12516   if (FD) {
12517     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12518   }
12519 
12520   return true;
12521 }
12522 
12523 // Returns true if the SourceLocation is expanded from any macro body.
12524 // Returns false if the SourceLocation is invalid, is from not in a macro
12525 // expansion, or is from expanded from a top-level macro argument.
12526 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12527   if (Loc.isInvalid())
12528     return false;
12529 
12530   while (Loc.isMacroID()) {
12531     if (SM.isMacroBodyExpansion(Loc))
12532       return true;
12533     Loc = SM.getImmediateMacroCallerLoc(Loc);
12534   }
12535 
12536   return false;
12537 }
12538 
12539 /// Diagnose pointers that are always non-null.
12540 /// \param E the expression containing the pointer
12541 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12542 /// compared to a null pointer
12543 /// \param IsEqual True when the comparison is equal to a null pointer
12544 /// \param Range Extra SourceRange to highlight in the diagnostic
12545 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12546                                         Expr::NullPointerConstantKind NullKind,
12547                                         bool IsEqual, SourceRange Range) {
12548   if (!E)
12549     return;
12550 
12551   // Don't warn inside macros.
12552   if (E->getExprLoc().isMacroID()) {
12553     const SourceManager &SM = getSourceManager();
12554     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12555         IsInAnyMacroBody(SM, Range.getBegin()))
12556       return;
12557   }
12558   E = E->IgnoreImpCasts();
12559 
12560   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12561 
12562   if (isa<CXXThisExpr>(E)) {
12563     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12564                                 : diag::warn_this_bool_conversion;
12565     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12566     return;
12567   }
12568 
12569   bool IsAddressOf = false;
12570 
12571   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12572     if (UO->getOpcode() != UO_AddrOf)
12573       return;
12574     IsAddressOf = true;
12575     E = UO->getSubExpr();
12576   }
12577 
12578   if (IsAddressOf) {
12579     unsigned DiagID = IsCompare
12580                           ? diag::warn_address_of_reference_null_compare
12581                           : diag::warn_address_of_reference_bool_conversion;
12582     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12583                                          << IsEqual;
12584     if (CheckForReference(*this, E, PD)) {
12585       return;
12586     }
12587   }
12588 
12589   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12590     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12591     std::string Str;
12592     llvm::raw_string_ostream S(Str);
12593     E->printPretty(S, nullptr, getPrintingPolicy());
12594     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12595                                 : diag::warn_cast_nonnull_to_bool;
12596     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12597       << E->getSourceRange() << Range << IsEqual;
12598     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12599   };
12600 
12601   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12602   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12603     if (auto *Callee = Call->getDirectCallee()) {
12604       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12605         ComplainAboutNonnullParamOrCall(A);
12606         return;
12607       }
12608     }
12609   }
12610 
12611   // Expect to find a single Decl.  Skip anything more complicated.
12612   ValueDecl *D = nullptr;
12613   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12614     D = R->getDecl();
12615   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12616     D = M->getMemberDecl();
12617   }
12618 
12619   // Weak Decls can be null.
12620   if (!D || D->isWeak())
12621     return;
12622 
12623   // Check for parameter decl with nonnull attribute
12624   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12625     if (getCurFunction() &&
12626         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12627       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12628         ComplainAboutNonnullParamOrCall(A);
12629         return;
12630       }
12631 
12632       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12633         // Skip function template not specialized yet.
12634         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12635           return;
12636         auto ParamIter = llvm::find(FD->parameters(), PV);
12637         assert(ParamIter != FD->param_end());
12638         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12639 
12640         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12641           if (!NonNull->args_size()) {
12642               ComplainAboutNonnullParamOrCall(NonNull);
12643               return;
12644           }
12645 
12646           for (const ParamIdx &ArgNo : NonNull->args()) {
12647             if (ArgNo.getASTIndex() == ParamNo) {
12648               ComplainAboutNonnullParamOrCall(NonNull);
12649               return;
12650             }
12651           }
12652         }
12653       }
12654     }
12655   }
12656 
12657   QualType T = D->getType();
12658   const bool IsArray = T->isArrayType();
12659   const bool IsFunction = T->isFunctionType();
12660 
12661   // Address of function is used to silence the function warning.
12662   if (IsAddressOf && IsFunction) {
12663     return;
12664   }
12665 
12666   // Found nothing.
12667   if (!IsAddressOf && !IsFunction && !IsArray)
12668     return;
12669 
12670   // Pretty print the expression for the diagnostic.
12671   std::string Str;
12672   llvm::raw_string_ostream S(Str);
12673   E->printPretty(S, nullptr, getPrintingPolicy());
12674 
12675   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12676                               : diag::warn_impcast_pointer_to_bool;
12677   enum {
12678     AddressOf,
12679     FunctionPointer,
12680     ArrayPointer
12681   } DiagType;
12682   if (IsAddressOf)
12683     DiagType = AddressOf;
12684   else if (IsFunction)
12685     DiagType = FunctionPointer;
12686   else if (IsArray)
12687     DiagType = ArrayPointer;
12688   else
12689     llvm_unreachable("Could not determine diagnostic.");
12690   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12691                                 << Range << IsEqual;
12692 
12693   if (!IsFunction)
12694     return;
12695 
12696   // Suggest '&' to silence the function warning.
12697   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12698       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12699 
12700   // Check to see if '()' fixit should be emitted.
12701   QualType ReturnType;
12702   UnresolvedSet<4> NonTemplateOverloads;
12703   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12704   if (ReturnType.isNull())
12705     return;
12706 
12707   if (IsCompare) {
12708     // There are two cases here.  If there is null constant, the only suggest
12709     // for a pointer return type.  If the null is 0, then suggest if the return
12710     // type is a pointer or an integer type.
12711     if (!ReturnType->isPointerType()) {
12712       if (NullKind == Expr::NPCK_ZeroExpression ||
12713           NullKind == Expr::NPCK_ZeroLiteral) {
12714         if (!ReturnType->isIntegerType())
12715           return;
12716       } else {
12717         return;
12718       }
12719     }
12720   } else { // !IsCompare
12721     // For function to bool, only suggest if the function pointer has bool
12722     // return type.
12723     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12724       return;
12725   }
12726   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12727       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12728 }
12729 
12730 /// Diagnoses "dangerous" implicit conversions within the given
12731 /// expression (which is a full expression).  Implements -Wconversion
12732 /// and -Wsign-compare.
12733 ///
12734 /// \param CC the "context" location of the implicit conversion, i.e.
12735 ///   the most location of the syntactic entity requiring the implicit
12736 ///   conversion
12737 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12738   // Don't diagnose in unevaluated contexts.
12739   if (isUnevaluatedContext())
12740     return;
12741 
12742   // Don't diagnose for value- or type-dependent expressions.
12743   if (E->isTypeDependent() || E->isValueDependent())
12744     return;
12745 
12746   // Check for array bounds violations in cases where the check isn't triggered
12747   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12748   // ArraySubscriptExpr is on the RHS of a variable initialization.
12749   CheckArrayAccess(E);
12750 
12751   // This is not the right CC for (e.g.) a variable initialization.
12752   AnalyzeImplicitConversions(*this, E, CC);
12753 }
12754 
12755 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12756 /// Input argument E is a logical expression.
12757 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12758   ::CheckBoolLikeConversion(*this, E, CC);
12759 }
12760 
12761 /// Diagnose when expression is an integer constant expression and its evaluation
12762 /// results in integer overflow
12763 void Sema::CheckForIntOverflow (Expr *E) {
12764   // Use a work list to deal with nested struct initializers.
12765   SmallVector<Expr *, 2> Exprs(1, E);
12766 
12767   do {
12768     Expr *OriginalE = Exprs.pop_back_val();
12769     Expr *E = OriginalE->IgnoreParenCasts();
12770 
12771     if (isa<BinaryOperator>(E)) {
12772       E->EvaluateForOverflow(Context);
12773       continue;
12774     }
12775 
12776     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12777       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12778     else if (isa<ObjCBoxedExpr>(OriginalE))
12779       E->EvaluateForOverflow(Context);
12780     else if (auto Call = dyn_cast<CallExpr>(E))
12781       Exprs.append(Call->arg_begin(), Call->arg_end());
12782     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12783       Exprs.append(Message->arg_begin(), Message->arg_end());
12784   } while (!Exprs.empty());
12785 }
12786 
12787 namespace {
12788 
12789 /// Visitor for expressions which looks for unsequenced operations on the
12790 /// same object.
12791 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12792   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12793 
12794   /// A tree of sequenced regions within an expression. Two regions are
12795   /// unsequenced if one is an ancestor or a descendent of the other. When we
12796   /// finish processing an expression with sequencing, such as a comma
12797   /// expression, we fold its tree nodes into its parent, since they are
12798   /// unsequenced with respect to nodes we will visit later.
12799   class SequenceTree {
12800     struct Value {
12801       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12802       unsigned Parent : 31;
12803       unsigned Merged : 1;
12804     };
12805     SmallVector<Value, 8> Values;
12806 
12807   public:
12808     /// A region within an expression which may be sequenced with respect
12809     /// to some other region.
12810     class Seq {
12811       friend class SequenceTree;
12812 
12813       unsigned Index;
12814 
12815       explicit Seq(unsigned N) : Index(N) {}
12816 
12817     public:
12818       Seq() : Index(0) {}
12819     };
12820 
12821     SequenceTree() { Values.push_back(Value(0)); }
12822     Seq root() const { return Seq(0); }
12823 
12824     /// Create a new sequence of operations, which is an unsequenced
12825     /// subset of \p Parent. This sequence of operations is sequenced with
12826     /// respect to other children of \p Parent.
12827     Seq allocate(Seq Parent) {
12828       Values.push_back(Value(Parent.Index));
12829       return Seq(Values.size() - 1);
12830     }
12831 
12832     /// Merge a sequence of operations into its parent.
12833     void merge(Seq S) {
12834       Values[S.Index].Merged = true;
12835     }
12836 
12837     /// Determine whether two operations are unsequenced. This operation
12838     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12839     /// should have been merged into its parent as appropriate.
12840     bool isUnsequenced(Seq Cur, Seq Old) {
12841       unsigned C = representative(Cur.Index);
12842       unsigned Target = representative(Old.Index);
12843       while (C >= Target) {
12844         if (C == Target)
12845           return true;
12846         C = Values[C].Parent;
12847       }
12848       return false;
12849     }
12850 
12851   private:
12852     /// Pick a representative for a sequence.
12853     unsigned representative(unsigned K) {
12854       if (Values[K].Merged)
12855         // Perform path compression as we go.
12856         return Values[K].Parent = representative(Values[K].Parent);
12857       return K;
12858     }
12859   };
12860 
12861   /// An object for which we can track unsequenced uses.
12862   using Object = const NamedDecl *;
12863 
12864   /// Different flavors of object usage which we track. We only track the
12865   /// least-sequenced usage of each kind.
12866   enum UsageKind {
12867     /// A read of an object. Multiple unsequenced reads are OK.
12868     UK_Use,
12869 
12870     /// A modification of an object which is sequenced before the value
12871     /// computation of the expression, such as ++n in C++.
12872     UK_ModAsValue,
12873 
12874     /// A modification of an object which is not sequenced before the value
12875     /// computation of the expression, such as n++.
12876     UK_ModAsSideEffect,
12877 
12878     UK_Count = UK_ModAsSideEffect + 1
12879   };
12880 
12881   /// Bundle together a sequencing region and the expression corresponding
12882   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12883   struct Usage {
12884     const Expr *UsageExpr;
12885     SequenceTree::Seq Seq;
12886 
12887     Usage() : UsageExpr(nullptr), Seq() {}
12888   };
12889 
12890   struct UsageInfo {
12891     Usage Uses[UK_Count];
12892 
12893     /// Have we issued a diagnostic for this object already?
12894     bool Diagnosed;
12895 
12896     UsageInfo() : Uses(), Diagnosed(false) {}
12897   };
12898   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12899 
12900   Sema &SemaRef;
12901 
12902   /// Sequenced regions within the expression.
12903   SequenceTree Tree;
12904 
12905   /// Declaration modifications and references which we have seen.
12906   UsageInfoMap UsageMap;
12907 
12908   /// The region we are currently within.
12909   SequenceTree::Seq Region;
12910 
12911   /// Filled in with declarations which were modified as a side-effect
12912   /// (that is, post-increment operations).
12913   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12914 
12915   /// Expressions to check later. We defer checking these to reduce
12916   /// stack usage.
12917   SmallVectorImpl<const Expr *> &WorkList;
12918 
12919   /// RAII object wrapping the visitation of a sequenced subexpression of an
12920   /// expression. At the end of this process, the side-effects of the evaluation
12921   /// become sequenced with respect to the value computation of the result, so
12922   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12923   /// UK_ModAsValue.
12924   struct SequencedSubexpression {
12925     SequencedSubexpression(SequenceChecker &Self)
12926       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12927       Self.ModAsSideEffect = &ModAsSideEffect;
12928     }
12929 
12930     ~SequencedSubexpression() {
12931       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12932         // Add a new usage with usage kind UK_ModAsValue, and then restore
12933         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12934         // the previous one was empty).
12935         UsageInfo &UI = Self.UsageMap[M.first];
12936         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12937         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12938         SideEffectUsage = M.second;
12939       }
12940       Self.ModAsSideEffect = OldModAsSideEffect;
12941     }
12942 
12943     SequenceChecker &Self;
12944     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12945     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12946   };
12947 
12948   /// RAII object wrapping the visitation of a subexpression which we might
12949   /// choose to evaluate as a constant. If any subexpression is evaluated and
12950   /// found to be non-constant, this allows us to suppress the evaluation of
12951   /// the outer expression.
12952   class EvaluationTracker {
12953   public:
12954     EvaluationTracker(SequenceChecker &Self)
12955         : Self(Self), Prev(Self.EvalTracker) {
12956       Self.EvalTracker = this;
12957     }
12958 
12959     ~EvaluationTracker() {
12960       Self.EvalTracker = Prev;
12961       if (Prev)
12962         Prev->EvalOK &= EvalOK;
12963     }
12964 
12965     bool evaluate(const Expr *E, bool &Result) {
12966       if (!EvalOK || E->isValueDependent())
12967         return false;
12968       EvalOK = E->EvaluateAsBooleanCondition(
12969           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12970       return EvalOK;
12971     }
12972 
12973   private:
12974     SequenceChecker &Self;
12975     EvaluationTracker *Prev;
12976     bool EvalOK = true;
12977   } *EvalTracker = nullptr;
12978 
12979   /// Find the object which is produced by the specified expression,
12980   /// if any.
12981   Object getObject(const Expr *E, bool Mod) const {
12982     E = E->IgnoreParenCasts();
12983     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12984       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12985         return getObject(UO->getSubExpr(), Mod);
12986     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12987       if (BO->getOpcode() == BO_Comma)
12988         return getObject(BO->getRHS(), Mod);
12989       if (Mod && BO->isAssignmentOp())
12990         return getObject(BO->getLHS(), Mod);
12991     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12992       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12993       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12994         return ME->getMemberDecl();
12995     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12996       // FIXME: If this is a reference, map through to its value.
12997       return DRE->getDecl();
12998     return nullptr;
12999   }
13000 
13001   /// Note that an object \p O was modified or used by an expression
13002   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13003   /// the object \p O as obtained via the \p UsageMap.
13004   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13005     // Get the old usage for the given object and usage kind.
13006     Usage &U = UI.Uses[UK];
13007     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13008       // If we have a modification as side effect and are in a sequenced
13009       // subexpression, save the old Usage so that we can restore it later
13010       // in SequencedSubexpression::~SequencedSubexpression.
13011       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13012         ModAsSideEffect->push_back(std::make_pair(O, U));
13013       // Then record the new usage with the current sequencing region.
13014       U.UsageExpr = UsageExpr;
13015       U.Seq = Region;
13016     }
13017   }
13018 
13019   /// Check whether a modification or use of an object \p O in an expression
13020   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13021   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13022   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13023   /// usage and false we are checking for a mod-use unsequenced usage.
13024   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13025                   UsageKind OtherKind, bool IsModMod) {
13026     if (UI.Diagnosed)
13027       return;
13028 
13029     const Usage &U = UI.Uses[OtherKind];
13030     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13031       return;
13032 
13033     const Expr *Mod = U.UsageExpr;
13034     const Expr *ModOrUse = UsageExpr;
13035     if (OtherKind == UK_Use)
13036       std::swap(Mod, ModOrUse);
13037 
13038     SemaRef.DiagRuntimeBehavior(
13039         Mod->getExprLoc(), {Mod, ModOrUse},
13040         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13041                                : diag::warn_unsequenced_mod_use)
13042             << O << SourceRange(ModOrUse->getExprLoc()));
13043     UI.Diagnosed = true;
13044   }
13045 
13046   // A note on note{Pre, Post}{Use, Mod}:
13047   //
13048   // (It helps to follow the algorithm with an expression such as
13049   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13050   //  operations before C++17 and both are well-defined in C++17).
13051   //
13052   // When visiting a node which uses/modify an object we first call notePreUse
13053   // or notePreMod before visiting its sub-expression(s). At this point the
13054   // children of the current node have not yet been visited and so the eventual
13055   // uses/modifications resulting from the children of the current node have not
13056   // been recorded yet.
13057   //
13058   // We then visit the children of the current node. After that notePostUse or
13059   // notePostMod is called. These will 1) detect an unsequenced modification
13060   // as side effect (as in "k++ + k") and 2) add a new usage with the
13061   // appropriate usage kind.
13062   //
13063   // We also have to be careful that some operation sequences modification as
13064   // side effect as well (for example: || or ,). To account for this we wrap
13065   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13066   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13067   // which record usages which are modifications as side effect, and then
13068   // downgrade them (or more accurately restore the previous usage which was a
13069   // modification as side effect) when exiting the scope of the sequenced
13070   // subexpression.
13071 
13072   void notePreUse(Object O, const Expr *UseExpr) {
13073     UsageInfo &UI = UsageMap[O];
13074     // Uses conflict with other modifications.
13075     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13076   }
13077 
13078   void notePostUse(Object O, const Expr *UseExpr) {
13079     UsageInfo &UI = UsageMap[O];
13080     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13081                /*IsModMod=*/false);
13082     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13083   }
13084 
13085   void notePreMod(Object O, const Expr *ModExpr) {
13086     UsageInfo &UI = UsageMap[O];
13087     // Modifications conflict with other modifications and with uses.
13088     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13089     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13090   }
13091 
13092   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13093     UsageInfo &UI = UsageMap[O];
13094     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13095                /*IsModMod=*/true);
13096     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13097   }
13098 
13099 public:
13100   SequenceChecker(Sema &S, const Expr *E,
13101                   SmallVectorImpl<const Expr *> &WorkList)
13102       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13103     Visit(E);
13104     // Silence a -Wunused-private-field since WorkList is now unused.
13105     // TODO: Evaluate if it can be used, and if not remove it.
13106     (void)this->WorkList;
13107   }
13108 
13109   void VisitStmt(const Stmt *S) {
13110     // Skip all statements which aren't expressions for now.
13111   }
13112 
13113   void VisitExpr(const Expr *E) {
13114     // By default, just recurse to evaluated subexpressions.
13115     Base::VisitStmt(E);
13116   }
13117 
13118   void VisitCastExpr(const CastExpr *E) {
13119     Object O = Object();
13120     if (E->getCastKind() == CK_LValueToRValue)
13121       O = getObject(E->getSubExpr(), false);
13122 
13123     if (O)
13124       notePreUse(O, E);
13125     VisitExpr(E);
13126     if (O)
13127       notePostUse(O, E);
13128   }
13129 
13130   void VisitSequencedExpressions(const Expr *SequencedBefore,
13131                                  const Expr *SequencedAfter) {
13132     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13133     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13134     SequenceTree::Seq OldRegion = Region;
13135 
13136     {
13137       SequencedSubexpression SeqBefore(*this);
13138       Region = BeforeRegion;
13139       Visit(SequencedBefore);
13140     }
13141 
13142     Region = AfterRegion;
13143     Visit(SequencedAfter);
13144 
13145     Region = OldRegion;
13146 
13147     Tree.merge(BeforeRegion);
13148     Tree.merge(AfterRegion);
13149   }
13150 
13151   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13152     // C++17 [expr.sub]p1:
13153     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13154     //   expression E1 is sequenced before the expression E2.
13155     if (SemaRef.getLangOpts().CPlusPlus17)
13156       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13157     else {
13158       Visit(ASE->getLHS());
13159       Visit(ASE->getRHS());
13160     }
13161   }
13162 
13163   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13164   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13165   void VisitBinPtrMem(const BinaryOperator *BO) {
13166     // C++17 [expr.mptr.oper]p4:
13167     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13168     //  the expression E1 is sequenced before the expression E2.
13169     if (SemaRef.getLangOpts().CPlusPlus17)
13170       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13171     else {
13172       Visit(BO->getLHS());
13173       Visit(BO->getRHS());
13174     }
13175   }
13176 
13177   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13178   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13179   void VisitBinShlShr(const BinaryOperator *BO) {
13180     // C++17 [expr.shift]p4:
13181     //  The expression E1 is sequenced before the expression E2.
13182     if (SemaRef.getLangOpts().CPlusPlus17)
13183       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13184     else {
13185       Visit(BO->getLHS());
13186       Visit(BO->getRHS());
13187     }
13188   }
13189 
13190   void VisitBinComma(const BinaryOperator *BO) {
13191     // C++11 [expr.comma]p1:
13192     //   Every value computation and side effect associated with the left
13193     //   expression is sequenced before every value computation and side
13194     //   effect associated with the right expression.
13195     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13196   }
13197 
13198   void VisitBinAssign(const BinaryOperator *BO) {
13199     SequenceTree::Seq RHSRegion;
13200     SequenceTree::Seq LHSRegion;
13201     if (SemaRef.getLangOpts().CPlusPlus17) {
13202       RHSRegion = Tree.allocate(Region);
13203       LHSRegion = Tree.allocate(Region);
13204     } else {
13205       RHSRegion = Region;
13206       LHSRegion = Region;
13207     }
13208     SequenceTree::Seq OldRegion = Region;
13209 
13210     // C++11 [expr.ass]p1:
13211     //  [...] the assignment is sequenced after the value computation
13212     //  of the right and left operands, [...]
13213     //
13214     // so check it before inspecting the operands and update the
13215     // map afterwards.
13216     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13217     if (O)
13218       notePreMod(O, BO);
13219 
13220     if (SemaRef.getLangOpts().CPlusPlus17) {
13221       // C++17 [expr.ass]p1:
13222       //  [...] The right operand is sequenced before the left operand. [...]
13223       {
13224         SequencedSubexpression SeqBefore(*this);
13225         Region = RHSRegion;
13226         Visit(BO->getRHS());
13227       }
13228 
13229       Region = LHSRegion;
13230       Visit(BO->getLHS());
13231 
13232       if (O && isa<CompoundAssignOperator>(BO))
13233         notePostUse(O, BO);
13234 
13235     } else {
13236       // C++11 does not specify any sequencing between the LHS and RHS.
13237       Region = LHSRegion;
13238       Visit(BO->getLHS());
13239 
13240       if (O && isa<CompoundAssignOperator>(BO))
13241         notePostUse(O, BO);
13242 
13243       Region = RHSRegion;
13244       Visit(BO->getRHS());
13245     }
13246 
13247     // C++11 [expr.ass]p1:
13248     //  the assignment is sequenced [...] before the value computation of the
13249     //  assignment expression.
13250     // C11 6.5.16/3 has no such rule.
13251     Region = OldRegion;
13252     if (O)
13253       notePostMod(O, BO,
13254                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13255                                                   : UK_ModAsSideEffect);
13256     if (SemaRef.getLangOpts().CPlusPlus17) {
13257       Tree.merge(RHSRegion);
13258       Tree.merge(LHSRegion);
13259     }
13260   }
13261 
13262   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13263     VisitBinAssign(CAO);
13264   }
13265 
13266   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13267   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13268   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13269     Object O = getObject(UO->getSubExpr(), true);
13270     if (!O)
13271       return VisitExpr(UO);
13272 
13273     notePreMod(O, UO);
13274     Visit(UO->getSubExpr());
13275     // C++11 [expr.pre.incr]p1:
13276     //   the expression ++x is equivalent to x+=1
13277     notePostMod(O, UO,
13278                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13279                                                 : UK_ModAsSideEffect);
13280   }
13281 
13282   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13283   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13284   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13285     Object O = getObject(UO->getSubExpr(), true);
13286     if (!O)
13287       return VisitExpr(UO);
13288 
13289     notePreMod(O, UO);
13290     Visit(UO->getSubExpr());
13291     notePostMod(O, UO, UK_ModAsSideEffect);
13292   }
13293 
13294   void VisitBinLOr(const BinaryOperator *BO) {
13295     // C++11 [expr.log.or]p2:
13296     //  If the second expression is evaluated, every value computation and
13297     //  side effect associated with the first expression is sequenced before
13298     //  every value computation and side effect associated with the
13299     //  second expression.
13300     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13301     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13302     SequenceTree::Seq OldRegion = Region;
13303 
13304     EvaluationTracker Eval(*this);
13305     {
13306       SequencedSubexpression Sequenced(*this);
13307       Region = LHSRegion;
13308       Visit(BO->getLHS());
13309     }
13310 
13311     // C++11 [expr.log.or]p1:
13312     //  [...] the second operand is not evaluated if the first operand
13313     //  evaluates to true.
13314     bool EvalResult = false;
13315     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13316     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13317     if (ShouldVisitRHS) {
13318       Region = RHSRegion;
13319       Visit(BO->getRHS());
13320     }
13321 
13322     Region = OldRegion;
13323     Tree.merge(LHSRegion);
13324     Tree.merge(RHSRegion);
13325   }
13326 
13327   void VisitBinLAnd(const BinaryOperator *BO) {
13328     // C++11 [expr.log.and]p2:
13329     //  If the second expression is evaluated, every value computation and
13330     //  side effect associated with the first expression is sequenced before
13331     //  every value computation and side effect associated with the
13332     //  second expression.
13333     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13334     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13335     SequenceTree::Seq OldRegion = Region;
13336 
13337     EvaluationTracker Eval(*this);
13338     {
13339       SequencedSubexpression Sequenced(*this);
13340       Region = LHSRegion;
13341       Visit(BO->getLHS());
13342     }
13343 
13344     // C++11 [expr.log.and]p1:
13345     //  [...] the second operand is not evaluated if the first operand is false.
13346     bool EvalResult = false;
13347     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13348     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13349     if (ShouldVisitRHS) {
13350       Region = RHSRegion;
13351       Visit(BO->getRHS());
13352     }
13353 
13354     Region = OldRegion;
13355     Tree.merge(LHSRegion);
13356     Tree.merge(RHSRegion);
13357   }
13358 
13359   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13360     // C++11 [expr.cond]p1:
13361     //  [...] Every value computation and side effect associated with the first
13362     //  expression is sequenced before every value computation and side effect
13363     //  associated with the second or third expression.
13364     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13365 
13366     // No sequencing is specified between the true and false expression.
13367     // However since exactly one of both is going to be evaluated we can
13368     // consider them to be sequenced. This is needed to avoid warning on
13369     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13370     // both the true and false expressions because we can't evaluate x.
13371     // This will still allow us to detect an expression like (pre C++17)
13372     // "(x ? y += 1 : y += 2) = y".
13373     //
13374     // We don't wrap the visitation of the true and false expression with
13375     // SequencedSubexpression because we don't want to downgrade modifications
13376     // as side effect in the true and false expressions after the visition
13377     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13378     // not warn between the two "y++", but we should warn between the "y++"
13379     // and the "y".
13380     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13381     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13382     SequenceTree::Seq OldRegion = Region;
13383 
13384     EvaluationTracker Eval(*this);
13385     {
13386       SequencedSubexpression Sequenced(*this);
13387       Region = ConditionRegion;
13388       Visit(CO->getCond());
13389     }
13390 
13391     // C++11 [expr.cond]p1:
13392     // [...] The first expression is contextually converted to bool (Clause 4).
13393     // It is evaluated and if it is true, the result of the conditional
13394     // expression is the value of the second expression, otherwise that of the
13395     // third expression. Only one of the second and third expressions is
13396     // evaluated. [...]
13397     bool EvalResult = false;
13398     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13399     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13400     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13401     if (ShouldVisitTrueExpr) {
13402       Region = TrueRegion;
13403       Visit(CO->getTrueExpr());
13404     }
13405     if (ShouldVisitFalseExpr) {
13406       Region = FalseRegion;
13407       Visit(CO->getFalseExpr());
13408     }
13409 
13410     Region = OldRegion;
13411     Tree.merge(ConditionRegion);
13412     Tree.merge(TrueRegion);
13413     Tree.merge(FalseRegion);
13414   }
13415 
13416   void VisitCallExpr(const CallExpr *CE) {
13417     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13418 
13419     if (CE->isUnevaluatedBuiltinCall(Context))
13420       return;
13421 
13422     // C++11 [intro.execution]p15:
13423     //   When calling a function [...], every value computation and side effect
13424     //   associated with any argument expression, or with the postfix expression
13425     //   designating the called function, is sequenced before execution of every
13426     //   expression or statement in the body of the function [and thus before
13427     //   the value computation of its result].
13428     SequencedSubexpression Sequenced(*this);
13429     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13430       // C++17 [expr.call]p5
13431       //   The postfix-expression is sequenced before each expression in the
13432       //   expression-list and any default argument. [...]
13433       SequenceTree::Seq CalleeRegion;
13434       SequenceTree::Seq OtherRegion;
13435       if (SemaRef.getLangOpts().CPlusPlus17) {
13436         CalleeRegion = Tree.allocate(Region);
13437         OtherRegion = Tree.allocate(Region);
13438       } else {
13439         CalleeRegion = Region;
13440         OtherRegion = Region;
13441       }
13442       SequenceTree::Seq OldRegion = Region;
13443 
13444       // Visit the callee expression first.
13445       Region = CalleeRegion;
13446       if (SemaRef.getLangOpts().CPlusPlus17) {
13447         SequencedSubexpression Sequenced(*this);
13448         Visit(CE->getCallee());
13449       } else {
13450         Visit(CE->getCallee());
13451       }
13452 
13453       // Then visit the argument expressions.
13454       Region = OtherRegion;
13455       for (const Expr *Argument : CE->arguments())
13456         Visit(Argument);
13457 
13458       Region = OldRegion;
13459       if (SemaRef.getLangOpts().CPlusPlus17) {
13460         Tree.merge(CalleeRegion);
13461         Tree.merge(OtherRegion);
13462       }
13463     });
13464   }
13465 
13466   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13467     // C++17 [over.match.oper]p2:
13468     //   [...] the operator notation is first transformed to the equivalent
13469     //   function-call notation as summarized in Table 12 (where @ denotes one
13470     //   of the operators covered in the specified subclause). However, the
13471     //   operands are sequenced in the order prescribed for the built-in
13472     //   operator (Clause 8).
13473     //
13474     // From the above only overloaded binary operators and overloaded call
13475     // operators have sequencing rules in C++17 that we need to handle
13476     // separately.
13477     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13478         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13479       return VisitCallExpr(CXXOCE);
13480 
13481     enum {
13482       NoSequencing,
13483       LHSBeforeRHS,
13484       RHSBeforeLHS,
13485       LHSBeforeRest
13486     } SequencingKind;
13487     switch (CXXOCE->getOperator()) {
13488     case OO_Equal:
13489     case OO_PlusEqual:
13490     case OO_MinusEqual:
13491     case OO_StarEqual:
13492     case OO_SlashEqual:
13493     case OO_PercentEqual:
13494     case OO_CaretEqual:
13495     case OO_AmpEqual:
13496     case OO_PipeEqual:
13497     case OO_LessLessEqual:
13498     case OO_GreaterGreaterEqual:
13499       SequencingKind = RHSBeforeLHS;
13500       break;
13501 
13502     case OO_LessLess:
13503     case OO_GreaterGreater:
13504     case OO_AmpAmp:
13505     case OO_PipePipe:
13506     case OO_Comma:
13507     case OO_ArrowStar:
13508     case OO_Subscript:
13509       SequencingKind = LHSBeforeRHS;
13510       break;
13511 
13512     case OO_Call:
13513       SequencingKind = LHSBeforeRest;
13514       break;
13515 
13516     default:
13517       SequencingKind = NoSequencing;
13518       break;
13519     }
13520 
13521     if (SequencingKind == NoSequencing)
13522       return VisitCallExpr(CXXOCE);
13523 
13524     // This is a call, so all subexpressions are sequenced before the result.
13525     SequencedSubexpression Sequenced(*this);
13526 
13527     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13528       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13529              "Should only get there with C++17 and above!");
13530       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13531              "Should only get there with an overloaded binary operator"
13532              " or an overloaded call operator!");
13533 
13534       if (SequencingKind == LHSBeforeRest) {
13535         assert(CXXOCE->getOperator() == OO_Call &&
13536                "We should only have an overloaded call operator here!");
13537 
13538         // This is very similar to VisitCallExpr, except that we only have the
13539         // C++17 case. The postfix-expression is the first argument of the
13540         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13541         // are in the following arguments.
13542         //
13543         // Note that we intentionally do not visit the callee expression since
13544         // it is just a decayed reference to a function.
13545         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13546         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13547         SequenceTree::Seq OldRegion = Region;
13548 
13549         assert(CXXOCE->getNumArgs() >= 1 &&
13550                "An overloaded call operator must have at least one argument"
13551                " for the postfix-expression!");
13552         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13553         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13554                                           CXXOCE->getNumArgs() - 1);
13555 
13556         // Visit the postfix-expression first.
13557         {
13558           Region = PostfixExprRegion;
13559           SequencedSubexpression Sequenced(*this);
13560           Visit(PostfixExpr);
13561         }
13562 
13563         // Then visit the argument expressions.
13564         Region = ArgsRegion;
13565         for (const Expr *Arg : Args)
13566           Visit(Arg);
13567 
13568         Region = OldRegion;
13569         Tree.merge(PostfixExprRegion);
13570         Tree.merge(ArgsRegion);
13571       } else {
13572         assert(CXXOCE->getNumArgs() == 2 &&
13573                "Should only have two arguments here!");
13574         assert((SequencingKind == LHSBeforeRHS ||
13575                 SequencingKind == RHSBeforeLHS) &&
13576                "Unexpected sequencing kind!");
13577 
13578         // We do not visit the callee expression since it is just a decayed
13579         // reference to a function.
13580         const Expr *E1 = CXXOCE->getArg(0);
13581         const Expr *E2 = CXXOCE->getArg(1);
13582         if (SequencingKind == RHSBeforeLHS)
13583           std::swap(E1, E2);
13584 
13585         return VisitSequencedExpressions(E1, E2);
13586       }
13587     });
13588   }
13589 
13590   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13591     // This is a call, so all subexpressions are sequenced before the result.
13592     SequencedSubexpression Sequenced(*this);
13593 
13594     if (!CCE->isListInitialization())
13595       return VisitExpr(CCE);
13596 
13597     // In C++11, list initializations are sequenced.
13598     SmallVector<SequenceTree::Seq, 32> Elts;
13599     SequenceTree::Seq Parent = Region;
13600     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13601                                               E = CCE->arg_end();
13602          I != E; ++I) {
13603       Region = Tree.allocate(Parent);
13604       Elts.push_back(Region);
13605       Visit(*I);
13606     }
13607 
13608     // Forget that the initializers are sequenced.
13609     Region = Parent;
13610     for (unsigned I = 0; I < Elts.size(); ++I)
13611       Tree.merge(Elts[I]);
13612   }
13613 
13614   void VisitInitListExpr(const InitListExpr *ILE) {
13615     if (!SemaRef.getLangOpts().CPlusPlus11)
13616       return VisitExpr(ILE);
13617 
13618     // In C++11, list initializations are sequenced.
13619     SmallVector<SequenceTree::Seq, 32> Elts;
13620     SequenceTree::Seq Parent = Region;
13621     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13622       const Expr *E = ILE->getInit(I);
13623       if (!E)
13624         continue;
13625       Region = Tree.allocate(Parent);
13626       Elts.push_back(Region);
13627       Visit(E);
13628     }
13629 
13630     // Forget that the initializers are sequenced.
13631     Region = Parent;
13632     for (unsigned I = 0; I < Elts.size(); ++I)
13633       Tree.merge(Elts[I]);
13634   }
13635 };
13636 
13637 } // namespace
13638 
13639 void Sema::CheckUnsequencedOperations(const Expr *E) {
13640   SmallVector<const Expr *, 8> WorkList;
13641   WorkList.push_back(E);
13642   while (!WorkList.empty()) {
13643     const Expr *Item = WorkList.pop_back_val();
13644     SequenceChecker(*this, Item, WorkList);
13645   }
13646 }
13647 
13648 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13649                               bool IsConstexpr) {
13650   llvm::SaveAndRestore<bool> ConstantContext(
13651       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13652   CheckImplicitConversions(E, CheckLoc);
13653   if (!E->isInstantiationDependent())
13654     CheckUnsequencedOperations(E);
13655   if (!IsConstexpr && !E->isValueDependent())
13656     CheckForIntOverflow(E);
13657   DiagnoseMisalignedMembers();
13658 }
13659 
13660 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13661                                        FieldDecl *BitField,
13662                                        Expr *Init) {
13663   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13664 }
13665 
13666 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13667                                          SourceLocation Loc) {
13668   if (!PType->isVariablyModifiedType())
13669     return;
13670   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13671     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13672     return;
13673   }
13674   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13675     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13676     return;
13677   }
13678   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13679     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13680     return;
13681   }
13682 
13683   const ArrayType *AT = S.Context.getAsArrayType(PType);
13684   if (!AT)
13685     return;
13686 
13687   if (AT->getSizeModifier() != ArrayType::Star) {
13688     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13689     return;
13690   }
13691 
13692   S.Diag(Loc, diag::err_array_star_in_function_definition);
13693 }
13694 
13695 /// CheckParmsForFunctionDef - Check that the parameters of the given
13696 /// function are appropriate for the definition of a function. This
13697 /// takes care of any checks that cannot be performed on the
13698 /// declaration itself, e.g., that the types of each of the function
13699 /// parameters are complete.
13700 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13701                                     bool CheckParameterNames) {
13702   bool HasInvalidParm = false;
13703   for (ParmVarDecl *Param : Parameters) {
13704     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13705     // function declarator that is part of a function definition of
13706     // that function shall not have incomplete type.
13707     //
13708     // This is also C++ [dcl.fct]p6.
13709     if (!Param->isInvalidDecl() &&
13710         RequireCompleteType(Param->getLocation(), Param->getType(),
13711                             diag::err_typecheck_decl_incomplete_type)) {
13712       Param->setInvalidDecl();
13713       HasInvalidParm = true;
13714     }
13715 
13716     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13717     // declaration of each parameter shall include an identifier.
13718     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13719         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13720       // Diagnose this as an extension in C17 and earlier.
13721       if (!getLangOpts().C2x)
13722         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13723     }
13724 
13725     // C99 6.7.5.3p12:
13726     //   If the function declarator is not part of a definition of that
13727     //   function, parameters may have incomplete type and may use the [*]
13728     //   notation in their sequences of declarator specifiers to specify
13729     //   variable length array types.
13730     QualType PType = Param->getOriginalType();
13731     // FIXME: This diagnostic should point the '[*]' if source-location
13732     // information is added for it.
13733     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13734 
13735     // If the parameter is a c++ class type and it has to be destructed in the
13736     // callee function, declare the destructor so that it can be called by the
13737     // callee function. Do not perform any direct access check on the dtor here.
13738     if (!Param->isInvalidDecl()) {
13739       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13740         if (!ClassDecl->isInvalidDecl() &&
13741             !ClassDecl->hasIrrelevantDestructor() &&
13742             !ClassDecl->isDependentContext() &&
13743             ClassDecl->isParamDestroyedInCallee()) {
13744           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13745           MarkFunctionReferenced(Param->getLocation(), Destructor);
13746           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13747         }
13748       }
13749     }
13750 
13751     // Parameters with the pass_object_size attribute only need to be marked
13752     // constant at function definitions. Because we lack information about
13753     // whether we're on a declaration or definition when we're instantiating the
13754     // attribute, we need to check for constness here.
13755     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13756       if (!Param->getType().isConstQualified())
13757         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13758             << Attr->getSpelling() << 1;
13759 
13760     // Check for parameter names shadowing fields from the class.
13761     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13762       // The owning context for the parameter should be the function, but we
13763       // want to see if this function's declaration context is a record.
13764       DeclContext *DC = Param->getDeclContext();
13765       if (DC && DC->isFunctionOrMethod()) {
13766         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13767           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13768                                      RD, /*DeclIsField*/ false);
13769       }
13770     }
13771   }
13772 
13773   return HasInvalidParm;
13774 }
13775 
13776 Optional<std::pair<CharUnits, CharUnits>>
13777 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13778 
13779 /// Compute the alignment and offset of the base class object given the
13780 /// derived-to-base cast expression and the alignment and offset of the derived
13781 /// class object.
13782 static std::pair<CharUnits, CharUnits>
13783 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13784                                    CharUnits BaseAlignment, CharUnits Offset,
13785                                    ASTContext &Ctx) {
13786   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13787        ++PathI) {
13788     const CXXBaseSpecifier *Base = *PathI;
13789     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13790     if (Base->isVirtual()) {
13791       // The complete object may have a lower alignment than the non-virtual
13792       // alignment of the base, in which case the base may be misaligned. Choose
13793       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13794       // conservative lower bound of the complete object alignment.
13795       CharUnits NonVirtualAlignment =
13796           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13797       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13798       Offset = CharUnits::Zero();
13799     } else {
13800       const ASTRecordLayout &RL =
13801           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13802       Offset += RL.getBaseClassOffset(BaseDecl);
13803     }
13804     DerivedType = Base->getType();
13805   }
13806 
13807   return std::make_pair(BaseAlignment, Offset);
13808 }
13809 
13810 /// Compute the alignment and offset of a binary additive operator.
13811 static Optional<std::pair<CharUnits, CharUnits>>
13812 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13813                                      bool IsSub, ASTContext &Ctx) {
13814   QualType PointeeType = PtrE->getType()->getPointeeType();
13815 
13816   if (!PointeeType->isConstantSizeType())
13817     return llvm::None;
13818 
13819   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13820 
13821   if (!P)
13822     return llvm::None;
13823 
13824   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13825   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13826     CharUnits Offset = EltSize * IdxRes->getExtValue();
13827     if (IsSub)
13828       Offset = -Offset;
13829     return std::make_pair(P->first, P->second + Offset);
13830   }
13831 
13832   // If the integer expression isn't a constant expression, compute the lower
13833   // bound of the alignment using the alignment and offset of the pointer
13834   // expression and the element size.
13835   return std::make_pair(
13836       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13837       CharUnits::Zero());
13838 }
13839 
13840 /// This helper function takes an lvalue expression and returns the alignment of
13841 /// a VarDecl and a constant offset from the VarDecl.
13842 Optional<std::pair<CharUnits, CharUnits>>
13843 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13844   E = E->IgnoreParens();
13845   switch (E->getStmtClass()) {
13846   default:
13847     break;
13848   case Stmt::CStyleCastExprClass:
13849   case Stmt::CXXStaticCastExprClass:
13850   case Stmt::ImplicitCastExprClass: {
13851     auto *CE = cast<CastExpr>(E);
13852     const Expr *From = CE->getSubExpr();
13853     switch (CE->getCastKind()) {
13854     default:
13855       break;
13856     case CK_NoOp:
13857       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13858     case CK_UncheckedDerivedToBase:
13859     case CK_DerivedToBase: {
13860       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13861       if (!P)
13862         break;
13863       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13864                                                 P->second, Ctx);
13865     }
13866     }
13867     break;
13868   }
13869   case Stmt::ArraySubscriptExprClass: {
13870     auto *ASE = cast<ArraySubscriptExpr>(E);
13871     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13872                                                 false, Ctx);
13873   }
13874   case Stmt::DeclRefExprClass: {
13875     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13876       // FIXME: If VD is captured by copy or is an escaping __block variable,
13877       // use the alignment of VD's type.
13878       if (!VD->getType()->isReferenceType())
13879         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13880       if (VD->hasInit())
13881         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13882     }
13883     break;
13884   }
13885   case Stmt::MemberExprClass: {
13886     auto *ME = cast<MemberExpr>(E);
13887     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13888     if (!FD || FD->getType()->isReferenceType())
13889       break;
13890     Optional<std::pair<CharUnits, CharUnits>> P;
13891     if (ME->isArrow())
13892       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
13893     else
13894       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13895     if (!P)
13896       break;
13897     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13898     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13899     return std::make_pair(P->first,
13900                           P->second + CharUnits::fromQuantity(Offset));
13901   }
13902   case Stmt::UnaryOperatorClass: {
13903     auto *UO = cast<UnaryOperator>(E);
13904     switch (UO->getOpcode()) {
13905     default:
13906       break;
13907     case UO_Deref:
13908       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13909     }
13910     break;
13911   }
13912   case Stmt::BinaryOperatorClass: {
13913     auto *BO = cast<BinaryOperator>(E);
13914     auto Opcode = BO->getOpcode();
13915     switch (Opcode) {
13916     default:
13917       break;
13918     case BO_Comma:
13919       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13920     }
13921     break;
13922   }
13923   }
13924   return llvm::None;
13925 }
13926 
13927 /// This helper function takes a pointer expression and returns the alignment of
13928 /// a VarDecl and a constant offset from the VarDecl.
13929 Optional<std::pair<CharUnits, CharUnits>>
13930 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13931   E = E->IgnoreParens();
13932   switch (E->getStmtClass()) {
13933   default:
13934     break;
13935   case Stmt::CStyleCastExprClass:
13936   case Stmt::CXXStaticCastExprClass:
13937   case Stmt::ImplicitCastExprClass: {
13938     auto *CE = cast<CastExpr>(E);
13939     const Expr *From = CE->getSubExpr();
13940     switch (CE->getCastKind()) {
13941     default:
13942       break;
13943     case CK_NoOp:
13944       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13945     case CK_ArrayToPointerDecay:
13946       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13947     case CK_UncheckedDerivedToBase:
13948     case CK_DerivedToBase: {
13949       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13950       if (!P)
13951         break;
13952       return getDerivedToBaseAlignmentAndOffset(
13953           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13954     }
13955     }
13956     break;
13957   }
13958   case Stmt::CXXThisExprClass: {
13959     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13960     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
13961     return std::make_pair(Alignment, CharUnits::Zero());
13962   }
13963   case Stmt::UnaryOperatorClass: {
13964     auto *UO = cast<UnaryOperator>(E);
13965     if (UO->getOpcode() == UO_AddrOf)
13966       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13967     break;
13968   }
13969   case Stmt::BinaryOperatorClass: {
13970     auto *BO = cast<BinaryOperator>(E);
13971     auto Opcode = BO->getOpcode();
13972     switch (Opcode) {
13973     default:
13974       break;
13975     case BO_Add:
13976     case BO_Sub: {
13977       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13978       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13979         std::swap(LHS, RHS);
13980       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13981                                                   Ctx);
13982     }
13983     case BO_Comma:
13984       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13985     }
13986     break;
13987   }
13988   }
13989   return llvm::None;
13990 }
13991 
13992 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13993   // See if we can compute the alignment of a VarDecl and an offset from it.
13994   Optional<std::pair<CharUnits, CharUnits>> P =
13995       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13996 
13997   if (P)
13998     return P->first.alignmentAtOffset(P->second);
13999 
14000   // If that failed, return the type's alignment.
14001   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14002 }
14003 
14004 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14005 /// pointer cast increases the alignment requirements.
14006 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14007   // This is actually a lot of work to potentially be doing on every
14008   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14009   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14010     return;
14011 
14012   // Ignore dependent types.
14013   if (T->isDependentType() || Op->getType()->isDependentType())
14014     return;
14015 
14016   // Require that the destination be a pointer type.
14017   const PointerType *DestPtr = T->getAs<PointerType>();
14018   if (!DestPtr) return;
14019 
14020   // If the destination has alignment 1, we're done.
14021   QualType DestPointee = DestPtr->getPointeeType();
14022   if (DestPointee->isIncompleteType()) return;
14023   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14024   if (DestAlign.isOne()) return;
14025 
14026   // Require that the source be a pointer type.
14027   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14028   if (!SrcPtr) return;
14029   QualType SrcPointee = SrcPtr->getPointeeType();
14030 
14031   // Explicitly allow casts from cv void*.  We already implicitly
14032   // allowed casts to cv void*, since they have alignment 1.
14033   // Also allow casts involving incomplete types, which implicitly
14034   // includes 'void'.
14035   if (SrcPointee->isIncompleteType()) return;
14036 
14037   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14038 
14039   if (SrcAlign >= DestAlign) return;
14040 
14041   Diag(TRange.getBegin(), diag::warn_cast_align)
14042     << Op->getType() << T
14043     << static_cast<unsigned>(SrcAlign.getQuantity())
14044     << static_cast<unsigned>(DestAlign.getQuantity())
14045     << TRange << Op->getSourceRange();
14046 }
14047 
14048 /// Check whether this array fits the idiom of a size-one tail padded
14049 /// array member of a struct.
14050 ///
14051 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14052 /// commonly used to emulate flexible arrays in C89 code.
14053 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14054                                     const NamedDecl *ND) {
14055   if (Size != 1 || !ND) return false;
14056 
14057   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14058   if (!FD) return false;
14059 
14060   // Don't consider sizes resulting from macro expansions or template argument
14061   // substitution to form C89 tail-padded arrays.
14062 
14063   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14064   while (TInfo) {
14065     TypeLoc TL = TInfo->getTypeLoc();
14066     // Look through typedefs.
14067     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14068       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14069       TInfo = TDL->getTypeSourceInfo();
14070       continue;
14071     }
14072     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14073       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14074       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14075         return false;
14076     }
14077     break;
14078   }
14079 
14080   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14081   if (!RD) return false;
14082   if (RD->isUnion()) return false;
14083   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14084     if (!CRD->isStandardLayout()) return false;
14085   }
14086 
14087   // See if this is the last field decl in the record.
14088   const Decl *D = FD;
14089   while ((D = D->getNextDeclInContext()))
14090     if (isa<FieldDecl>(D))
14091       return false;
14092   return true;
14093 }
14094 
14095 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14096                             const ArraySubscriptExpr *ASE,
14097                             bool AllowOnePastEnd, bool IndexNegated) {
14098   // Already diagnosed by the constant evaluator.
14099   if (isConstantEvaluated())
14100     return;
14101 
14102   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14103   if (IndexExpr->isValueDependent())
14104     return;
14105 
14106   const Type *EffectiveType =
14107       BaseExpr->getType()->getPointeeOrArrayElementType();
14108   BaseExpr = BaseExpr->IgnoreParenCasts();
14109   const ConstantArrayType *ArrayTy =
14110       Context.getAsConstantArrayType(BaseExpr->getType());
14111 
14112   if (!ArrayTy)
14113     return;
14114 
14115   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14116   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14117     return;
14118 
14119   Expr::EvalResult Result;
14120   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14121     return;
14122 
14123   llvm::APSInt index = Result.Val.getInt();
14124   if (IndexNegated)
14125     index = -index;
14126 
14127   const NamedDecl *ND = nullptr;
14128   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14129     ND = DRE->getDecl();
14130   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14131     ND = ME->getMemberDecl();
14132 
14133   if (index.isUnsigned() || !index.isNegative()) {
14134     // It is possible that the type of the base expression after
14135     // IgnoreParenCasts is incomplete, even though the type of the base
14136     // expression before IgnoreParenCasts is complete (see PR39746 for an
14137     // example). In this case we have no information about whether the array
14138     // access exceeds the array bounds. However we can still diagnose an array
14139     // access which precedes the array bounds.
14140     if (BaseType->isIncompleteType())
14141       return;
14142 
14143     llvm::APInt size = ArrayTy->getSize();
14144     if (!size.isStrictlyPositive())
14145       return;
14146 
14147     if (BaseType != EffectiveType) {
14148       // Make sure we're comparing apples to apples when comparing index to size
14149       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14150       uint64_t array_typesize = Context.getTypeSize(BaseType);
14151       // Handle ptrarith_typesize being zero, such as when casting to void*
14152       if (!ptrarith_typesize) ptrarith_typesize = 1;
14153       if (ptrarith_typesize != array_typesize) {
14154         // There's a cast to a different size type involved
14155         uint64_t ratio = array_typesize / ptrarith_typesize;
14156         // TODO: Be smarter about handling cases where array_typesize is not a
14157         // multiple of ptrarith_typesize
14158         if (ptrarith_typesize * ratio == array_typesize)
14159           size *= llvm::APInt(size.getBitWidth(), ratio);
14160       }
14161     }
14162 
14163     if (size.getBitWidth() > index.getBitWidth())
14164       index = index.zext(size.getBitWidth());
14165     else if (size.getBitWidth() < index.getBitWidth())
14166       size = size.zext(index.getBitWidth());
14167 
14168     // For array subscripting the index must be less than size, but for pointer
14169     // arithmetic also allow the index (offset) to be equal to size since
14170     // computing the next address after the end of the array is legal and
14171     // commonly done e.g. in C++ iterators and range-based for loops.
14172     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14173       return;
14174 
14175     // Also don't warn for arrays of size 1 which are members of some
14176     // structure. These are often used to approximate flexible arrays in C89
14177     // code.
14178     if (IsTailPaddedMemberArray(*this, size, ND))
14179       return;
14180 
14181     // Suppress the warning if the subscript expression (as identified by the
14182     // ']' location) and the index expression are both from macro expansions
14183     // within a system header.
14184     if (ASE) {
14185       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14186           ASE->getRBracketLoc());
14187       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14188         SourceLocation IndexLoc =
14189             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14190         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14191           return;
14192       }
14193     }
14194 
14195     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14196     if (ASE)
14197       DiagID = diag::warn_array_index_exceeds_bounds;
14198 
14199     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14200                         PDiag(DiagID) << index.toString(10, true)
14201                                       << size.toString(10, true)
14202                                       << (unsigned)size.getLimitedValue(~0U)
14203                                       << IndexExpr->getSourceRange());
14204   } else {
14205     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14206     if (!ASE) {
14207       DiagID = diag::warn_ptr_arith_precedes_bounds;
14208       if (index.isNegative()) index = -index;
14209     }
14210 
14211     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14212                         PDiag(DiagID) << index.toString(10, true)
14213                                       << IndexExpr->getSourceRange());
14214   }
14215 
14216   if (!ND) {
14217     // Try harder to find a NamedDecl to point at in the note.
14218     while (const ArraySubscriptExpr *ASE =
14219            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14220       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14221     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14222       ND = DRE->getDecl();
14223     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14224       ND = ME->getMemberDecl();
14225   }
14226 
14227   if (ND)
14228     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14229                         PDiag(diag::note_array_declared_here) << ND);
14230 }
14231 
14232 void Sema::CheckArrayAccess(const Expr *expr) {
14233   int AllowOnePastEnd = 0;
14234   while (expr) {
14235     expr = expr->IgnoreParenImpCasts();
14236     switch (expr->getStmtClass()) {
14237       case Stmt::ArraySubscriptExprClass: {
14238         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14239         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14240                          AllowOnePastEnd > 0);
14241         expr = ASE->getBase();
14242         break;
14243       }
14244       case Stmt::MemberExprClass: {
14245         expr = cast<MemberExpr>(expr)->getBase();
14246         break;
14247       }
14248       case Stmt::OMPArraySectionExprClass: {
14249         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14250         if (ASE->getLowerBound())
14251           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14252                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14253         return;
14254       }
14255       case Stmt::UnaryOperatorClass: {
14256         // Only unwrap the * and & unary operators
14257         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14258         expr = UO->getSubExpr();
14259         switch (UO->getOpcode()) {
14260           case UO_AddrOf:
14261             AllowOnePastEnd++;
14262             break;
14263           case UO_Deref:
14264             AllowOnePastEnd--;
14265             break;
14266           default:
14267             return;
14268         }
14269         break;
14270       }
14271       case Stmt::ConditionalOperatorClass: {
14272         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14273         if (const Expr *lhs = cond->getLHS())
14274           CheckArrayAccess(lhs);
14275         if (const Expr *rhs = cond->getRHS())
14276           CheckArrayAccess(rhs);
14277         return;
14278       }
14279       case Stmt::CXXOperatorCallExprClass: {
14280         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14281         for (const auto *Arg : OCE->arguments())
14282           CheckArrayAccess(Arg);
14283         return;
14284       }
14285       default:
14286         return;
14287     }
14288   }
14289 }
14290 
14291 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14292 
14293 namespace {
14294 
14295 struct RetainCycleOwner {
14296   VarDecl *Variable = nullptr;
14297   SourceRange Range;
14298   SourceLocation Loc;
14299   bool Indirect = false;
14300 
14301   RetainCycleOwner() = default;
14302 
14303   void setLocsFrom(Expr *e) {
14304     Loc = e->getExprLoc();
14305     Range = e->getSourceRange();
14306   }
14307 };
14308 
14309 } // namespace
14310 
14311 /// Consider whether capturing the given variable can possibly lead to
14312 /// a retain cycle.
14313 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14314   // In ARC, it's captured strongly iff the variable has __strong
14315   // lifetime.  In MRR, it's captured strongly if the variable is
14316   // __block and has an appropriate type.
14317   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14318     return false;
14319 
14320   owner.Variable = var;
14321   if (ref)
14322     owner.setLocsFrom(ref);
14323   return true;
14324 }
14325 
14326 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14327   while (true) {
14328     e = e->IgnoreParens();
14329     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14330       switch (cast->getCastKind()) {
14331       case CK_BitCast:
14332       case CK_LValueBitCast:
14333       case CK_LValueToRValue:
14334       case CK_ARCReclaimReturnedObject:
14335         e = cast->getSubExpr();
14336         continue;
14337 
14338       default:
14339         return false;
14340       }
14341     }
14342 
14343     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14344       ObjCIvarDecl *ivar = ref->getDecl();
14345       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14346         return false;
14347 
14348       // Try to find a retain cycle in the base.
14349       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14350         return false;
14351 
14352       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14353       owner.Indirect = true;
14354       return true;
14355     }
14356 
14357     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14358       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14359       if (!var) return false;
14360       return considerVariable(var, ref, owner);
14361     }
14362 
14363     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14364       if (member->isArrow()) return false;
14365 
14366       // Don't count this as an indirect ownership.
14367       e = member->getBase();
14368       continue;
14369     }
14370 
14371     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14372       // Only pay attention to pseudo-objects on property references.
14373       ObjCPropertyRefExpr *pre
14374         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14375                                               ->IgnoreParens());
14376       if (!pre) return false;
14377       if (pre->isImplicitProperty()) return false;
14378       ObjCPropertyDecl *property = pre->getExplicitProperty();
14379       if (!property->isRetaining() &&
14380           !(property->getPropertyIvarDecl() &&
14381             property->getPropertyIvarDecl()->getType()
14382               .getObjCLifetime() == Qualifiers::OCL_Strong))
14383           return false;
14384 
14385       owner.Indirect = true;
14386       if (pre->isSuperReceiver()) {
14387         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14388         if (!owner.Variable)
14389           return false;
14390         owner.Loc = pre->getLocation();
14391         owner.Range = pre->getSourceRange();
14392         return true;
14393       }
14394       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14395                               ->getSourceExpr());
14396       continue;
14397     }
14398 
14399     // Array ivars?
14400 
14401     return false;
14402   }
14403 }
14404 
14405 namespace {
14406 
14407   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14408     ASTContext &Context;
14409     VarDecl *Variable;
14410     Expr *Capturer = nullptr;
14411     bool VarWillBeReased = false;
14412 
14413     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14414         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14415           Context(Context), Variable(variable) {}
14416 
14417     void VisitDeclRefExpr(DeclRefExpr *ref) {
14418       if (ref->getDecl() == Variable && !Capturer)
14419         Capturer = ref;
14420     }
14421 
14422     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14423       if (Capturer) return;
14424       Visit(ref->getBase());
14425       if (Capturer && ref->isFreeIvar())
14426         Capturer = ref;
14427     }
14428 
14429     void VisitBlockExpr(BlockExpr *block) {
14430       // Look inside nested blocks
14431       if (block->getBlockDecl()->capturesVariable(Variable))
14432         Visit(block->getBlockDecl()->getBody());
14433     }
14434 
14435     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14436       if (Capturer) return;
14437       if (OVE->getSourceExpr())
14438         Visit(OVE->getSourceExpr());
14439     }
14440 
14441     void VisitBinaryOperator(BinaryOperator *BinOp) {
14442       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14443         return;
14444       Expr *LHS = BinOp->getLHS();
14445       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14446         if (DRE->getDecl() != Variable)
14447           return;
14448         if (Expr *RHS = BinOp->getRHS()) {
14449           RHS = RHS->IgnoreParenCasts();
14450           Optional<llvm::APSInt> Value;
14451           VarWillBeReased =
14452               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14453                *Value == 0);
14454         }
14455       }
14456     }
14457   };
14458 
14459 } // namespace
14460 
14461 /// Check whether the given argument is a block which captures a
14462 /// variable.
14463 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14464   assert(owner.Variable && owner.Loc.isValid());
14465 
14466   e = e->IgnoreParenCasts();
14467 
14468   // Look through [^{...} copy] and Block_copy(^{...}).
14469   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14470     Selector Cmd = ME->getSelector();
14471     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14472       e = ME->getInstanceReceiver();
14473       if (!e)
14474         return nullptr;
14475       e = e->IgnoreParenCasts();
14476     }
14477   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14478     if (CE->getNumArgs() == 1) {
14479       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14480       if (Fn) {
14481         const IdentifierInfo *FnI = Fn->getIdentifier();
14482         if (FnI && FnI->isStr("_Block_copy")) {
14483           e = CE->getArg(0)->IgnoreParenCasts();
14484         }
14485       }
14486     }
14487   }
14488 
14489   BlockExpr *block = dyn_cast<BlockExpr>(e);
14490   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14491     return nullptr;
14492 
14493   FindCaptureVisitor visitor(S.Context, owner.Variable);
14494   visitor.Visit(block->getBlockDecl()->getBody());
14495   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14496 }
14497 
14498 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14499                                 RetainCycleOwner &owner) {
14500   assert(capturer);
14501   assert(owner.Variable && owner.Loc.isValid());
14502 
14503   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14504     << owner.Variable << capturer->getSourceRange();
14505   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14506     << owner.Indirect << owner.Range;
14507 }
14508 
14509 /// Check for a keyword selector that starts with the word 'add' or
14510 /// 'set'.
14511 static bool isSetterLikeSelector(Selector sel) {
14512   if (sel.isUnarySelector()) return false;
14513 
14514   StringRef str = sel.getNameForSlot(0);
14515   while (!str.empty() && str.front() == '_') str = str.substr(1);
14516   if (str.startswith("set"))
14517     str = str.substr(3);
14518   else if (str.startswith("add")) {
14519     // Specially allow 'addOperationWithBlock:'.
14520     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14521       return false;
14522     str = str.substr(3);
14523   }
14524   else
14525     return false;
14526 
14527   if (str.empty()) return true;
14528   return !isLowercase(str.front());
14529 }
14530 
14531 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14532                                                     ObjCMessageExpr *Message) {
14533   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14534                                                 Message->getReceiverInterface(),
14535                                                 NSAPI::ClassId_NSMutableArray);
14536   if (!IsMutableArray) {
14537     return None;
14538   }
14539 
14540   Selector Sel = Message->getSelector();
14541 
14542   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14543     S.NSAPIObj->getNSArrayMethodKind(Sel);
14544   if (!MKOpt) {
14545     return None;
14546   }
14547 
14548   NSAPI::NSArrayMethodKind MK = *MKOpt;
14549 
14550   switch (MK) {
14551     case NSAPI::NSMutableArr_addObject:
14552     case NSAPI::NSMutableArr_insertObjectAtIndex:
14553     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14554       return 0;
14555     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14556       return 1;
14557 
14558     default:
14559       return None;
14560   }
14561 
14562   return None;
14563 }
14564 
14565 static
14566 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14567                                                   ObjCMessageExpr *Message) {
14568   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14569                                             Message->getReceiverInterface(),
14570                                             NSAPI::ClassId_NSMutableDictionary);
14571   if (!IsMutableDictionary) {
14572     return None;
14573   }
14574 
14575   Selector Sel = Message->getSelector();
14576 
14577   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14578     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14579   if (!MKOpt) {
14580     return None;
14581   }
14582 
14583   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14584 
14585   switch (MK) {
14586     case NSAPI::NSMutableDict_setObjectForKey:
14587     case NSAPI::NSMutableDict_setValueForKey:
14588     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14589       return 0;
14590 
14591     default:
14592       return None;
14593   }
14594 
14595   return None;
14596 }
14597 
14598 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14599   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14600                                                 Message->getReceiverInterface(),
14601                                                 NSAPI::ClassId_NSMutableSet);
14602 
14603   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14604                                             Message->getReceiverInterface(),
14605                                             NSAPI::ClassId_NSMutableOrderedSet);
14606   if (!IsMutableSet && !IsMutableOrderedSet) {
14607     return None;
14608   }
14609 
14610   Selector Sel = Message->getSelector();
14611 
14612   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14613   if (!MKOpt) {
14614     return None;
14615   }
14616 
14617   NSAPI::NSSetMethodKind MK = *MKOpt;
14618 
14619   switch (MK) {
14620     case NSAPI::NSMutableSet_addObject:
14621     case NSAPI::NSOrderedSet_setObjectAtIndex:
14622     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14623     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14624       return 0;
14625     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14626       return 1;
14627   }
14628 
14629   return None;
14630 }
14631 
14632 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14633   if (!Message->isInstanceMessage()) {
14634     return;
14635   }
14636 
14637   Optional<int> ArgOpt;
14638 
14639   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14640       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14641       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14642     return;
14643   }
14644 
14645   int ArgIndex = *ArgOpt;
14646 
14647   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14648   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14649     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14650   }
14651 
14652   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14653     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14654       if (ArgRE->isObjCSelfExpr()) {
14655         Diag(Message->getSourceRange().getBegin(),
14656              diag::warn_objc_circular_container)
14657           << ArgRE->getDecl() << StringRef("'super'");
14658       }
14659     }
14660   } else {
14661     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14662 
14663     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14664       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14665     }
14666 
14667     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14668       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14669         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14670           ValueDecl *Decl = ReceiverRE->getDecl();
14671           Diag(Message->getSourceRange().getBegin(),
14672                diag::warn_objc_circular_container)
14673             << Decl << Decl;
14674           if (!ArgRE->isObjCSelfExpr()) {
14675             Diag(Decl->getLocation(),
14676                  diag::note_objc_circular_container_declared_here)
14677               << Decl;
14678           }
14679         }
14680       }
14681     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14682       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14683         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14684           ObjCIvarDecl *Decl = IvarRE->getDecl();
14685           Diag(Message->getSourceRange().getBegin(),
14686                diag::warn_objc_circular_container)
14687             << Decl << Decl;
14688           Diag(Decl->getLocation(),
14689                diag::note_objc_circular_container_declared_here)
14690             << Decl;
14691         }
14692       }
14693     }
14694   }
14695 }
14696 
14697 /// Check a message send to see if it's likely to cause a retain cycle.
14698 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14699   // Only check instance methods whose selector looks like a setter.
14700   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14701     return;
14702 
14703   // Try to find a variable that the receiver is strongly owned by.
14704   RetainCycleOwner owner;
14705   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14706     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14707       return;
14708   } else {
14709     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14710     owner.Variable = getCurMethodDecl()->getSelfDecl();
14711     owner.Loc = msg->getSuperLoc();
14712     owner.Range = msg->getSuperLoc();
14713   }
14714 
14715   // Check whether the receiver is captured by any of the arguments.
14716   const ObjCMethodDecl *MD = msg->getMethodDecl();
14717   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14718     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14719       // noescape blocks should not be retained by the method.
14720       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14721         continue;
14722       return diagnoseRetainCycle(*this, capturer, owner);
14723     }
14724   }
14725 }
14726 
14727 /// Check a property assign to see if it's likely to cause a retain cycle.
14728 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14729   RetainCycleOwner owner;
14730   if (!findRetainCycleOwner(*this, receiver, owner))
14731     return;
14732 
14733   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14734     diagnoseRetainCycle(*this, capturer, owner);
14735 }
14736 
14737 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14738   RetainCycleOwner Owner;
14739   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14740     return;
14741 
14742   // Because we don't have an expression for the variable, we have to set the
14743   // location explicitly here.
14744   Owner.Loc = Var->getLocation();
14745   Owner.Range = Var->getSourceRange();
14746 
14747   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14748     diagnoseRetainCycle(*this, Capturer, Owner);
14749 }
14750 
14751 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14752                                      Expr *RHS, bool isProperty) {
14753   // Check if RHS is an Objective-C object literal, which also can get
14754   // immediately zapped in a weak reference.  Note that we explicitly
14755   // allow ObjCStringLiterals, since those are designed to never really die.
14756   RHS = RHS->IgnoreParenImpCasts();
14757 
14758   // This enum needs to match with the 'select' in
14759   // warn_objc_arc_literal_assign (off-by-1).
14760   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14761   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14762     return false;
14763 
14764   S.Diag(Loc, diag::warn_arc_literal_assign)
14765     << (unsigned) Kind
14766     << (isProperty ? 0 : 1)
14767     << RHS->getSourceRange();
14768 
14769   return true;
14770 }
14771 
14772 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14773                                     Qualifiers::ObjCLifetime LT,
14774                                     Expr *RHS, bool isProperty) {
14775   // Strip off any implicit cast added to get to the one ARC-specific.
14776   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14777     if (cast->getCastKind() == CK_ARCConsumeObject) {
14778       S.Diag(Loc, diag::warn_arc_retained_assign)
14779         << (LT == Qualifiers::OCL_ExplicitNone)
14780         << (isProperty ? 0 : 1)
14781         << RHS->getSourceRange();
14782       return true;
14783     }
14784     RHS = cast->getSubExpr();
14785   }
14786 
14787   if (LT == Qualifiers::OCL_Weak &&
14788       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14789     return true;
14790 
14791   return false;
14792 }
14793 
14794 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14795                               QualType LHS, Expr *RHS) {
14796   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14797 
14798   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14799     return false;
14800 
14801   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14802     return true;
14803 
14804   return false;
14805 }
14806 
14807 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14808                               Expr *LHS, Expr *RHS) {
14809   QualType LHSType;
14810   // PropertyRef on LHS type need be directly obtained from
14811   // its declaration as it has a PseudoType.
14812   ObjCPropertyRefExpr *PRE
14813     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14814   if (PRE && !PRE->isImplicitProperty()) {
14815     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14816     if (PD)
14817       LHSType = PD->getType();
14818   }
14819 
14820   if (LHSType.isNull())
14821     LHSType = LHS->getType();
14822 
14823   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14824 
14825   if (LT == Qualifiers::OCL_Weak) {
14826     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14827       getCurFunction()->markSafeWeakUse(LHS);
14828   }
14829 
14830   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14831     return;
14832 
14833   // FIXME. Check for other life times.
14834   if (LT != Qualifiers::OCL_None)
14835     return;
14836 
14837   if (PRE) {
14838     if (PRE->isImplicitProperty())
14839       return;
14840     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14841     if (!PD)
14842       return;
14843 
14844     unsigned Attributes = PD->getPropertyAttributes();
14845     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14846       // when 'assign' attribute was not explicitly specified
14847       // by user, ignore it and rely on property type itself
14848       // for lifetime info.
14849       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14850       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14851           LHSType->isObjCRetainableType())
14852         return;
14853 
14854       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14855         if (cast->getCastKind() == CK_ARCConsumeObject) {
14856           Diag(Loc, diag::warn_arc_retained_property_assign)
14857           << RHS->getSourceRange();
14858           return;
14859         }
14860         RHS = cast->getSubExpr();
14861       }
14862     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14863       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14864         return;
14865     }
14866   }
14867 }
14868 
14869 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14870 
14871 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14872                                         SourceLocation StmtLoc,
14873                                         const NullStmt *Body) {
14874   // Do not warn if the body is a macro that expands to nothing, e.g:
14875   //
14876   // #define CALL(x)
14877   // if (condition)
14878   //   CALL(0);
14879   if (Body->hasLeadingEmptyMacro())
14880     return false;
14881 
14882   // Get line numbers of statement and body.
14883   bool StmtLineInvalid;
14884   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14885                                                       &StmtLineInvalid);
14886   if (StmtLineInvalid)
14887     return false;
14888 
14889   bool BodyLineInvalid;
14890   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14891                                                       &BodyLineInvalid);
14892   if (BodyLineInvalid)
14893     return false;
14894 
14895   // Warn if null statement and body are on the same line.
14896   if (StmtLine != BodyLine)
14897     return false;
14898 
14899   return true;
14900 }
14901 
14902 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14903                                  const Stmt *Body,
14904                                  unsigned DiagID) {
14905   // Since this is a syntactic check, don't emit diagnostic for template
14906   // instantiations, this just adds noise.
14907   if (CurrentInstantiationScope)
14908     return;
14909 
14910   // The body should be a null statement.
14911   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14912   if (!NBody)
14913     return;
14914 
14915   // Do the usual checks.
14916   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14917     return;
14918 
14919   Diag(NBody->getSemiLoc(), DiagID);
14920   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14921 }
14922 
14923 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14924                                  const Stmt *PossibleBody) {
14925   assert(!CurrentInstantiationScope); // Ensured by caller
14926 
14927   SourceLocation StmtLoc;
14928   const Stmt *Body;
14929   unsigned DiagID;
14930   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14931     StmtLoc = FS->getRParenLoc();
14932     Body = FS->getBody();
14933     DiagID = diag::warn_empty_for_body;
14934   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14935     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14936     Body = WS->getBody();
14937     DiagID = diag::warn_empty_while_body;
14938   } else
14939     return; // Neither `for' nor `while'.
14940 
14941   // The body should be a null statement.
14942   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14943   if (!NBody)
14944     return;
14945 
14946   // Skip expensive checks if diagnostic is disabled.
14947   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14948     return;
14949 
14950   // Do the usual checks.
14951   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14952     return;
14953 
14954   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14955   // noise level low, emit diagnostics only if for/while is followed by a
14956   // CompoundStmt, e.g.:
14957   //    for (int i = 0; i < n; i++);
14958   //    {
14959   //      a(i);
14960   //    }
14961   // or if for/while is followed by a statement with more indentation
14962   // than for/while itself:
14963   //    for (int i = 0; i < n; i++);
14964   //      a(i);
14965   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14966   if (!ProbableTypo) {
14967     bool BodyColInvalid;
14968     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14969         PossibleBody->getBeginLoc(), &BodyColInvalid);
14970     if (BodyColInvalid)
14971       return;
14972 
14973     bool StmtColInvalid;
14974     unsigned StmtCol =
14975         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14976     if (StmtColInvalid)
14977       return;
14978 
14979     if (BodyCol > StmtCol)
14980       ProbableTypo = true;
14981   }
14982 
14983   if (ProbableTypo) {
14984     Diag(NBody->getSemiLoc(), DiagID);
14985     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14986   }
14987 }
14988 
14989 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14990 
14991 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14992 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14993                              SourceLocation OpLoc) {
14994   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14995     return;
14996 
14997   if (inTemplateInstantiation())
14998     return;
14999 
15000   // Strip parens and casts away.
15001   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15002   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15003 
15004   // Check for a call expression
15005   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15006   if (!CE || CE->getNumArgs() != 1)
15007     return;
15008 
15009   // Check for a call to std::move
15010   if (!CE->isCallToStdMove())
15011     return;
15012 
15013   // Get argument from std::move
15014   RHSExpr = CE->getArg(0);
15015 
15016   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15017   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15018 
15019   // Two DeclRefExpr's, check that the decls are the same.
15020   if (LHSDeclRef && RHSDeclRef) {
15021     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15022       return;
15023     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15024         RHSDeclRef->getDecl()->getCanonicalDecl())
15025       return;
15026 
15027     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15028                                         << LHSExpr->getSourceRange()
15029                                         << RHSExpr->getSourceRange();
15030     return;
15031   }
15032 
15033   // Member variables require a different approach to check for self moves.
15034   // MemberExpr's are the same if every nested MemberExpr refers to the same
15035   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15036   // the base Expr's are CXXThisExpr's.
15037   const Expr *LHSBase = LHSExpr;
15038   const Expr *RHSBase = RHSExpr;
15039   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15040   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15041   if (!LHSME || !RHSME)
15042     return;
15043 
15044   while (LHSME && RHSME) {
15045     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15046         RHSME->getMemberDecl()->getCanonicalDecl())
15047       return;
15048 
15049     LHSBase = LHSME->getBase();
15050     RHSBase = RHSME->getBase();
15051     LHSME = dyn_cast<MemberExpr>(LHSBase);
15052     RHSME = dyn_cast<MemberExpr>(RHSBase);
15053   }
15054 
15055   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15056   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15057   if (LHSDeclRef && RHSDeclRef) {
15058     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15059       return;
15060     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15061         RHSDeclRef->getDecl()->getCanonicalDecl())
15062       return;
15063 
15064     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15065                                         << LHSExpr->getSourceRange()
15066                                         << RHSExpr->getSourceRange();
15067     return;
15068   }
15069 
15070   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15071     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15072                                         << LHSExpr->getSourceRange()
15073                                         << RHSExpr->getSourceRange();
15074 }
15075 
15076 //===--- Layout compatibility ----------------------------------------------//
15077 
15078 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15079 
15080 /// Check if two enumeration types are layout-compatible.
15081 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15082   // C++11 [dcl.enum] p8:
15083   // Two enumeration types are layout-compatible if they have the same
15084   // underlying type.
15085   return ED1->isComplete() && ED2->isComplete() &&
15086          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15087 }
15088 
15089 /// Check if two fields are layout-compatible.
15090 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15091                                FieldDecl *Field2) {
15092   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15093     return false;
15094 
15095   if (Field1->isBitField() != Field2->isBitField())
15096     return false;
15097 
15098   if (Field1->isBitField()) {
15099     // Make sure that the bit-fields are the same length.
15100     unsigned Bits1 = Field1->getBitWidthValue(C);
15101     unsigned Bits2 = Field2->getBitWidthValue(C);
15102 
15103     if (Bits1 != Bits2)
15104       return false;
15105   }
15106 
15107   return true;
15108 }
15109 
15110 /// Check if two standard-layout structs are layout-compatible.
15111 /// (C++11 [class.mem] p17)
15112 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15113                                      RecordDecl *RD2) {
15114   // If both records are C++ classes, check that base classes match.
15115   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15116     // If one of records is a CXXRecordDecl we are in C++ mode,
15117     // thus the other one is a CXXRecordDecl, too.
15118     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15119     // Check number of base classes.
15120     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15121       return false;
15122 
15123     // Check the base classes.
15124     for (CXXRecordDecl::base_class_const_iterator
15125                Base1 = D1CXX->bases_begin(),
15126            BaseEnd1 = D1CXX->bases_end(),
15127               Base2 = D2CXX->bases_begin();
15128          Base1 != BaseEnd1;
15129          ++Base1, ++Base2) {
15130       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15131         return false;
15132     }
15133   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15134     // If only RD2 is a C++ class, it should have zero base classes.
15135     if (D2CXX->getNumBases() > 0)
15136       return false;
15137   }
15138 
15139   // Check the fields.
15140   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15141                              Field2End = RD2->field_end(),
15142                              Field1 = RD1->field_begin(),
15143                              Field1End = RD1->field_end();
15144   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15145     if (!isLayoutCompatible(C, *Field1, *Field2))
15146       return false;
15147   }
15148   if (Field1 != Field1End || Field2 != Field2End)
15149     return false;
15150 
15151   return true;
15152 }
15153 
15154 /// Check if two standard-layout unions are layout-compatible.
15155 /// (C++11 [class.mem] p18)
15156 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15157                                     RecordDecl *RD2) {
15158   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15159   for (auto *Field2 : RD2->fields())
15160     UnmatchedFields.insert(Field2);
15161 
15162   for (auto *Field1 : RD1->fields()) {
15163     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15164         I = UnmatchedFields.begin(),
15165         E = UnmatchedFields.end();
15166 
15167     for ( ; I != E; ++I) {
15168       if (isLayoutCompatible(C, Field1, *I)) {
15169         bool Result = UnmatchedFields.erase(*I);
15170         (void) Result;
15171         assert(Result);
15172         break;
15173       }
15174     }
15175     if (I == E)
15176       return false;
15177   }
15178 
15179   return UnmatchedFields.empty();
15180 }
15181 
15182 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15183                                RecordDecl *RD2) {
15184   if (RD1->isUnion() != RD2->isUnion())
15185     return false;
15186 
15187   if (RD1->isUnion())
15188     return isLayoutCompatibleUnion(C, RD1, RD2);
15189   else
15190     return isLayoutCompatibleStruct(C, RD1, RD2);
15191 }
15192 
15193 /// Check if two types are layout-compatible in C++11 sense.
15194 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15195   if (T1.isNull() || T2.isNull())
15196     return false;
15197 
15198   // C++11 [basic.types] p11:
15199   // If two types T1 and T2 are the same type, then T1 and T2 are
15200   // layout-compatible types.
15201   if (C.hasSameType(T1, T2))
15202     return true;
15203 
15204   T1 = T1.getCanonicalType().getUnqualifiedType();
15205   T2 = T2.getCanonicalType().getUnqualifiedType();
15206 
15207   const Type::TypeClass TC1 = T1->getTypeClass();
15208   const Type::TypeClass TC2 = T2->getTypeClass();
15209 
15210   if (TC1 != TC2)
15211     return false;
15212 
15213   if (TC1 == Type::Enum) {
15214     return isLayoutCompatible(C,
15215                               cast<EnumType>(T1)->getDecl(),
15216                               cast<EnumType>(T2)->getDecl());
15217   } else if (TC1 == Type::Record) {
15218     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15219       return false;
15220 
15221     return isLayoutCompatible(C,
15222                               cast<RecordType>(T1)->getDecl(),
15223                               cast<RecordType>(T2)->getDecl());
15224   }
15225 
15226   return false;
15227 }
15228 
15229 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15230 
15231 /// Given a type tag expression find the type tag itself.
15232 ///
15233 /// \param TypeExpr Type tag expression, as it appears in user's code.
15234 ///
15235 /// \param VD Declaration of an identifier that appears in a type tag.
15236 ///
15237 /// \param MagicValue Type tag magic value.
15238 ///
15239 /// \param isConstantEvaluated wether the evalaution should be performed in
15240 
15241 /// constant context.
15242 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15243                             const ValueDecl **VD, uint64_t *MagicValue,
15244                             bool isConstantEvaluated) {
15245   while(true) {
15246     if (!TypeExpr)
15247       return false;
15248 
15249     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15250 
15251     switch (TypeExpr->getStmtClass()) {
15252     case Stmt::UnaryOperatorClass: {
15253       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15254       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15255         TypeExpr = UO->getSubExpr();
15256         continue;
15257       }
15258       return false;
15259     }
15260 
15261     case Stmt::DeclRefExprClass: {
15262       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15263       *VD = DRE->getDecl();
15264       return true;
15265     }
15266 
15267     case Stmt::IntegerLiteralClass: {
15268       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15269       llvm::APInt MagicValueAPInt = IL->getValue();
15270       if (MagicValueAPInt.getActiveBits() <= 64) {
15271         *MagicValue = MagicValueAPInt.getZExtValue();
15272         return true;
15273       } else
15274         return false;
15275     }
15276 
15277     case Stmt::BinaryConditionalOperatorClass:
15278     case Stmt::ConditionalOperatorClass: {
15279       const AbstractConditionalOperator *ACO =
15280           cast<AbstractConditionalOperator>(TypeExpr);
15281       bool Result;
15282       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15283                                                      isConstantEvaluated)) {
15284         if (Result)
15285           TypeExpr = ACO->getTrueExpr();
15286         else
15287           TypeExpr = ACO->getFalseExpr();
15288         continue;
15289       }
15290       return false;
15291     }
15292 
15293     case Stmt::BinaryOperatorClass: {
15294       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15295       if (BO->getOpcode() == BO_Comma) {
15296         TypeExpr = BO->getRHS();
15297         continue;
15298       }
15299       return false;
15300     }
15301 
15302     default:
15303       return false;
15304     }
15305   }
15306 }
15307 
15308 /// Retrieve the C type corresponding to type tag TypeExpr.
15309 ///
15310 /// \param TypeExpr Expression that specifies a type tag.
15311 ///
15312 /// \param MagicValues Registered magic values.
15313 ///
15314 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15315 ///        kind.
15316 ///
15317 /// \param TypeInfo Information about the corresponding C type.
15318 ///
15319 /// \param isConstantEvaluated wether the evalaution should be performed in
15320 /// constant context.
15321 ///
15322 /// \returns true if the corresponding C type was found.
15323 static bool GetMatchingCType(
15324     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15325     const ASTContext &Ctx,
15326     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15327         *MagicValues,
15328     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15329     bool isConstantEvaluated) {
15330   FoundWrongKind = false;
15331 
15332   // Variable declaration that has type_tag_for_datatype attribute.
15333   const ValueDecl *VD = nullptr;
15334 
15335   uint64_t MagicValue;
15336 
15337   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15338     return false;
15339 
15340   if (VD) {
15341     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15342       if (I->getArgumentKind() != ArgumentKind) {
15343         FoundWrongKind = true;
15344         return false;
15345       }
15346       TypeInfo.Type = I->getMatchingCType();
15347       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15348       TypeInfo.MustBeNull = I->getMustBeNull();
15349       return true;
15350     }
15351     return false;
15352   }
15353 
15354   if (!MagicValues)
15355     return false;
15356 
15357   llvm::DenseMap<Sema::TypeTagMagicValue,
15358                  Sema::TypeTagData>::const_iterator I =
15359       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15360   if (I == MagicValues->end())
15361     return false;
15362 
15363   TypeInfo = I->second;
15364   return true;
15365 }
15366 
15367 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15368                                       uint64_t MagicValue, QualType Type,
15369                                       bool LayoutCompatible,
15370                                       bool MustBeNull) {
15371   if (!TypeTagForDatatypeMagicValues)
15372     TypeTagForDatatypeMagicValues.reset(
15373         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15374 
15375   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15376   (*TypeTagForDatatypeMagicValues)[Magic] =
15377       TypeTagData(Type, LayoutCompatible, MustBeNull);
15378 }
15379 
15380 static bool IsSameCharType(QualType T1, QualType T2) {
15381   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15382   if (!BT1)
15383     return false;
15384 
15385   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15386   if (!BT2)
15387     return false;
15388 
15389   BuiltinType::Kind T1Kind = BT1->getKind();
15390   BuiltinType::Kind T2Kind = BT2->getKind();
15391 
15392   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15393          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15394          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15395          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15396 }
15397 
15398 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15399                                     const ArrayRef<const Expr *> ExprArgs,
15400                                     SourceLocation CallSiteLoc) {
15401   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15402   bool IsPointerAttr = Attr->getIsPointer();
15403 
15404   // Retrieve the argument representing the 'type_tag'.
15405   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15406   if (TypeTagIdxAST >= ExprArgs.size()) {
15407     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15408         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15409     return;
15410   }
15411   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15412   bool FoundWrongKind;
15413   TypeTagData TypeInfo;
15414   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15415                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15416                         TypeInfo, isConstantEvaluated())) {
15417     if (FoundWrongKind)
15418       Diag(TypeTagExpr->getExprLoc(),
15419            diag::warn_type_tag_for_datatype_wrong_kind)
15420         << TypeTagExpr->getSourceRange();
15421     return;
15422   }
15423 
15424   // Retrieve the argument representing the 'arg_idx'.
15425   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15426   if (ArgumentIdxAST >= ExprArgs.size()) {
15427     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15428         << 1 << Attr->getArgumentIdx().getSourceIndex();
15429     return;
15430   }
15431   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15432   if (IsPointerAttr) {
15433     // Skip implicit cast of pointer to `void *' (as a function argument).
15434     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15435       if (ICE->getType()->isVoidPointerType() &&
15436           ICE->getCastKind() == CK_BitCast)
15437         ArgumentExpr = ICE->getSubExpr();
15438   }
15439   QualType ArgumentType = ArgumentExpr->getType();
15440 
15441   // Passing a `void*' pointer shouldn't trigger a warning.
15442   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15443     return;
15444 
15445   if (TypeInfo.MustBeNull) {
15446     // Type tag with matching void type requires a null pointer.
15447     if (!ArgumentExpr->isNullPointerConstant(Context,
15448                                              Expr::NPC_ValueDependentIsNotNull)) {
15449       Diag(ArgumentExpr->getExprLoc(),
15450            diag::warn_type_safety_null_pointer_required)
15451           << ArgumentKind->getName()
15452           << ArgumentExpr->getSourceRange()
15453           << TypeTagExpr->getSourceRange();
15454     }
15455     return;
15456   }
15457 
15458   QualType RequiredType = TypeInfo.Type;
15459   if (IsPointerAttr)
15460     RequiredType = Context.getPointerType(RequiredType);
15461 
15462   bool mismatch = false;
15463   if (!TypeInfo.LayoutCompatible) {
15464     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15465 
15466     // C++11 [basic.fundamental] p1:
15467     // Plain char, signed char, and unsigned char are three distinct types.
15468     //
15469     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15470     // char' depending on the current char signedness mode.
15471     if (mismatch)
15472       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15473                                            RequiredType->getPointeeType())) ||
15474           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15475         mismatch = false;
15476   } else
15477     if (IsPointerAttr)
15478       mismatch = !isLayoutCompatible(Context,
15479                                      ArgumentType->getPointeeType(),
15480                                      RequiredType->getPointeeType());
15481     else
15482       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15483 
15484   if (mismatch)
15485     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15486         << ArgumentType << ArgumentKind
15487         << TypeInfo.LayoutCompatible << RequiredType
15488         << ArgumentExpr->getSourceRange()
15489         << TypeTagExpr->getSourceRange();
15490 }
15491 
15492 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15493                                          CharUnits Alignment) {
15494   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15495 }
15496 
15497 void Sema::DiagnoseMisalignedMembers() {
15498   for (MisalignedMember &m : MisalignedMembers) {
15499     const NamedDecl *ND = m.RD;
15500     if (ND->getName().empty()) {
15501       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15502         ND = TD;
15503     }
15504     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15505         << m.MD << ND << m.E->getSourceRange();
15506   }
15507   MisalignedMembers.clear();
15508 }
15509 
15510 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15511   E = E->IgnoreParens();
15512   if (!T->isPointerType() && !T->isIntegerType())
15513     return;
15514   if (isa<UnaryOperator>(E) &&
15515       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15516     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15517     if (isa<MemberExpr>(Op)) {
15518       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15519       if (MA != MisalignedMembers.end() &&
15520           (T->isIntegerType() ||
15521            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15522                                    Context.getTypeAlignInChars(
15523                                        T->getPointeeType()) <= MA->Alignment))))
15524         MisalignedMembers.erase(MA);
15525     }
15526   }
15527 }
15528 
15529 void Sema::RefersToMemberWithReducedAlignment(
15530     Expr *E,
15531     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15532         Action) {
15533   const auto *ME = dyn_cast<MemberExpr>(E);
15534   if (!ME)
15535     return;
15536 
15537   // No need to check expressions with an __unaligned-qualified type.
15538   if (E->getType().getQualifiers().hasUnaligned())
15539     return;
15540 
15541   // For a chain of MemberExpr like "a.b.c.d" this list
15542   // will keep FieldDecl's like [d, c, b].
15543   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15544   const MemberExpr *TopME = nullptr;
15545   bool AnyIsPacked = false;
15546   do {
15547     QualType BaseType = ME->getBase()->getType();
15548     if (BaseType->isDependentType())
15549       return;
15550     if (ME->isArrow())
15551       BaseType = BaseType->getPointeeType();
15552     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15553     if (RD->isInvalidDecl())
15554       return;
15555 
15556     ValueDecl *MD = ME->getMemberDecl();
15557     auto *FD = dyn_cast<FieldDecl>(MD);
15558     // We do not care about non-data members.
15559     if (!FD || FD->isInvalidDecl())
15560       return;
15561 
15562     AnyIsPacked =
15563         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15564     ReverseMemberChain.push_back(FD);
15565 
15566     TopME = ME;
15567     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15568   } while (ME);
15569   assert(TopME && "We did not compute a topmost MemberExpr!");
15570 
15571   // Not the scope of this diagnostic.
15572   if (!AnyIsPacked)
15573     return;
15574 
15575   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15576   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15577   // TODO: The innermost base of the member expression may be too complicated.
15578   // For now, just disregard these cases. This is left for future
15579   // improvement.
15580   if (!DRE && !isa<CXXThisExpr>(TopBase))
15581       return;
15582 
15583   // Alignment expected by the whole expression.
15584   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15585 
15586   // No need to do anything else with this case.
15587   if (ExpectedAlignment.isOne())
15588     return;
15589 
15590   // Synthesize offset of the whole access.
15591   CharUnits Offset;
15592   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15593        I++) {
15594     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15595   }
15596 
15597   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15598   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15599       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15600 
15601   // The base expression of the innermost MemberExpr may give
15602   // stronger guarantees than the class containing the member.
15603   if (DRE && !TopME->isArrow()) {
15604     const ValueDecl *VD = DRE->getDecl();
15605     if (!VD->getType()->isReferenceType())
15606       CompleteObjectAlignment =
15607           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15608   }
15609 
15610   // Check if the synthesized offset fulfills the alignment.
15611   if (Offset % ExpectedAlignment != 0 ||
15612       // It may fulfill the offset it but the effective alignment may still be
15613       // lower than the expected expression alignment.
15614       CompleteObjectAlignment < ExpectedAlignment) {
15615     // If this happens, we want to determine a sensible culprit of this.
15616     // Intuitively, watching the chain of member expressions from right to
15617     // left, we start with the required alignment (as required by the field
15618     // type) but some packed attribute in that chain has reduced the alignment.
15619     // It may happen that another packed structure increases it again. But if
15620     // we are here such increase has not been enough. So pointing the first
15621     // FieldDecl that either is packed or else its RecordDecl is,
15622     // seems reasonable.
15623     FieldDecl *FD = nullptr;
15624     CharUnits Alignment;
15625     for (FieldDecl *FDI : ReverseMemberChain) {
15626       if (FDI->hasAttr<PackedAttr>() ||
15627           FDI->getParent()->hasAttr<PackedAttr>()) {
15628         FD = FDI;
15629         Alignment = std::min(
15630             Context.getTypeAlignInChars(FD->getType()),
15631             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15632         break;
15633       }
15634     }
15635     assert(FD && "We did not find a packed FieldDecl!");
15636     Action(E, FD->getParent(), FD, Alignment);
15637   }
15638 }
15639 
15640 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15641   using namespace std::placeholders;
15642 
15643   RefersToMemberWithReducedAlignment(
15644       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15645                      _2, _3, _4));
15646 }
15647 
15648 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15649                                             ExprResult CallResult) {
15650   if (checkArgCount(*this, TheCall, 1))
15651     return ExprError();
15652 
15653   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15654   if (MatrixArg.isInvalid())
15655     return MatrixArg;
15656   Expr *Matrix = MatrixArg.get();
15657 
15658   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15659   if (!MType) {
15660     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15661     return ExprError();
15662   }
15663 
15664   // Create returned matrix type by swapping rows and columns of the argument
15665   // matrix type.
15666   QualType ResultType = Context.getConstantMatrixType(
15667       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15668 
15669   // Change the return type to the type of the returned matrix.
15670   TheCall->setType(ResultType);
15671 
15672   // Update call argument to use the possibly converted matrix argument.
15673   TheCall->setArg(0, Matrix);
15674   return CallResult;
15675 }
15676 
15677 // Get and verify the matrix dimensions.
15678 static llvm::Optional<unsigned>
15679 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15680   SourceLocation ErrorPos;
15681   Optional<llvm::APSInt> Value =
15682       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15683   if (!Value) {
15684     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15685         << Name;
15686     return {};
15687   }
15688   uint64_t Dim = Value->getZExtValue();
15689   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15690     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15691         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15692     return {};
15693   }
15694   return Dim;
15695 }
15696 
15697 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15698                                                   ExprResult CallResult) {
15699   if (!getLangOpts().MatrixTypes) {
15700     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15701     return ExprError();
15702   }
15703 
15704   if (checkArgCount(*this, TheCall, 4))
15705     return ExprError();
15706 
15707   unsigned PtrArgIdx = 0;
15708   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15709   Expr *RowsExpr = TheCall->getArg(1);
15710   Expr *ColumnsExpr = TheCall->getArg(2);
15711   Expr *StrideExpr = TheCall->getArg(3);
15712 
15713   bool ArgError = false;
15714 
15715   // Check pointer argument.
15716   {
15717     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15718     if (PtrConv.isInvalid())
15719       return PtrConv;
15720     PtrExpr = PtrConv.get();
15721     TheCall->setArg(0, PtrExpr);
15722     if (PtrExpr->isTypeDependent()) {
15723       TheCall->setType(Context.DependentTy);
15724       return TheCall;
15725     }
15726   }
15727 
15728   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15729   QualType ElementTy;
15730   if (!PtrTy) {
15731     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15732         << PtrArgIdx + 1;
15733     ArgError = true;
15734   } else {
15735     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15736 
15737     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15738       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15739           << PtrArgIdx + 1;
15740       ArgError = true;
15741     }
15742   }
15743 
15744   // Apply default Lvalue conversions and convert the expression to size_t.
15745   auto ApplyArgumentConversions = [this](Expr *E) {
15746     ExprResult Conv = DefaultLvalueConversion(E);
15747     if (Conv.isInvalid())
15748       return Conv;
15749 
15750     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15751   };
15752 
15753   // Apply conversion to row and column expressions.
15754   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15755   if (!RowsConv.isInvalid()) {
15756     RowsExpr = RowsConv.get();
15757     TheCall->setArg(1, RowsExpr);
15758   } else
15759     RowsExpr = nullptr;
15760 
15761   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15762   if (!ColumnsConv.isInvalid()) {
15763     ColumnsExpr = ColumnsConv.get();
15764     TheCall->setArg(2, ColumnsExpr);
15765   } else
15766     ColumnsExpr = nullptr;
15767 
15768   // If any any part of the result matrix type is still pending, just use
15769   // Context.DependentTy, until all parts are resolved.
15770   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15771       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15772     TheCall->setType(Context.DependentTy);
15773     return CallResult;
15774   }
15775 
15776   // Check row and column dimenions.
15777   llvm::Optional<unsigned> MaybeRows;
15778   if (RowsExpr)
15779     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15780 
15781   llvm::Optional<unsigned> MaybeColumns;
15782   if (ColumnsExpr)
15783     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15784 
15785   // Check stride argument.
15786   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15787   if (StrideConv.isInvalid())
15788     return ExprError();
15789   StrideExpr = StrideConv.get();
15790   TheCall->setArg(3, StrideExpr);
15791 
15792   if (MaybeRows) {
15793     if (Optional<llvm::APSInt> Value =
15794             StrideExpr->getIntegerConstantExpr(Context)) {
15795       uint64_t Stride = Value->getZExtValue();
15796       if (Stride < *MaybeRows) {
15797         Diag(StrideExpr->getBeginLoc(),
15798              diag::err_builtin_matrix_stride_too_small);
15799         ArgError = true;
15800       }
15801     }
15802   }
15803 
15804   if (ArgError || !MaybeRows || !MaybeColumns)
15805     return ExprError();
15806 
15807   TheCall->setType(
15808       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15809   return CallResult;
15810 }
15811 
15812 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15813                                                    ExprResult CallResult) {
15814   if (checkArgCount(*this, TheCall, 3))
15815     return ExprError();
15816 
15817   unsigned PtrArgIdx = 1;
15818   Expr *MatrixExpr = TheCall->getArg(0);
15819   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15820   Expr *StrideExpr = TheCall->getArg(2);
15821 
15822   bool ArgError = false;
15823 
15824   {
15825     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15826     if (MatrixConv.isInvalid())
15827       return MatrixConv;
15828     MatrixExpr = MatrixConv.get();
15829     TheCall->setArg(0, MatrixExpr);
15830   }
15831   if (MatrixExpr->isTypeDependent()) {
15832     TheCall->setType(Context.DependentTy);
15833     return TheCall;
15834   }
15835 
15836   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15837   if (!MatrixTy) {
15838     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15839     ArgError = true;
15840   }
15841 
15842   {
15843     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15844     if (PtrConv.isInvalid())
15845       return PtrConv;
15846     PtrExpr = PtrConv.get();
15847     TheCall->setArg(1, PtrExpr);
15848     if (PtrExpr->isTypeDependent()) {
15849       TheCall->setType(Context.DependentTy);
15850       return TheCall;
15851     }
15852   }
15853 
15854   // Check pointer argument.
15855   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15856   if (!PtrTy) {
15857     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15858         << PtrArgIdx + 1;
15859     ArgError = true;
15860   } else {
15861     QualType ElementTy = PtrTy->getPointeeType();
15862     if (ElementTy.isConstQualified()) {
15863       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15864       ArgError = true;
15865     }
15866     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15867     if (MatrixTy &&
15868         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15869       Diag(PtrExpr->getBeginLoc(),
15870            diag::err_builtin_matrix_pointer_arg_mismatch)
15871           << ElementTy << MatrixTy->getElementType();
15872       ArgError = true;
15873     }
15874   }
15875 
15876   // Apply default Lvalue conversions and convert the stride expression to
15877   // size_t.
15878   {
15879     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15880     if (StrideConv.isInvalid())
15881       return StrideConv;
15882 
15883     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15884     if (StrideConv.isInvalid())
15885       return StrideConv;
15886     StrideExpr = StrideConv.get();
15887     TheCall->setArg(2, StrideExpr);
15888   }
15889 
15890   // Check stride argument.
15891   if (MatrixTy) {
15892     if (Optional<llvm::APSInt> Value =
15893             StrideExpr->getIntegerConstantExpr(Context)) {
15894       uint64_t Stride = Value->getZExtValue();
15895       if (Stride < MatrixTy->getNumRows()) {
15896         Diag(StrideExpr->getBeginLoc(),
15897              diag::err_builtin_matrix_stride_too_small);
15898         ArgError = true;
15899       }
15900     }
15901   }
15902 
15903   if (ArgError)
15904     return ExprError();
15905 
15906   return CallResult;
15907 }
15908