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 (Call->getNumArgs() != 1) {
1278     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1279         << Call->getDirectCallee() << Call->getSourceRange();
1280     return true;
1281   }
1282 
1283   auto RT = Call->getArg(0)->getType();
1284   if (!RT->isPointerType() || RT->getPointeeType()
1285       .getAddressSpace() == LangAS::opencl_constant) {
1286     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1287         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1288     return true;
1289   }
1290 
1291   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1292     S.Diag(Call->getArg(0)->getBeginLoc(),
1293            diag::warn_opencl_generic_address_space_arg)
1294         << Call->getDirectCallee()->getNameInfo().getAsString()
1295         << Call->getArg(0)->getSourceRange();
1296   }
1297 
1298   RT = RT->getPointeeType();
1299   auto Qual = RT.getQualifiers();
1300   switch (BuiltinID) {
1301   case Builtin::BIto_global:
1302     Qual.setAddressSpace(LangAS::opencl_global);
1303     break;
1304   case Builtin::BIto_local:
1305     Qual.setAddressSpace(LangAS::opencl_local);
1306     break;
1307   case Builtin::BIto_private:
1308     Qual.setAddressSpace(LangAS::opencl_private);
1309     break;
1310   default:
1311     llvm_unreachable("Invalid builtin function");
1312   }
1313   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1314       RT.getUnqualifiedType(), Qual)));
1315 
1316   return false;
1317 }
1318 
1319 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1320   if (checkArgCount(S, TheCall, 1))
1321     return ExprError();
1322 
1323   // Compute __builtin_launder's parameter type from the argument.
1324   // The parameter type is:
1325   //  * The type of the argument if it's not an array or function type,
1326   //  Otherwise,
1327   //  * The decayed argument type.
1328   QualType ParamTy = [&]() {
1329     QualType ArgTy = TheCall->getArg(0)->getType();
1330     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1331       return S.Context.getPointerType(Ty->getElementType());
1332     if (ArgTy->isFunctionType()) {
1333       return S.Context.getPointerType(ArgTy);
1334     }
1335     return ArgTy;
1336   }();
1337 
1338   TheCall->setType(ParamTy);
1339 
1340   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1341     if (!ParamTy->isPointerType())
1342       return 0;
1343     if (ParamTy->isFunctionPointerType())
1344       return 1;
1345     if (ParamTy->isVoidPointerType())
1346       return 2;
1347     return llvm::Optional<unsigned>{};
1348   }();
1349   if (DiagSelect.hasValue()) {
1350     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1351         << DiagSelect.getValue() << TheCall->getSourceRange();
1352     return ExprError();
1353   }
1354 
1355   // We either have an incomplete class type, or we have a class template
1356   // whose instantiation has not been forced. Example:
1357   //
1358   //   template <class T> struct Foo { T value; };
1359   //   Foo<int> *p = nullptr;
1360   //   auto *d = __builtin_launder(p);
1361   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1362                             diag::err_incomplete_type))
1363     return ExprError();
1364 
1365   assert(ParamTy->getPointeeType()->isObjectType() &&
1366          "Unhandled non-object pointer case");
1367 
1368   InitializedEntity Entity =
1369       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1370   ExprResult Arg =
1371       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1372   if (Arg.isInvalid())
1373     return ExprError();
1374   TheCall->setArg(0, Arg.get());
1375 
1376   return TheCall;
1377 }
1378 
1379 // Emit an error and return true if the current architecture is not in the list
1380 // of supported architectures.
1381 static bool
1382 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1383                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1384   llvm::Triple::ArchType CurArch =
1385       S.getASTContext().getTargetInfo().getTriple().getArch();
1386   if (llvm::is_contained(SupportedArchs, CurArch))
1387     return false;
1388   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1389       << TheCall->getSourceRange();
1390   return true;
1391 }
1392 
1393 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1394                                  SourceLocation CallSiteLoc);
1395 
1396 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1397                                       CallExpr *TheCall) {
1398   switch (TI.getTriple().getArch()) {
1399   default:
1400     // Some builtins don't require additional checking, so just consider these
1401     // acceptable.
1402     return false;
1403   case llvm::Triple::arm:
1404   case llvm::Triple::armeb:
1405   case llvm::Triple::thumb:
1406   case llvm::Triple::thumbeb:
1407     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1408   case llvm::Triple::aarch64:
1409   case llvm::Triple::aarch64_32:
1410   case llvm::Triple::aarch64_be:
1411     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1412   case llvm::Triple::bpfeb:
1413   case llvm::Triple::bpfel:
1414     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1415   case llvm::Triple::hexagon:
1416     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1417   case llvm::Triple::mips:
1418   case llvm::Triple::mipsel:
1419   case llvm::Triple::mips64:
1420   case llvm::Triple::mips64el:
1421     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1422   case llvm::Triple::systemz:
1423     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1424   case llvm::Triple::x86:
1425   case llvm::Triple::x86_64:
1426     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1427   case llvm::Triple::ppc:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   }
1434 }
1435 
1436 ExprResult
1437 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1438                                CallExpr *TheCall) {
1439   ExprResult TheCallResult(TheCall);
1440 
1441   // Find out if any arguments are required to be integer constant expressions.
1442   unsigned ICEArguments = 0;
1443   ASTContext::GetBuiltinTypeError Error;
1444   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1445   if (Error != ASTContext::GE_None)
1446     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1447 
1448   // If any arguments are required to be ICE's, check and diagnose.
1449   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1450     // Skip arguments not required to be ICE's.
1451     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1452 
1453     llvm::APSInt Result;
1454     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1455       return true;
1456     ICEArguments &= ~(1 << ArgNo);
1457   }
1458 
1459   switch (BuiltinID) {
1460   case Builtin::BI__builtin___CFStringMakeConstantString:
1461     assert(TheCall->getNumArgs() == 1 &&
1462            "Wrong # arguments to builtin CFStringMakeConstantString");
1463     if (CheckObjCString(TheCall->getArg(0)))
1464       return ExprError();
1465     break;
1466   case Builtin::BI__builtin_ms_va_start:
1467   case Builtin::BI__builtin_stdarg_start:
1468   case Builtin::BI__builtin_va_start:
1469     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1470       return ExprError();
1471     break;
1472   case Builtin::BI__va_start: {
1473     switch (Context.getTargetInfo().getTriple().getArch()) {
1474     case llvm::Triple::aarch64:
1475     case llvm::Triple::arm:
1476     case llvm::Triple::thumb:
1477       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1478         return ExprError();
1479       break;
1480     default:
1481       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1482         return ExprError();
1483       break;
1484     }
1485     break;
1486   }
1487 
1488   // The acquire, release, and no fence variants are ARM and AArch64 only.
1489   case Builtin::BI_interlockedbittestandset_acq:
1490   case Builtin::BI_interlockedbittestandset_rel:
1491   case Builtin::BI_interlockedbittestandset_nf:
1492   case Builtin::BI_interlockedbittestandreset_acq:
1493   case Builtin::BI_interlockedbittestandreset_rel:
1494   case Builtin::BI_interlockedbittestandreset_nf:
1495     if (CheckBuiltinTargetSupport(
1496             *this, BuiltinID, TheCall,
1497             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1498       return ExprError();
1499     break;
1500 
1501   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1502   case Builtin::BI_bittest64:
1503   case Builtin::BI_bittestandcomplement64:
1504   case Builtin::BI_bittestandreset64:
1505   case Builtin::BI_bittestandset64:
1506   case Builtin::BI_interlockedbittestandreset64:
1507   case Builtin::BI_interlockedbittestandset64:
1508     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1509                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1510                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1511       return ExprError();
1512     break;
1513 
1514   case Builtin::BI__builtin_isgreater:
1515   case Builtin::BI__builtin_isgreaterequal:
1516   case Builtin::BI__builtin_isless:
1517   case Builtin::BI__builtin_islessequal:
1518   case Builtin::BI__builtin_islessgreater:
1519   case Builtin::BI__builtin_isunordered:
1520     if (SemaBuiltinUnorderedCompare(TheCall))
1521       return ExprError();
1522     break;
1523   case Builtin::BI__builtin_fpclassify:
1524     if (SemaBuiltinFPClassification(TheCall, 6))
1525       return ExprError();
1526     break;
1527   case Builtin::BI__builtin_isfinite:
1528   case Builtin::BI__builtin_isinf:
1529   case Builtin::BI__builtin_isinf_sign:
1530   case Builtin::BI__builtin_isnan:
1531   case Builtin::BI__builtin_isnormal:
1532   case Builtin::BI__builtin_signbit:
1533   case Builtin::BI__builtin_signbitf:
1534   case Builtin::BI__builtin_signbitl:
1535     if (SemaBuiltinFPClassification(TheCall, 1))
1536       return ExprError();
1537     break;
1538   case Builtin::BI__builtin_shufflevector:
1539     return SemaBuiltinShuffleVector(TheCall);
1540     // TheCall will be freed by the smart pointer here, but that's fine, since
1541     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1542   case Builtin::BI__builtin_prefetch:
1543     if (SemaBuiltinPrefetch(TheCall))
1544       return ExprError();
1545     break;
1546   case Builtin::BI__builtin_alloca_with_align:
1547     if (SemaBuiltinAllocaWithAlign(TheCall))
1548       return ExprError();
1549     LLVM_FALLTHROUGH;
1550   case Builtin::BI__builtin_alloca:
1551     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1552         << TheCall->getDirectCallee();
1553     break;
1554   case Builtin::BI__assume:
1555   case Builtin::BI__builtin_assume:
1556     if (SemaBuiltinAssume(TheCall))
1557       return ExprError();
1558     break;
1559   case Builtin::BI__builtin_assume_aligned:
1560     if (SemaBuiltinAssumeAligned(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_dynamic_object_size:
1564   case Builtin::BI__builtin_object_size:
1565     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1566       return ExprError();
1567     break;
1568   case Builtin::BI__builtin_longjmp:
1569     if (SemaBuiltinLongjmp(TheCall))
1570       return ExprError();
1571     break;
1572   case Builtin::BI__builtin_setjmp:
1573     if (SemaBuiltinSetjmp(TheCall))
1574       return ExprError();
1575     break;
1576   case Builtin::BI_setjmp:
1577   case Builtin::BI_setjmpex:
1578     if (checkArgCount(*this, TheCall, 1))
1579       return true;
1580     break;
1581   case Builtin::BI__builtin_classify_type:
1582     if (checkArgCount(*this, TheCall, 1)) return true;
1583     TheCall->setType(Context.IntTy);
1584     break;
1585   case Builtin::BI__builtin_constant_p: {
1586     if (checkArgCount(*this, TheCall, 1)) return true;
1587     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1588     if (Arg.isInvalid()) return true;
1589     TheCall->setArg(0, Arg.get());
1590     TheCall->setType(Context.IntTy);
1591     break;
1592   }
1593   case Builtin::BI__builtin_launder:
1594     return SemaBuiltinLaunder(*this, TheCall);
1595   case Builtin::BI__sync_fetch_and_add:
1596   case Builtin::BI__sync_fetch_and_add_1:
1597   case Builtin::BI__sync_fetch_and_add_2:
1598   case Builtin::BI__sync_fetch_and_add_4:
1599   case Builtin::BI__sync_fetch_and_add_8:
1600   case Builtin::BI__sync_fetch_and_add_16:
1601   case Builtin::BI__sync_fetch_and_sub:
1602   case Builtin::BI__sync_fetch_and_sub_1:
1603   case Builtin::BI__sync_fetch_and_sub_2:
1604   case Builtin::BI__sync_fetch_and_sub_4:
1605   case Builtin::BI__sync_fetch_and_sub_8:
1606   case Builtin::BI__sync_fetch_and_sub_16:
1607   case Builtin::BI__sync_fetch_and_or:
1608   case Builtin::BI__sync_fetch_and_or_1:
1609   case Builtin::BI__sync_fetch_and_or_2:
1610   case Builtin::BI__sync_fetch_and_or_4:
1611   case Builtin::BI__sync_fetch_and_or_8:
1612   case Builtin::BI__sync_fetch_and_or_16:
1613   case Builtin::BI__sync_fetch_and_and:
1614   case Builtin::BI__sync_fetch_and_and_1:
1615   case Builtin::BI__sync_fetch_and_and_2:
1616   case Builtin::BI__sync_fetch_and_and_4:
1617   case Builtin::BI__sync_fetch_and_and_8:
1618   case Builtin::BI__sync_fetch_and_and_16:
1619   case Builtin::BI__sync_fetch_and_xor:
1620   case Builtin::BI__sync_fetch_and_xor_1:
1621   case Builtin::BI__sync_fetch_and_xor_2:
1622   case Builtin::BI__sync_fetch_and_xor_4:
1623   case Builtin::BI__sync_fetch_and_xor_8:
1624   case Builtin::BI__sync_fetch_and_xor_16:
1625   case Builtin::BI__sync_fetch_and_nand:
1626   case Builtin::BI__sync_fetch_and_nand_1:
1627   case Builtin::BI__sync_fetch_and_nand_2:
1628   case Builtin::BI__sync_fetch_and_nand_4:
1629   case Builtin::BI__sync_fetch_and_nand_8:
1630   case Builtin::BI__sync_fetch_and_nand_16:
1631   case Builtin::BI__sync_add_and_fetch:
1632   case Builtin::BI__sync_add_and_fetch_1:
1633   case Builtin::BI__sync_add_and_fetch_2:
1634   case Builtin::BI__sync_add_and_fetch_4:
1635   case Builtin::BI__sync_add_and_fetch_8:
1636   case Builtin::BI__sync_add_and_fetch_16:
1637   case Builtin::BI__sync_sub_and_fetch:
1638   case Builtin::BI__sync_sub_and_fetch_1:
1639   case Builtin::BI__sync_sub_and_fetch_2:
1640   case Builtin::BI__sync_sub_and_fetch_4:
1641   case Builtin::BI__sync_sub_and_fetch_8:
1642   case Builtin::BI__sync_sub_and_fetch_16:
1643   case Builtin::BI__sync_and_and_fetch:
1644   case Builtin::BI__sync_and_and_fetch_1:
1645   case Builtin::BI__sync_and_and_fetch_2:
1646   case Builtin::BI__sync_and_and_fetch_4:
1647   case Builtin::BI__sync_and_and_fetch_8:
1648   case Builtin::BI__sync_and_and_fetch_16:
1649   case Builtin::BI__sync_or_and_fetch:
1650   case Builtin::BI__sync_or_and_fetch_1:
1651   case Builtin::BI__sync_or_and_fetch_2:
1652   case Builtin::BI__sync_or_and_fetch_4:
1653   case Builtin::BI__sync_or_and_fetch_8:
1654   case Builtin::BI__sync_or_and_fetch_16:
1655   case Builtin::BI__sync_xor_and_fetch:
1656   case Builtin::BI__sync_xor_and_fetch_1:
1657   case Builtin::BI__sync_xor_and_fetch_2:
1658   case Builtin::BI__sync_xor_and_fetch_4:
1659   case Builtin::BI__sync_xor_and_fetch_8:
1660   case Builtin::BI__sync_xor_and_fetch_16:
1661   case Builtin::BI__sync_nand_and_fetch:
1662   case Builtin::BI__sync_nand_and_fetch_1:
1663   case Builtin::BI__sync_nand_and_fetch_2:
1664   case Builtin::BI__sync_nand_and_fetch_4:
1665   case Builtin::BI__sync_nand_and_fetch_8:
1666   case Builtin::BI__sync_nand_and_fetch_16:
1667   case Builtin::BI__sync_val_compare_and_swap:
1668   case Builtin::BI__sync_val_compare_and_swap_1:
1669   case Builtin::BI__sync_val_compare_and_swap_2:
1670   case Builtin::BI__sync_val_compare_and_swap_4:
1671   case Builtin::BI__sync_val_compare_and_swap_8:
1672   case Builtin::BI__sync_val_compare_and_swap_16:
1673   case Builtin::BI__sync_bool_compare_and_swap:
1674   case Builtin::BI__sync_bool_compare_and_swap_1:
1675   case Builtin::BI__sync_bool_compare_and_swap_2:
1676   case Builtin::BI__sync_bool_compare_and_swap_4:
1677   case Builtin::BI__sync_bool_compare_and_swap_8:
1678   case Builtin::BI__sync_bool_compare_and_swap_16:
1679   case Builtin::BI__sync_lock_test_and_set:
1680   case Builtin::BI__sync_lock_test_and_set_1:
1681   case Builtin::BI__sync_lock_test_and_set_2:
1682   case Builtin::BI__sync_lock_test_and_set_4:
1683   case Builtin::BI__sync_lock_test_and_set_8:
1684   case Builtin::BI__sync_lock_test_and_set_16:
1685   case Builtin::BI__sync_lock_release:
1686   case Builtin::BI__sync_lock_release_1:
1687   case Builtin::BI__sync_lock_release_2:
1688   case Builtin::BI__sync_lock_release_4:
1689   case Builtin::BI__sync_lock_release_8:
1690   case Builtin::BI__sync_lock_release_16:
1691   case Builtin::BI__sync_swap:
1692   case Builtin::BI__sync_swap_1:
1693   case Builtin::BI__sync_swap_2:
1694   case Builtin::BI__sync_swap_4:
1695   case Builtin::BI__sync_swap_8:
1696   case Builtin::BI__sync_swap_16:
1697     return SemaBuiltinAtomicOverloaded(TheCallResult);
1698   case Builtin::BI__sync_synchronize:
1699     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1700         << TheCall->getCallee()->getSourceRange();
1701     break;
1702   case Builtin::BI__builtin_nontemporal_load:
1703   case Builtin::BI__builtin_nontemporal_store:
1704     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1705   case Builtin::BI__builtin_memcpy_inline: {
1706     clang::Expr *SizeOp = TheCall->getArg(2);
1707     // We warn about copying to or from `nullptr` pointers when `size` is
1708     // greater than 0. When `size` is value dependent we cannot evaluate its
1709     // value so we bail out.
1710     if (SizeOp->isValueDependent())
1711       break;
1712     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1713       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1714       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1715     }
1716     break;
1717   }
1718 #define BUILTIN(ID, TYPE, ATTRS)
1719 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1720   case Builtin::BI##ID: \
1721     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1722 #include "clang/Basic/Builtins.def"
1723   case Builtin::BI__annotation:
1724     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_annotation:
1728     if (SemaBuiltinAnnotation(*this, TheCall))
1729       return ExprError();
1730     break;
1731   case Builtin::BI__builtin_addressof:
1732     if (SemaBuiltinAddressof(*this, TheCall))
1733       return ExprError();
1734     break;
1735   case Builtin::BI__builtin_is_aligned:
1736   case Builtin::BI__builtin_align_up:
1737   case Builtin::BI__builtin_align_down:
1738     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__builtin_add_overflow:
1742   case Builtin::BI__builtin_sub_overflow:
1743   case Builtin::BI__builtin_mul_overflow:
1744     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_operator_new:
1748   case Builtin::BI__builtin_operator_delete: {
1749     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1750     ExprResult Res =
1751         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1752     if (Res.isInvalid())
1753       CorrectDelayedTyposInExpr(TheCallResult.get());
1754     return Res;
1755   }
1756   case Builtin::BI__builtin_dump_struct: {
1757     // We first want to ensure we are called with 2 arguments
1758     if (checkArgCount(*this, TheCall, 2))
1759       return ExprError();
1760     // Ensure that the first argument is of type 'struct XX *'
1761     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1762     const QualType PtrArgType = PtrArg->getType();
1763     if (!PtrArgType->isPointerType() ||
1764         !PtrArgType->getPointeeType()->isRecordType()) {
1765       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1766           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1767           << "structure pointer";
1768       return ExprError();
1769     }
1770 
1771     // Ensure that the second argument is of type 'FunctionType'
1772     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1773     const QualType FnPtrArgType = FnPtrArg->getType();
1774     if (!FnPtrArgType->isPointerType()) {
1775       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1776           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1777           << FnPtrArgType << "'int (*)(const char *, ...)'";
1778       return ExprError();
1779     }
1780 
1781     const auto *FuncType =
1782         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1783 
1784     if (!FuncType) {
1785       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1787           << FnPtrArgType << "'int (*)(const char *, ...)'";
1788       return ExprError();
1789     }
1790 
1791     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1792       if (!FT->getNumParams()) {
1793         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1794             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1795             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1796         return ExprError();
1797       }
1798       QualType PT = FT->getParamType(0);
1799       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1800           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1801           !PT->getPointeeType().isConstQualified()) {
1802         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1803             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1804             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1805         return ExprError();
1806       }
1807     }
1808 
1809     TheCall->setType(Context.IntTy);
1810     break;
1811   }
1812   case Builtin::BI__builtin_expect_with_probability: {
1813     // We first want to ensure we are called with 3 arguments
1814     if (checkArgCount(*this, TheCall, 3))
1815       return ExprError();
1816     // then check probability is constant float in range [0.0, 1.0]
1817     const Expr *ProbArg = TheCall->getArg(2);
1818     SmallVector<PartialDiagnosticAt, 8> Notes;
1819     Expr::EvalResult Eval;
1820     Eval.Diag = &Notes;
1821     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
1822                                           Context)) ||
1823         !Eval.Val.isFloat()) {
1824       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1825           << ProbArg->getSourceRange();
1826       for (const PartialDiagnosticAt &PDiag : Notes)
1827         Diag(PDiag.first, PDiag.second);
1828       return ExprError();
1829     }
1830     llvm::APFloat Probability = Eval.Val.getFloat();
1831     bool LoseInfo = false;
1832     Probability.convert(llvm::APFloat::IEEEdouble(),
1833                         llvm::RoundingMode::Dynamic, &LoseInfo);
1834     if (!(Probability >= llvm::APFloat(0.0) &&
1835           Probability <= llvm::APFloat(1.0))) {
1836       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1837           << ProbArg->getSourceRange();
1838       return ExprError();
1839     }
1840     break;
1841   }
1842   case Builtin::BI__builtin_preserve_access_index:
1843     if (SemaBuiltinPreserveAI(*this, TheCall))
1844       return ExprError();
1845     break;
1846   case Builtin::BI__builtin_call_with_static_chain:
1847     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1848       return ExprError();
1849     break;
1850   case Builtin::BI__exception_code:
1851   case Builtin::BI_exception_code:
1852     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1853                                  diag::err_seh___except_block))
1854       return ExprError();
1855     break;
1856   case Builtin::BI__exception_info:
1857   case Builtin::BI_exception_info:
1858     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1859                                  diag::err_seh___except_filter))
1860       return ExprError();
1861     break;
1862   case Builtin::BI__GetExceptionInfo:
1863     if (checkArgCount(*this, TheCall, 1))
1864       return ExprError();
1865 
1866     if (CheckCXXThrowOperand(
1867             TheCall->getBeginLoc(),
1868             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1869             TheCall))
1870       return ExprError();
1871 
1872     TheCall->setType(Context.VoidPtrTy);
1873     break;
1874   // OpenCL v2.0, s6.13.16 - Pipe functions
1875   case Builtin::BIread_pipe:
1876   case Builtin::BIwrite_pipe:
1877     // Since those two functions are declared with var args, we need a semantic
1878     // check for the argument.
1879     if (SemaBuiltinRWPipe(*this, TheCall))
1880       return ExprError();
1881     break;
1882   case Builtin::BIreserve_read_pipe:
1883   case Builtin::BIreserve_write_pipe:
1884   case Builtin::BIwork_group_reserve_read_pipe:
1885   case Builtin::BIwork_group_reserve_write_pipe:
1886     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1887       return ExprError();
1888     break;
1889   case Builtin::BIsub_group_reserve_read_pipe:
1890   case Builtin::BIsub_group_reserve_write_pipe:
1891     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1892         SemaBuiltinReserveRWPipe(*this, TheCall))
1893       return ExprError();
1894     break;
1895   case Builtin::BIcommit_read_pipe:
1896   case Builtin::BIcommit_write_pipe:
1897   case Builtin::BIwork_group_commit_read_pipe:
1898   case Builtin::BIwork_group_commit_write_pipe:
1899     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1900       return ExprError();
1901     break;
1902   case Builtin::BIsub_group_commit_read_pipe:
1903   case Builtin::BIsub_group_commit_write_pipe:
1904     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1905         SemaBuiltinCommitRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIget_pipe_num_packets:
1909   case Builtin::BIget_pipe_max_packets:
1910     if (SemaBuiltinPipePackets(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIto_global:
1914   case Builtin::BIto_local:
1915   case Builtin::BIto_private:
1916     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1917       return ExprError();
1918     break;
1919   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1920   case Builtin::BIenqueue_kernel:
1921     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_work_group_size:
1925   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1926     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1930   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1931     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BI__builtin_os_log_format:
1935     Cleanup.setExprNeedsCleanups(true);
1936     LLVM_FALLTHROUGH;
1937   case Builtin::BI__builtin_os_log_format_buffer_size:
1938     if (SemaBuiltinOSLogFormat(TheCall))
1939       return ExprError();
1940     break;
1941   case Builtin::BI__builtin_frame_address:
1942   case Builtin::BI__builtin_return_address: {
1943     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1944       return ExprError();
1945 
1946     // -Wframe-address warning if non-zero passed to builtin
1947     // return/frame address.
1948     Expr::EvalResult Result;
1949     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1950         Result.Val.getInt() != 0)
1951       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1952           << ((BuiltinID == Builtin::BI__builtin_return_address)
1953                   ? "__builtin_return_address"
1954                   : "__builtin_frame_address")
1955           << TheCall->getSourceRange();
1956     break;
1957   }
1958 
1959   case Builtin::BI__builtin_matrix_transpose:
1960     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1961 
1962   case Builtin::BI__builtin_matrix_column_major_load:
1963     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1964 
1965   case Builtin::BI__builtin_matrix_column_major_store:
1966     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1967   }
1968 
1969   // Since the target specific builtins for each arch overlap, only check those
1970   // of the arch we are compiling for.
1971   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1972     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1973       assert(Context.getAuxTargetInfo() &&
1974              "Aux Target Builtin, but not an aux target?");
1975 
1976       if (CheckTSBuiltinFunctionCall(
1977               *Context.getAuxTargetInfo(),
1978               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1979         return ExprError();
1980     } else {
1981       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1982                                      TheCall))
1983         return ExprError();
1984     }
1985   }
1986 
1987   return TheCallResult;
1988 }
1989 
1990 // Get the valid immediate range for the specified NEON type code.
1991 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1992   NeonTypeFlags Type(t);
1993   int IsQuad = ForceQuad ? true : Type.isQuad();
1994   switch (Type.getEltType()) {
1995   case NeonTypeFlags::Int8:
1996   case NeonTypeFlags::Poly8:
1997     return shift ? 7 : (8 << IsQuad) - 1;
1998   case NeonTypeFlags::Int16:
1999   case NeonTypeFlags::Poly16:
2000     return shift ? 15 : (4 << IsQuad) - 1;
2001   case NeonTypeFlags::Int32:
2002     return shift ? 31 : (2 << IsQuad) - 1;
2003   case NeonTypeFlags::Int64:
2004   case NeonTypeFlags::Poly64:
2005     return shift ? 63 : (1 << IsQuad) - 1;
2006   case NeonTypeFlags::Poly128:
2007     return shift ? 127 : (1 << IsQuad) - 1;
2008   case NeonTypeFlags::Float16:
2009     assert(!shift && "cannot shift float types!");
2010     return (4 << IsQuad) - 1;
2011   case NeonTypeFlags::Float32:
2012     assert(!shift && "cannot shift float types!");
2013     return (2 << IsQuad) - 1;
2014   case NeonTypeFlags::Float64:
2015     assert(!shift && "cannot shift float types!");
2016     return (1 << IsQuad) - 1;
2017   case NeonTypeFlags::BFloat16:
2018     assert(!shift && "cannot shift float types!");
2019     return (4 << IsQuad) - 1;
2020   }
2021   llvm_unreachable("Invalid NeonTypeFlag!");
2022 }
2023 
2024 /// getNeonEltType - Return the QualType corresponding to the elements of
2025 /// the vector type specified by the NeonTypeFlags.  This is used to check
2026 /// the pointer arguments for Neon load/store intrinsics.
2027 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2028                                bool IsPolyUnsigned, bool IsInt64Long) {
2029   switch (Flags.getEltType()) {
2030   case NeonTypeFlags::Int8:
2031     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2032   case NeonTypeFlags::Int16:
2033     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2034   case NeonTypeFlags::Int32:
2035     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2036   case NeonTypeFlags::Int64:
2037     if (IsInt64Long)
2038       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2039     else
2040       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2041                                 : Context.LongLongTy;
2042   case NeonTypeFlags::Poly8:
2043     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2044   case NeonTypeFlags::Poly16:
2045     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2046   case NeonTypeFlags::Poly64:
2047     if (IsInt64Long)
2048       return Context.UnsignedLongTy;
2049     else
2050       return Context.UnsignedLongLongTy;
2051   case NeonTypeFlags::Poly128:
2052     break;
2053   case NeonTypeFlags::Float16:
2054     return Context.HalfTy;
2055   case NeonTypeFlags::Float32:
2056     return Context.FloatTy;
2057   case NeonTypeFlags::Float64:
2058     return Context.DoubleTy;
2059   case NeonTypeFlags::BFloat16:
2060     return Context.BFloat16Ty;
2061   }
2062   llvm_unreachable("Invalid NeonTypeFlag!");
2063 }
2064 
2065 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2066   // Range check SVE intrinsics that take immediate values.
2067   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2068 
2069   switch (BuiltinID) {
2070   default:
2071     return false;
2072 #define GET_SVE_IMMEDIATE_CHECK
2073 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2074 #undef GET_SVE_IMMEDIATE_CHECK
2075   }
2076 
2077   // Perform all the immediate checks for this builtin call.
2078   bool HasError = false;
2079   for (auto &I : ImmChecks) {
2080     int ArgNum, CheckTy, ElementSizeInBits;
2081     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2082 
2083     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2084 
2085     // Function that checks whether the operand (ArgNum) is an immediate
2086     // that is one of the predefined values.
2087     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2088                                    int ErrDiag) -> bool {
2089       // We can't check the value of a dependent argument.
2090       Expr *Arg = TheCall->getArg(ArgNum);
2091       if (Arg->isTypeDependent() || Arg->isValueDependent())
2092         return false;
2093 
2094       // Check constant-ness first.
2095       llvm::APSInt Imm;
2096       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2097         return true;
2098 
2099       if (!CheckImm(Imm.getSExtValue()))
2100         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2101       return false;
2102     };
2103 
2104     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2105     case SVETypeFlags::ImmCheck0_31:
2106       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2107         HasError = true;
2108       break;
2109     case SVETypeFlags::ImmCheck0_13:
2110       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2111         HasError = true;
2112       break;
2113     case SVETypeFlags::ImmCheck1_16:
2114       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2115         HasError = true;
2116       break;
2117     case SVETypeFlags::ImmCheck0_7:
2118       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2119         HasError = true;
2120       break;
2121     case SVETypeFlags::ImmCheckExtract:
2122       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2123                                       (2048 / ElementSizeInBits) - 1))
2124         HasError = true;
2125       break;
2126     case SVETypeFlags::ImmCheckShiftRight:
2127       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2128         HasError = true;
2129       break;
2130     case SVETypeFlags::ImmCheckShiftRightNarrow:
2131       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2132                                       ElementSizeInBits / 2))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheckShiftLeft:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2137                                       ElementSizeInBits - 1))
2138         HasError = true;
2139       break;
2140     case SVETypeFlags::ImmCheckLaneIndex:
2141       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2142                                       (128 / (1 * ElementSizeInBits)) - 1))
2143         HasError = true;
2144       break;
2145     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2147                                       (128 / (2 * ElementSizeInBits)) - 1))
2148         HasError = true;
2149       break;
2150     case SVETypeFlags::ImmCheckLaneIndexDot:
2151       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2152                                       (128 / (4 * ElementSizeInBits)) - 1))
2153         HasError = true;
2154       break;
2155     case SVETypeFlags::ImmCheckComplexRot90_270:
2156       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2157                               diag::err_rotation_argument_to_cadd))
2158         HasError = true;
2159       break;
2160     case SVETypeFlags::ImmCheckComplexRotAll90:
2161       if (CheckImmediateInSet(
2162               [](int64_t V) {
2163                 return V == 0 || V == 90 || V == 180 || V == 270;
2164               },
2165               diag::err_rotation_argument_to_cmla))
2166         HasError = true;
2167       break;
2168     case SVETypeFlags::ImmCheck0_1:
2169       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2170         HasError = true;
2171       break;
2172     case SVETypeFlags::ImmCheck0_2:
2173       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2174         HasError = true;
2175       break;
2176     case SVETypeFlags::ImmCheck0_3:
2177       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2178         HasError = true;
2179       break;
2180     }
2181   }
2182 
2183   return HasError;
2184 }
2185 
2186 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2187                                         unsigned BuiltinID, CallExpr *TheCall) {
2188   llvm::APSInt Result;
2189   uint64_t mask = 0;
2190   unsigned TV = 0;
2191   int PtrArgNum = -1;
2192   bool HasConstPtr = false;
2193   switch (BuiltinID) {
2194 #define GET_NEON_OVERLOAD_CHECK
2195 #include "clang/Basic/arm_neon.inc"
2196 #include "clang/Basic/arm_fp16.inc"
2197 #undef GET_NEON_OVERLOAD_CHECK
2198   }
2199 
2200   // For NEON intrinsics which are overloaded on vector element type, validate
2201   // the immediate which specifies which variant to emit.
2202   unsigned ImmArg = TheCall->getNumArgs()-1;
2203   if (mask) {
2204     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2205       return true;
2206 
2207     TV = Result.getLimitedValue(64);
2208     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2209       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2210              << TheCall->getArg(ImmArg)->getSourceRange();
2211   }
2212 
2213   if (PtrArgNum >= 0) {
2214     // Check that pointer arguments have the specified type.
2215     Expr *Arg = TheCall->getArg(PtrArgNum);
2216     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2217       Arg = ICE->getSubExpr();
2218     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2219     QualType RHSTy = RHS.get()->getType();
2220 
2221     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2222     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2223                           Arch == llvm::Triple::aarch64_32 ||
2224                           Arch == llvm::Triple::aarch64_be;
2225     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2226     QualType EltTy =
2227         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2228     if (HasConstPtr)
2229       EltTy = EltTy.withConst();
2230     QualType LHSTy = Context.getPointerType(EltTy);
2231     AssignConvertType ConvTy;
2232     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2233     if (RHS.isInvalid())
2234       return true;
2235     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2236                                  RHS.get(), AA_Assigning))
2237       return true;
2238   }
2239 
2240   // For NEON intrinsics which take an immediate value as part of the
2241   // instruction, range check them here.
2242   unsigned i = 0, l = 0, u = 0;
2243   switch (BuiltinID) {
2244   default:
2245     return false;
2246   #define GET_NEON_IMMEDIATE_CHECK
2247   #include "clang/Basic/arm_neon.inc"
2248   #include "clang/Basic/arm_fp16.inc"
2249   #undef GET_NEON_IMMEDIATE_CHECK
2250   }
2251 
2252   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2253 }
2254 
2255 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2256   switch (BuiltinID) {
2257   default:
2258     return false;
2259   #include "clang/Basic/arm_mve_builtin_sema.inc"
2260   }
2261 }
2262 
2263 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2264                                        CallExpr *TheCall) {
2265   bool Err = false;
2266   switch (BuiltinID) {
2267   default:
2268     return false;
2269 #include "clang/Basic/arm_cde_builtin_sema.inc"
2270   }
2271 
2272   if (Err)
2273     return true;
2274 
2275   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2276 }
2277 
2278 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2279                                         const Expr *CoprocArg, bool WantCDE) {
2280   if (isConstantEvaluated())
2281     return false;
2282 
2283   // We can't check the value of a dependent argument.
2284   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2285     return false;
2286 
2287   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2288   int64_t CoprocNo = CoprocNoAP.getExtValue();
2289   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2290 
2291   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2292   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2293 
2294   if (IsCDECoproc != WantCDE)
2295     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2296            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2297 
2298   return false;
2299 }
2300 
2301 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2302                                         unsigned MaxWidth) {
2303   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2304           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2305           BuiltinID == ARM::BI__builtin_arm_strex ||
2306           BuiltinID == ARM::BI__builtin_arm_stlex ||
2307           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2308           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2309           BuiltinID == AArch64::BI__builtin_arm_strex ||
2310           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2311          "unexpected ARM builtin");
2312   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2313                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2314                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2315                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2316 
2317   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2318 
2319   // Ensure that we have the proper number of arguments.
2320   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2321     return true;
2322 
2323   // Inspect the pointer argument of the atomic builtin.  This should always be
2324   // a pointer type, whose element is an integral scalar or pointer type.
2325   // Because it is a pointer type, we don't have to worry about any implicit
2326   // casts here.
2327   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2328   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2329   if (PointerArgRes.isInvalid())
2330     return true;
2331   PointerArg = PointerArgRes.get();
2332 
2333   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2334   if (!pointerType) {
2335     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2336         << PointerArg->getType() << PointerArg->getSourceRange();
2337     return true;
2338   }
2339 
2340   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2341   // task is to insert the appropriate casts into the AST. First work out just
2342   // what the appropriate type is.
2343   QualType ValType = pointerType->getPointeeType();
2344   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2345   if (IsLdrex)
2346     AddrType.addConst();
2347 
2348   // Issue a warning if the cast is dodgy.
2349   CastKind CastNeeded = CK_NoOp;
2350   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2351     CastNeeded = CK_BitCast;
2352     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2353         << PointerArg->getType() << Context.getPointerType(AddrType)
2354         << AA_Passing << PointerArg->getSourceRange();
2355   }
2356 
2357   // Finally, do the cast and replace the argument with the corrected version.
2358   AddrType = Context.getPointerType(AddrType);
2359   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2360   if (PointerArgRes.isInvalid())
2361     return true;
2362   PointerArg = PointerArgRes.get();
2363 
2364   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2365 
2366   // In general, we allow ints, floats and pointers to be loaded and stored.
2367   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2368       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2369     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2370         << PointerArg->getType() << PointerArg->getSourceRange();
2371     return true;
2372   }
2373 
2374   // But ARM doesn't have instructions to deal with 128-bit versions.
2375   if (Context.getTypeSize(ValType) > MaxWidth) {
2376     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2377     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2378         << PointerArg->getType() << PointerArg->getSourceRange();
2379     return true;
2380   }
2381 
2382   switch (ValType.getObjCLifetime()) {
2383   case Qualifiers::OCL_None:
2384   case Qualifiers::OCL_ExplicitNone:
2385     // okay
2386     break;
2387 
2388   case Qualifiers::OCL_Weak:
2389   case Qualifiers::OCL_Strong:
2390   case Qualifiers::OCL_Autoreleasing:
2391     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2392         << ValType << PointerArg->getSourceRange();
2393     return true;
2394   }
2395 
2396   if (IsLdrex) {
2397     TheCall->setType(ValType);
2398     return false;
2399   }
2400 
2401   // Initialize the argument to be stored.
2402   ExprResult ValArg = TheCall->getArg(0);
2403   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2404       Context, ValType, /*consume*/ false);
2405   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2406   if (ValArg.isInvalid())
2407     return true;
2408   TheCall->setArg(0, ValArg.get());
2409 
2410   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2411   // but the custom checker bypasses all default analysis.
2412   TheCall->setType(Context.IntTy);
2413   return false;
2414 }
2415 
2416 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2417                                        CallExpr *TheCall) {
2418   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2419       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2420       BuiltinID == ARM::BI__builtin_arm_strex ||
2421       BuiltinID == ARM::BI__builtin_arm_stlex) {
2422     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2423   }
2424 
2425   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2426     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2427       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2428   }
2429 
2430   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2431       BuiltinID == ARM::BI__builtin_arm_wsr64)
2432     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2433 
2434   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2435       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2436       BuiltinID == ARM::BI__builtin_arm_wsr ||
2437       BuiltinID == ARM::BI__builtin_arm_wsrp)
2438     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2439 
2440   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2441     return true;
2442   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2443     return true;
2444   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2445     return true;
2446 
2447   // For intrinsics which take an immediate value as part of the instruction,
2448   // range check them here.
2449   // FIXME: VFP Intrinsics should error if VFP not present.
2450   switch (BuiltinID) {
2451   default: return false;
2452   case ARM::BI__builtin_arm_ssat:
2453     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2454   case ARM::BI__builtin_arm_usat:
2455     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2456   case ARM::BI__builtin_arm_ssat16:
2457     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2458   case ARM::BI__builtin_arm_usat16:
2459     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2460   case ARM::BI__builtin_arm_vcvtr_f:
2461   case ARM::BI__builtin_arm_vcvtr_d:
2462     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2463   case ARM::BI__builtin_arm_dmb:
2464   case ARM::BI__builtin_arm_dsb:
2465   case ARM::BI__builtin_arm_isb:
2466   case ARM::BI__builtin_arm_dbg:
2467     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2468   case ARM::BI__builtin_arm_cdp:
2469   case ARM::BI__builtin_arm_cdp2:
2470   case ARM::BI__builtin_arm_mcr:
2471   case ARM::BI__builtin_arm_mcr2:
2472   case ARM::BI__builtin_arm_mrc:
2473   case ARM::BI__builtin_arm_mrc2:
2474   case ARM::BI__builtin_arm_mcrr:
2475   case ARM::BI__builtin_arm_mcrr2:
2476   case ARM::BI__builtin_arm_mrrc:
2477   case ARM::BI__builtin_arm_mrrc2:
2478   case ARM::BI__builtin_arm_ldc:
2479   case ARM::BI__builtin_arm_ldcl:
2480   case ARM::BI__builtin_arm_ldc2:
2481   case ARM::BI__builtin_arm_ldc2l:
2482   case ARM::BI__builtin_arm_stc:
2483   case ARM::BI__builtin_arm_stcl:
2484   case ARM::BI__builtin_arm_stc2:
2485   case ARM::BI__builtin_arm_stc2l:
2486     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2487            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2488                                         /*WantCDE*/ false);
2489   }
2490 }
2491 
2492 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2493                                            unsigned BuiltinID,
2494                                            CallExpr *TheCall) {
2495   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2496       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2497       BuiltinID == AArch64::BI__builtin_arm_strex ||
2498       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2499     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2500   }
2501 
2502   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2503     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2504       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2505       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2506       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2507   }
2508 
2509   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2510       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2511     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2512 
2513   // Memory Tagging Extensions (MTE) Intrinsics
2514   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2515       BuiltinID == AArch64::BI__builtin_arm_addg ||
2516       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2517       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2518       BuiltinID == AArch64::BI__builtin_arm_stg ||
2519       BuiltinID == AArch64::BI__builtin_arm_subp) {
2520     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2521   }
2522 
2523   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2524       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2525       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2526       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2527     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2528 
2529   // Only check the valid encoding range. Any constant in this range would be
2530   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2531   // an exception for incorrect registers. This matches MSVC behavior.
2532   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2533       BuiltinID == AArch64::BI_WriteStatusReg)
2534     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2535 
2536   if (BuiltinID == AArch64::BI__getReg)
2537     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2538 
2539   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2540     return true;
2541 
2542   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2543     return true;
2544 
2545   // For intrinsics which take an immediate value as part of the instruction,
2546   // range check them here.
2547   unsigned i = 0, l = 0, u = 0;
2548   switch (BuiltinID) {
2549   default: return false;
2550   case AArch64::BI__builtin_arm_dmb:
2551   case AArch64::BI__builtin_arm_dsb:
2552   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2553   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2554   }
2555 
2556   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2557 }
2558 
2559 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2560                                        CallExpr *TheCall) {
2561   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2562           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2563          "unexpected ARM builtin");
2564 
2565   if (checkArgCount(*this, TheCall, 2))
2566     return true;
2567 
2568   Expr *Arg;
2569   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2570     // The second argument needs to be a constant int
2571     Arg = TheCall->getArg(1);
2572     if (!Arg->isIntegerConstantExpr(Context)) {
2573       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2574           << 2 << Arg->getSourceRange();
2575       return true;
2576     }
2577 
2578     TheCall->setType(Context.UnsignedIntTy);
2579     return false;
2580   }
2581 
2582   // The first argument needs to be a record field access.
2583   // If it is an array element access, we delay decision
2584   // to BPF backend to check whether the access is a
2585   // field access or not.
2586   Arg = TheCall->getArg(0);
2587   if (Arg->getType()->getAsPlaceholderType() ||
2588       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2589        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2590        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2591     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2592         << 1 << Arg->getSourceRange();
2593     return true;
2594   }
2595 
2596   // The second argument needs to be a constant int
2597   Arg = TheCall->getArg(1);
2598   if (!Arg->isIntegerConstantExpr(Context)) {
2599     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2600         << 2 << Arg->getSourceRange();
2601     return true;
2602   }
2603 
2604   TheCall->setType(Context.UnsignedIntTy);
2605   return false;
2606 }
2607 
2608 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2609   struct ArgInfo {
2610     uint8_t OpNum;
2611     bool IsSigned;
2612     uint8_t BitWidth;
2613     uint8_t Align;
2614   };
2615   struct BuiltinInfo {
2616     unsigned BuiltinID;
2617     ArgInfo Infos[2];
2618   };
2619 
2620   static BuiltinInfo Infos[] = {
2621     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2622     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2623     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2624     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2625     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2626     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2627     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2628     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2629     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2630     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2631     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2632 
2633     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2636     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2637     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2638     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2639     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2641     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2642     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2643     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2644 
2645     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2646     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2647     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2649     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2675     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2679     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2697                                                       {{ 1, false, 6,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2705                                                       {{ 1, false, 5,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2712                                                        { 2, false, 5,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2714                                                        { 2, false, 6,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2716                                                        { 3, false, 5,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2718                                                        { 3, false, 6,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2735                                                       {{ 2, false, 4,  0 },
2736                                                        { 3, false, 5,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2738                                                       {{ 2, false, 4,  0 },
2739                                                        { 3, false, 5,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2741                                                       {{ 2, false, 4,  0 },
2742                                                        { 3, false, 5,  0 }} },
2743     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2744                                                       {{ 2, false, 4,  0 },
2745                                                        { 3, false, 5,  0 }} },
2746     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2747     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2749     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2757                                                        { 2, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2759                                                        { 2, false, 6,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2769                                                       {{ 1, false, 4,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2772                                                       {{ 1, false, 4,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2793                                                       {{ 3, false, 1,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2798                                                       {{ 3, false, 1,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2803                                                       {{ 3, false, 1,  0 }} },
2804   };
2805 
2806   // Use a dynamically initialized static to sort the table exactly once on
2807   // first run.
2808   static const bool SortOnce =
2809       (llvm::sort(Infos,
2810                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2811                    return LHS.BuiltinID < RHS.BuiltinID;
2812                  }),
2813        true);
2814   (void)SortOnce;
2815 
2816   const BuiltinInfo *F = llvm::partition_point(
2817       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2818   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2819     return false;
2820 
2821   bool Error = false;
2822 
2823   for (const ArgInfo &A : F->Infos) {
2824     // Ignore empty ArgInfo elements.
2825     if (A.BitWidth == 0)
2826       continue;
2827 
2828     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2829     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2830     if (!A.Align) {
2831       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2832     } else {
2833       unsigned M = 1 << A.Align;
2834       Min *= M;
2835       Max *= M;
2836       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2837                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2838     }
2839   }
2840   return Error;
2841 }
2842 
2843 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2844                                            CallExpr *TheCall) {
2845   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2846 }
2847 
2848 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2849                                         unsigned BuiltinID, CallExpr *TheCall) {
2850   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2851          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2852 }
2853 
2854 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2855                                CallExpr *TheCall) {
2856 
2857   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2858       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2859     if (!TI.hasFeature("dsp"))
2860       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2861   }
2862 
2863   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2864       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2865     if (!TI.hasFeature("dspr2"))
2866       return Diag(TheCall->getBeginLoc(),
2867                   diag::err_mips_builtin_requires_dspr2);
2868   }
2869 
2870   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2871       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2872     if (!TI.hasFeature("msa"))
2873       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2874   }
2875 
2876   return false;
2877 }
2878 
2879 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2880 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2881 // ordering for DSP is unspecified. MSA is ordered by the data format used
2882 // by the underlying instruction i.e., df/m, df/n and then by size.
2883 //
2884 // FIXME: The size tests here should instead be tablegen'd along with the
2885 //        definitions from include/clang/Basic/BuiltinsMips.def.
2886 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2887 //        be too.
2888 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2889   unsigned i = 0, l = 0, u = 0, m = 0;
2890   switch (BuiltinID) {
2891   default: return false;
2892   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2893   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2894   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2895   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2896   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2897   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2898   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2899   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2900   // df/m field.
2901   // These intrinsics take an unsigned 3 bit immediate.
2902   case Mips::BI__builtin_msa_bclri_b:
2903   case Mips::BI__builtin_msa_bnegi_b:
2904   case Mips::BI__builtin_msa_bseti_b:
2905   case Mips::BI__builtin_msa_sat_s_b:
2906   case Mips::BI__builtin_msa_sat_u_b:
2907   case Mips::BI__builtin_msa_slli_b:
2908   case Mips::BI__builtin_msa_srai_b:
2909   case Mips::BI__builtin_msa_srari_b:
2910   case Mips::BI__builtin_msa_srli_b:
2911   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2912   case Mips::BI__builtin_msa_binsli_b:
2913   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2914   // These intrinsics take an unsigned 4 bit immediate.
2915   case Mips::BI__builtin_msa_bclri_h:
2916   case Mips::BI__builtin_msa_bnegi_h:
2917   case Mips::BI__builtin_msa_bseti_h:
2918   case Mips::BI__builtin_msa_sat_s_h:
2919   case Mips::BI__builtin_msa_sat_u_h:
2920   case Mips::BI__builtin_msa_slli_h:
2921   case Mips::BI__builtin_msa_srai_h:
2922   case Mips::BI__builtin_msa_srari_h:
2923   case Mips::BI__builtin_msa_srli_h:
2924   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2925   case Mips::BI__builtin_msa_binsli_h:
2926   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2927   // These intrinsics take an unsigned 5 bit immediate.
2928   // The first block of intrinsics actually have an unsigned 5 bit field,
2929   // not a df/n field.
2930   case Mips::BI__builtin_msa_cfcmsa:
2931   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2932   case Mips::BI__builtin_msa_clei_u_b:
2933   case Mips::BI__builtin_msa_clei_u_h:
2934   case Mips::BI__builtin_msa_clei_u_w:
2935   case Mips::BI__builtin_msa_clei_u_d:
2936   case Mips::BI__builtin_msa_clti_u_b:
2937   case Mips::BI__builtin_msa_clti_u_h:
2938   case Mips::BI__builtin_msa_clti_u_w:
2939   case Mips::BI__builtin_msa_clti_u_d:
2940   case Mips::BI__builtin_msa_maxi_u_b:
2941   case Mips::BI__builtin_msa_maxi_u_h:
2942   case Mips::BI__builtin_msa_maxi_u_w:
2943   case Mips::BI__builtin_msa_maxi_u_d:
2944   case Mips::BI__builtin_msa_mini_u_b:
2945   case Mips::BI__builtin_msa_mini_u_h:
2946   case Mips::BI__builtin_msa_mini_u_w:
2947   case Mips::BI__builtin_msa_mini_u_d:
2948   case Mips::BI__builtin_msa_addvi_b:
2949   case Mips::BI__builtin_msa_addvi_h:
2950   case Mips::BI__builtin_msa_addvi_w:
2951   case Mips::BI__builtin_msa_addvi_d:
2952   case Mips::BI__builtin_msa_bclri_w:
2953   case Mips::BI__builtin_msa_bnegi_w:
2954   case Mips::BI__builtin_msa_bseti_w:
2955   case Mips::BI__builtin_msa_sat_s_w:
2956   case Mips::BI__builtin_msa_sat_u_w:
2957   case Mips::BI__builtin_msa_slli_w:
2958   case Mips::BI__builtin_msa_srai_w:
2959   case Mips::BI__builtin_msa_srari_w:
2960   case Mips::BI__builtin_msa_srli_w:
2961   case Mips::BI__builtin_msa_srlri_w:
2962   case Mips::BI__builtin_msa_subvi_b:
2963   case Mips::BI__builtin_msa_subvi_h:
2964   case Mips::BI__builtin_msa_subvi_w:
2965   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2966   case Mips::BI__builtin_msa_binsli_w:
2967   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2968   // These intrinsics take an unsigned 6 bit immediate.
2969   case Mips::BI__builtin_msa_bclri_d:
2970   case Mips::BI__builtin_msa_bnegi_d:
2971   case Mips::BI__builtin_msa_bseti_d:
2972   case Mips::BI__builtin_msa_sat_s_d:
2973   case Mips::BI__builtin_msa_sat_u_d:
2974   case Mips::BI__builtin_msa_slli_d:
2975   case Mips::BI__builtin_msa_srai_d:
2976   case Mips::BI__builtin_msa_srari_d:
2977   case Mips::BI__builtin_msa_srli_d:
2978   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2979   case Mips::BI__builtin_msa_binsli_d:
2980   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2981   // These intrinsics take a signed 5 bit immediate.
2982   case Mips::BI__builtin_msa_ceqi_b:
2983   case Mips::BI__builtin_msa_ceqi_h:
2984   case Mips::BI__builtin_msa_ceqi_w:
2985   case Mips::BI__builtin_msa_ceqi_d:
2986   case Mips::BI__builtin_msa_clti_s_b:
2987   case Mips::BI__builtin_msa_clti_s_h:
2988   case Mips::BI__builtin_msa_clti_s_w:
2989   case Mips::BI__builtin_msa_clti_s_d:
2990   case Mips::BI__builtin_msa_clei_s_b:
2991   case Mips::BI__builtin_msa_clei_s_h:
2992   case Mips::BI__builtin_msa_clei_s_w:
2993   case Mips::BI__builtin_msa_clei_s_d:
2994   case Mips::BI__builtin_msa_maxi_s_b:
2995   case Mips::BI__builtin_msa_maxi_s_h:
2996   case Mips::BI__builtin_msa_maxi_s_w:
2997   case Mips::BI__builtin_msa_maxi_s_d:
2998   case Mips::BI__builtin_msa_mini_s_b:
2999   case Mips::BI__builtin_msa_mini_s_h:
3000   case Mips::BI__builtin_msa_mini_s_w:
3001   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3002   // These intrinsics take an unsigned 8 bit immediate.
3003   case Mips::BI__builtin_msa_andi_b:
3004   case Mips::BI__builtin_msa_nori_b:
3005   case Mips::BI__builtin_msa_ori_b:
3006   case Mips::BI__builtin_msa_shf_b:
3007   case Mips::BI__builtin_msa_shf_h:
3008   case Mips::BI__builtin_msa_shf_w:
3009   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3010   case Mips::BI__builtin_msa_bseli_b:
3011   case Mips::BI__builtin_msa_bmnzi_b:
3012   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3013   // df/n format
3014   // These intrinsics take an unsigned 4 bit immediate.
3015   case Mips::BI__builtin_msa_copy_s_b:
3016   case Mips::BI__builtin_msa_copy_u_b:
3017   case Mips::BI__builtin_msa_insve_b:
3018   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3019   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3020   // These intrinsics take an unsigned 3 bit immediate.
3021   case Mips::BI__builtin_msa_copy_s_h:
3022   case Mips::BI__builtin_msa_copy_u_h:
3023   case Mips::BI__builtin_msa_insve_h:
3024   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3025   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3026   // These intrinsics take an unsigned 2 bit immediate.
3027   case Mips::BI__builtin_msa_copy_s_w:
3028   case Mips::BI__builtin_msa_copy_u_w:
3029   case Mips::BI__builtin_msa_insve_w:
3030   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3031   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3032   // These intrinsics take an unsigned 1 bit immediate.
3033   case Mips::BI__builtin_msa_copy_s_d:
3034   case Mips::BI__builtin_msa_copy_u_d:
3035   case Mips::BI__builtin_msa_insve_d:
3036   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3037   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3038   // Memory offsets and immediate loads.
3039   // These intrinsics take a signed 10 bit immediate.
3040   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3041   case Mips::BI__builtin_msa_ldi_h:
3042   case Mips::BI__builtin_msa_ldi_w:
3043   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3044   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3045   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3046   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3047   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3048   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3049   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3050   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3051   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3052   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3053   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3054   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3055   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3056   }
3057 
3058   if (!m)
3059     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3060 
3061   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3062          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3063 }
3064 
3065 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3066                                        CallExpr *TheCall) {
3067   unsigned i = 0, l = 0, u = 0;
3068   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3069                       BuiltinID == PPC::BI__builtin_divdeu ||
3070                       BuiltinID == PPC::BI__builtin_bpermd;
3071   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3072   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3073                        BuiltinID == PPC::BI__builtin_divweu ||
3074                        BuiltinID == PPC::BI__builtin_divde ||
3075                        BuiltinID == PPC::BI__builtin_divdeu;
3076 
3077   if (Is64BitBltin && !IsTarget64Bit)
3078     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3079            << TheCall->getSourceRange();
3080 
3081   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3082       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3083     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3084            << TheCall->getSourceRange();
3085 
3086   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3087     if (!TI.hasFeature("vsx"))
3088       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3089              << TheCall->getSourceRange();
3090     return false;
3091   };
3092 
3093   switch (BuiltinID) {
3094   default: return false;
3095   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3096   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3097     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3098            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3099   case PPC::BI__builtin_altivec_dss:
3100     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3101   case PPC::BI__builtin_tbegin:
3102   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3103   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3104   case PPC::BI__builtin_tabortwc:
3105   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3106   case PPC::BI__builtin_tabortwci:
3107   case PPC::BI__builtin_tabortdci:
3108     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3109            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3110   case PPC::BI__builtin_altivec_dst:
3111   case PPC::BI__builtin_altivec_dstt:
3112   case PPC::BI__builtin_altivec_dstst:
3113   case PPC::BI__builtin_altivec_dststt:
3114     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3115   case PPC::BI__builtin_vsx_xxpermdi:
3116   case PPC::BI__builtin_vsx_xxsldwi:
3117     return SemaBuiltinVSX(TheCall);
3118   case PPC::BI__builtin_unpack_vector_int128:
3119     return SemaVSXCheck(TheCall) ||
3120            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3121   case PPC::BI__builtin_pack_vector_int128:
3122     return SemaVSXCheck(TheCall);
3123   case PPC::BI__builtin_altivec_vgnb:
3124      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3125   case PPC::BI__builtin_vsx_xxeval:
3126      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3127   case PPC::BI__builtin_altivec_vsldbi:
3128      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3129   case PPC::BI__builtin_altivec_vsrdbi:
3130      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3131   case PPC::BI__builtin_vsx_xxpermx:
3132      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3133   }
3134   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3135 }
3136 
3137 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3138                                           CallExpr *TheCall) {
3139   // position of memory order and scope arguments in the builtin
3140   unsigned OrderIndex, ScopeIndex;
3141   switch (BuiltinID) {
3142   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3143   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3144   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3145   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3146     OrderIndex = 2;
3147     ScopeIndex = 3;
3148     break;
3149   case AMDGPU::BI__builtin_amdgcn_fence:
3150     OrderIndex = 0;
3151     ScopeIndex = 1;
3152     break;
3153   default:
3154     return false;
3155   }
3156 
3157   ExprResult Arg = TheCall->getArg(OrderIndex);
3158   auto ArgExpr = Arg.get();
3159   Expr::EvalResult ArgResult;
3160 
3161   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3162     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3163            << ArgExpr->getType();
3164   int ord = ArgResult.Val.getInt().getZExtValue();
3165 
3166   // Check valididty of memory ordering as per C11 / C++11's memody model.
3167   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3168   case llvm::AtomicOrderingCABI::acquire:
3169   case llvm::AtomicOrderingCABI::release:
3170   case llvm::AtomicOrderingCABI::acq_rel:
3171   case llvm::AtomicOrderingCABI::seq_cst:
3172     break;
3173   default: {
3174     return Diag(ArgExpr->getBeginLoc(),
3175                 diag::warn_atomic_op_has_invalid_memory_order)
3176            << ArgExpr->getSourceRange();
3177   }
3178   }
3179 
3180   Arg = TheCall->getArg(ScopeIndex);
3181   ArgExpr = Arg.get();
3182   Expr::EvalResult ArgResult1;
3183   // Check that sync scope is a constant literal
3184   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3185                                        Context))
3186     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3187            << ArgExpr->getType();
3188 
3189   return false;
3190 }
3191 
3192 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3193                                            CallExpr *TheCall) {
3194   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3195     Expr *Arg = TheCall->getArg(0);
3196     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3197       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3198         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3199                << Arg->getSourceRange();
3200   }
3201 
3202   // For intrinsics which take an immediate value as part of the instruction,
3203   // range check them here.
3204   unsigned i = 0, l = 0, u = 0;
3205   switch (BuiltinID) {
3206   default: return false;
3207   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3208   case SystemZ::BI__builtin_s390_verimb:
3209   case SystemZ::BI__builtin_s390_verimh:
3210   case SystemZ::BI__builtin_s390_verimf:
3211   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3212   case SystemZ::BI__builtin_s390_vfaeb:
3213   case SystemZ::BI__builtin_s390_vfaeh:
3214   case SystemZ::BI__builtin_s390_vfaef:
3215   case SystemZ::BI__builtin_s390_vfaebs:
3216   case SystemZ::BI__builtin_s390_vfaehs:
3217   case SystemZ::BI__builtin_s390_vfaefs:
3218   case SystemZ::BI__builtin_s390_vfaezb:
3219   case SystemZ::BI__builtin_s390_vfaezh:
3220   case SystemZ::BI__builtin_s390_vfaezf:
3221   case SystemZ::BI__builtin_s390_vfaezbs:
3222   case SystemZ::BI__builtin_s390_vfaezhs:
3223   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3224   case SystemZ::BI__builtin_s390_vfisb:
3225   case SystemZ::BI__builtin_s390_vfidb:
3226     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3227            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3228   case SystemZ::BI__builtin_s390_vftcisb:
3229   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3230   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3231   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3232   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3233   case SystemZ::BI__builtin_s390_vstrcb:
3234   case SystemZ::BI__builtin_s390_vstrch:
3235   case SystemZ::BI__builtin_s390_vstrcf:
3236   case SystemZ::BI__builtin_s390_vstrczb:
3237   case SystemZ::BI__builtin_s390_vstrczh:
3238   case SystemZ::BI__builtin_s390_vstrczf:
3239   case SystemZ::BI__builtin_s390_vstrcbs:
3240   case SystemZ::BI__builtin_s390_vstrchs:
3241   case SystemZ::BI__builtin_s390_vstrcfs:
3242   case SystemZ::BI__builtin_s390_vstrczbs:
3243   case SystemZ::BI__builtin_s390_vstrczhs:
3244   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3245   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3246   case SystemZ::BI__builtin_s390_vfminsb:
3247   case SystemZ::BI__builtin_s390_vfmaxsb:
3248   case SystemZ::BI__builtin_s390_vfmindb:
3249   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3250   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3251   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3252   }
3253   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3254 }
3255 
3256 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3257 /// This checks that the target supports __builtin_cpu_supports and
3258 /// that the string argument is constant and valid.
3259 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3260                                    CallExpr *TheCall) {
3261   Expr *Arg = TheCall->getArg(0);
3262 
3263   // Check if the argument is a string literal.
3264   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3265     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3266            << Arg->getSourceRange();
3267 
3268   // Check the contents of the string.
3269   StringRef Feature =
3270       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3271   if (!TI.validateCpuSupports(Feature))
3272     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3273            << Arg->getSourceRange();
3274   return false;
3275 }
3276 
3277 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3278 /// This checks that the target supports __builtin_cpu_is and
3279 /// that the string argument is constant and valid.
3280 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3281   Expr *Arg = TheCall->getArg(0);
3282 
3283   // Check if the argument is a string literal.
3284   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3285     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3286            << Arg->getSourceRange();
3287 
3288   // Check the contents of the string.
3289   StringRef Feature =
3290       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3291   if (!TI.validateCpuIs(Feature))
3292     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3293            << Arg->getSourceRange();
3294   return false;
3295 }
3296 
3297 // Check if the rounding mode is legal.
3298 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3299   // Indicates if this instruction has rounding control or just SAE.
3300   bool HasRC = false;
3301 
3302   unsigned ArgNum = 0;
3303   switch (BuiltinID) {
3304   default:
3305     return false;
3306   case X86::BI__builtin_ia32_vcvttsd2si32:
3307   case X86::BI__builtin_ia32_vcvttsd2si64:
3308   case X86::BI__builtin_ia32_vcvttsd2usi32:
3309   case X86::BI__builtin_ia32_vcvttsd2usi64:
3310   case X86::BI__builtin_ia32_vcvttss2si32:
3311   case X86::BI__builtin_ia32_vcvttss2si64:
3312   case X86::BI__builtin_ia32_vcvttss2usi32:
3313   case X86::BI__builtin_ia32_vcvttss2usi64:
3314     ArgNum = 1;
3315     break;
3316   case X86::BI__builtin_ia32_maxpd512:
3317   case X86::BI__builtin_ia32_maxps512:
3318   case X86::BI__builtin_ia32_minpd512:
3319   case X86::BI__builtin_ia32_minps512:
3320     ArgNum = 2;
3321     break;
3322   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3323   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3324   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3325   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3326   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3327   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3328   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3329   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3330   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3331   case X86::BI__builtin_ia32_exp2pd_mask:
3332   case X86::BI__builtin_ia32_exp2ps_mask:
3333   case X86::BI__builtin_ia32_getexppd512_mask:
3334   case X86::BI__builtin_ia32_getexpps512_mask:
3335   case X86::BI__builtin_ia32_rcp28pd_mask:
3336   case X86::BI__builtin_ia32_rcp28ps_mask:
3337   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3338   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3339   case X86::BI__builtin_ia32_vcomisd:
3340   case X86::BI__builtin_ia32_vcomiss:
3341   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3342     ArgNum = 3;
3343     break;
3344   case X86::BI__builtin_ia32_cmppd512_mask:
3345   case X86::BI__builtin_ia32_cmpps512_mask:
3346   case X86::BI__builtin_ia32_cmpsd_mask:
3347   case X86::BI__builtin_ia32_cmpss_mask:
3348   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3349   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3350   case X86::BI__builtin_ia32_getexpss128_round_mask:
3351   case X86::BI__builtin_ia32_getmantpd512_mask:
3352   case X86::BI__builtin_ia32_getmantps512_mask:
3353   case X86::BI__builtin_ia32_maxsd_round_mask:
3354   case X86::BI__builtin_ia32_maxss_round_mask:
3355   case X86::BI__builtin_ia32_minsd_round_mask:
3356   case X86::BI__builtin_ia32_minss_round_mask:
3357   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3358   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3359   case X86::BI__builtin_ia32_reducepd512_mask:
3360   case X86::BI__builtin_ia32_reduceps512_mask:
3361   case X86::BI__builtin_ia32_rndscalepd_mask:
3362   case X86::BI__builtin_ia32_rndscaleps_mask:
3363   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3364   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3365     ArgNum = 4;
3366     break;
3367   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3368   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3369   case X86::BI__builtin_ia32_fixupimmps512_mask:
3370   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3371   case X86::BI__builtin_ia32_fixupimmsd_mask:
3372   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3373   case X86::BI__builtin_ia32_fixupimmss_mask:
3374   case X86::BI__builtin_ia32_fixupimmss_maskz:
3375   case X86::BI__builtin_ia32_getmantsd_round_mask:
3376   case X86::BI__builtin_ia32_getmantss_round_mask:
3377   case X86::BI__builtin_ia32_rangepd512_mask:
3378   case X86::BI__builtin_ia32_rangeps512_mask:
3379   case X86::BI__builtin_ia32_rangesd128_round_mask:
3380   case X86::BI__builtin_ia32_rangess128_round_mask:
3381   case X86::BI__builtin_ia32_reducesd_mask:
3382   case X86::BI__builtin_ia32_reducess_mask:
3383   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3384   case X86::BI__builtin_ia32_rndscaless_round_mask:
3385     ArgNum = 5;
3386     break;
3387   case X86::BI__builtin_ia32_vcvtsd2si64:
3388   case X86::BI__builtin_ia32_vcvtsd2si32:
3389   case X86::BI__builtin_ia32_vcvtsd2usi32:
3390   case X86::BI__builtin_ia32_vcvtsd2usi64:
3391   case X86::BI__builtin_ia32_vcvtss2si32:
3392   case X86::BI__builtin_ia32_vcvtss2si64:
3393   case X86::BI__builtin_ia32_vcvtss2usi32:
3394   case X86::BI__builtin_ia32_vcvtss2usi64:
3395   case X86::BI__builtin_ia32_sqrtpd512:
3396   case X86::BI__builtin_ia32_sqrtps512:
3397     ArgNum = 1;
3398     HasRC = true;
3399     break;
3400   case X86::BI__builtin_ia32_addpd512:
3401   case X86::BI__builtin_ia32_addps512:
3402   case X86::BI__builtin_ia32_divpd512:
3403   case X86::BI__builtin_ia32_divps512:
3404   case X86::BI__builtin_ia32_mulpd512:
3405   case X86::BI__builtin_ia32_mulps512:
3406   case X86::BI__builtin_ia32_subpd512:
3407   case X86::BI__builtin_ia32_subps512:
3408   case X86::BI__builtin_ia32_cvtsi2sd64:
3409   case X86::BI__builtin_ia32_cvtsi2ss32:
3410   case X86::BI__builtin_ia32_cvtsi2ss64:
3411   case X86::BI__builtin_ia32_cvtusi2sd64:
3412   case X86::BI__builtin_ia32_cvtusi2ss32:
3413   case X86::BI__builtin_ia32_cvtusi2ss64:
3414     ArgNum = 2;
3415     HasRC = true;
3416     break;
3417   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3418   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3419   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3420   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3421   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3422   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3423   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3424   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3425   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3426   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3427   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3428   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3429   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3430   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3431   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3432     ArgNum = 3;
3433     HasRC = true;
3434     break;
3435   case X86::BI__builtin_ia32_addss_round_mask:
3436   case X86::BI__builtin_ia32_addsd_round_mask:
3437   case X86::BI__builtin_ia32_divss_round_mask:
3438   case X86::BI__builtin_ia32_divsd_round_mask:
3439   case X86::BI__builtin_ia32_mulss_round_mask:
3440   case X86::BI__builtin_ia32_mulsd_round_mask:
3441   case X86::BI__builtin_ia32_subss_round_mask:
3442   case X86::BI__builtin_ia32_subsd_round_mask:
3443   case X86::BI__builtin_ia32_scalefpd512_mask:
3444   case X86::BI__builtin_ia32_scalefps512_mask:
3445   case X86::BI__builtin_ia32_scalefsd_round_mask:
3446   case X86::BI__builtin_ia32_scalefss_round_mask:
3447   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3448   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3449   case X86::BI__builtin_ia32_sqrtss_round_mask:
3450   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3451   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3452   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3453   case X86::BI__builtin_ia32_vfmaddss3_mask:
3454   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3455   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3456   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3457   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3458   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3459   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3460   case X86::BI__builtin_ia32_vfmaddps512_mask:
3461   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3462   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3463   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3464   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3465   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3466   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3467   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3468   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3469   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3470   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3471   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3472     ArgNum = 4;
3473     HasRC = true;
3474     break;
3475   }
3476 
3477   llvm::APSInt Result;
3478 
3479   // We can't check the value of a dependent argument.
3480   Expr *Arg = TheCall->getArg(ArgNum);
3481   if (Arg->isTypeDependent() || Arg->isValueDependent())
3482     return false;
3483 
3484   // Check constant-ness first.
3485   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3486     return true;
3487 
3488   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3489   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3490   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3491   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3492   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3493       Result == 8/*ROUND_NO_EXC*/ ||
3494       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3495       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3496     return false;
3497 
3498   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3499          << Arg->getSourceRange();
3500 }
3501 
3502 // Check if the gather/scatter scale is legal.
3503 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3504                                              CallExpr *TheCall) {
3505   unsigned ArgNum = 0;
3506   switch (BuiltinID) {
3507   default:
3508     return false;
3509   case X86::BI__builtin_ia32_gatherpfdpd:
3510   case X86::BI__builtin_ia32_gatherpfdps:
3511   case X86::BI__builtin_ia32_gatherpfqpd:
3512   case X86::BI__builtin_ia32_gatherpfqps:
3513   case X86::BI__builtin_ia32_scatterpfdpd:
3514   case X86::BI__builtin_ia32_scatterpfdps:
3515   case X86::BI__builtin_ia32_scatterpfqpd:
3516   case X86::BI__builtin_ia32_scatterpfqps:
3517     ArgNum = 3;
3518     break;
3519   case X86::BI__builtin_ia32_gatherd_pd:
3520   case X86::BI__builtin_ia32_gatherd_pd256:
3521   case X86::BI__builtin_ia32_gatherq_pd:
3522   case X86::BI__builtin_ia32_gatherq_pd256:
3523   case X86::BI__builtin_ia32_gatherd_ps:
3524   case X86::BI__builtin_ia32_gatherd_ps256:
3525   case X86::BI__builtin_ia32_gatherq_ps:
3526   case X86::BI__builtin_ia32_gatherq_ps256:
3527   case X86::BI__builtin_ia32_gatherd_q:
3528   case X86::BI__builtin_ia32_gatherd_q256:
3529   case X86::BI__builtin_ia32_gatherq_q:
3530   case X86::BI__builtin_ia32_gatherq_q256:
3531   case X86::BI__builtin_ia32_gatherd_d:
3532   case X86::BI__builtin_ia32_gatherd_d256:
3533   case X86::BI__builtin_ia32_gatherq_d:
3534   case X86::BI__builtin_ia32_gatherq_d256:
3535   case X86::BI__builtin_ia32_gather3div2df:
3536   case X86::BI__builtin_ia32_gather3div2di:
3537   case X86::BI__builtin_ia32_gather3div4df:
3538   case X86::BI__builtin_ia32_gather3div4di:
3539   case X86::BI__builtin_ia32_gather3div4sf:
3540   case X86::BI__builtin_ia32_gather3div4si:
3541   case X86::BI__builtin_ia32_gather3div8sf:
3542   case X86::BI__builtin_ia32_gather3div8si:
3543   case X86::BI__builtin_ia32_gather3siv2df:
3544   case X86::BI__builtin_ia32_gather3siv2di:
3545   case X86::BI__builtin_ia32_gather3siv4df:
3546   case X86::BI__builtin_ia32_gather3siv4di:
3547   case X86::BI__builtin_ia32_gather3siv4sf:
3548   case X86::BI__builtin_ia32_gather3siv4si:
3549   case X86::BI__builtin_ia32_gather3siv8sf:
3550   case X86::BI__builtin_ia32_gather3siv8si:
3551   case X86::BI__builtin_ia32_gathersiv8df:
3552   case X86::BI__builtin_ia32_gathersiv16sf:
3553   case X86::BI__builtin_ia32_gatherdiv8df:
3554   case X86::BI__builtin_ia32_gatherdiv16sf:
3555   case X86::BI__builtin_ia32_gathersiv8di:
3556   case X86::BI__builtin_ia32_gathersiv16si:
3557   case X86::BI__builtin_ia32_gatherdiv8di:
3558   case X86::BI__builtin_ia32_gatherdiv16si:
3559   case X86::BI__builtin_ia32_scatterdiv2df:
3560   case X86::BI__builtin_ia32_scatterdiv2di:
3561   case X86::BI__builtin_ia32_scatterdiv4df:
3562   case X86::BI__builtin_ia32_scatterdiv4di:
3563   case X86::BI__builtin_ia32_scatterdiv4sf:
3564   case X86::BI__builtin_ia32_scatterdiv4si:
3565   case X86::BI__builtin_ia32_scatterdiv8sf:
3566   case X86::BI__builtin_ia32_scatterdiv8si:
3567   case X86::BI__builtin_ia32_scattersiv2df:
3568   case X86::BI__builtin_ia32_scattersiv2di:
3569   case X86::BI__builtin_ia32_scattersiv4df:
3570   case X86::BI__builtin_ia32_scattersiv4di:
3571   case X86::BI__builtin_ia32_scattersiv4sf:
3572   case X86::BI__builtin_ia32_scattersiv4si:
3573   case X86::BI__builtin_ia32_scattersiv8sf:
3574   case X86::BI__builtin_ia32_scattersiv8si:
3575   case X86::BI__builtin_ia32_scattersiv8df:
3576   case X86::BI__builtin_ia32_scattersiv16sf:
3577   case X86::BI__builtin_ia32_scatterdiv8df:
3578   case X86::BI__builtin_ia32_scatterdiv16sf:
3579   case X86::BI__builtin_ia32_scattersiv8di:
3580   case X86::BI__builtin_ia32_scattersiv16si:
3581   case X86::BI__builtin_ia32_scatterdiv8di:
3582   case X86::BI__builtin_ia32_scatterdiv16si:
3583     ArgNum = 4;
3584     break;
3585   }
3586 
3587   llvm::APSInt Result;
3588 
3589   // We can't check the value of a dependent argument.
3590   Expr *Arg = TheCall->getArg(ArgNum);
3591   if (Arg->isTypeDependent() || Arg->isValueDependent())
3592     return false;
3593 
3594   // Check constant-ness first.
3595   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3596     return true;
3597 
3598   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3599     return false;
3600 
3601   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3602          << Arg->getSourceRange();
3603 }
3604 
3605 enum { TileRegLow = 0, TileRegHigh = 7 };
3606 
3607 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3608                                     ArrayRef<int> ArgNums) {
3609   for (int ArgNum : ArgNums) {
3610     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3611       return true;
3612   }
3613   return false;
3614 }
3615 
3616 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum) {
3617   return SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh);
3618 }
3619 
3620 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3621                                         ArrayRef<int> ArgNums) {
3622   // Because the max number of tile register is TileRegHigh + 1, so here we use
3623   // each bit to represent the usage of them in bitset.
3624   std::bitset<TileRegHigh + 1> ArgValues;
3625   for (int ArgNum : ArgNums) {
3626     llvm::APSInt Arg;
3627     SemaBuiltinConstantArg(TheCall, ArgNum, Arg);
3628     int ArgExtValue = Arg.getExtValue();
3629     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3630            "Incorrect tile register num.");
3631     if (ArgValues.test(ArgExtValue))
3632       return Diag(TheCall->getBeginLoc(),
3633                   diag::err_x86_builtin_tile_arg_duplicate)
3634              << TheCall->getArg(ArgNum)->getSourceRange();
3635     ArgValues.set(ArgExtValue);
3636   }
3637   return false;
3638 }
3639 
3640 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3641                                                 ArrayRef<int> ArgNums) {
3642   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3643          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3644 }
3645 
3646 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3647   switch (BuiltinID) {
3648   default:
3649     return false;
3650   case X86::BI__builtin_ia32_tileloadd64:
3651   case X86::BI__builtin_ia32_tileloaddt164:
3652   case X86::BI__builtin_ia32_tilestored64:
3653   case X86::BI__builtin_ia32_tilezero:
3654     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3655   case X86::BI__builtin_ia32_tdpbssd:
3656   case X86::BI__builtin_ia32_tdpbsud:
3657   case X86::BI__builtin_ia32_tdpbusd:
3658   case X86::BI__builtin_ia32_tdpbuud:
3659   case X86::BI__builtin_ia32_tdpbf16ps:
3660     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3661   }
3662 }
3663 static bool isX86_32Builtin(unsigned BuiltinID) {
3664   // These builtins only work on x86-32 targets.
3665   switch (BuiltinID) {
3666   case X86::BI__builtin_ia32_readeflags_u32:
3667   case X86::BI__builtin_ia32_writeeflags_u32:
3668     return true;
3669   }
3670 
3671   return false;
3672 }
3673 
3674 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3675                                        CallExpr *TheCall) {
3676   if (BuiltinID == X86::BI__builtin_cpu_supports)
3677     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3678 
3679   if (BuiltinID == X86::BI__builtin_cpu_is)
3680     return SemaBuiltinCpuIs(*this, TI, TheCall);
3681 
3682   // Check for 32-bit only builtins on a 64-bit target.
3683   const llvm::Triple &TT = TI.getTriple();
3684   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3685     return Diag(TheCall->getCallee()->getBeginLoc(),
3686                 diag::err_32_bit_builtin_64_bit_tgt);
3687 
3688   // If the intrinsic has rounding or SAE make sure its valid.
3689   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3690     return true;
3691 
3692   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3693   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3694     return true;
3695 
3696   // If the intrinsic has a tile arguments, make sure they are valid.
3697   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3698     return true;
3699 
3700   // For intrinsics which take an immediate value as part of the instruction,
3701   // range check them here.
3702   int i = 0, l = 0, u = 0;
3703   switch (BuiltinID) {
3704   default:
3705     return false;
3706   case X86::BI__builtin_ia32_vec_ext_v2si:
3707   case X86::BI__builtin_ia32_vec_ext_v2di:
3708   case X86::BI__builtin_ia32_vextractf128_pd256:
3709   case X86::BI__builtin_ia32_vextractf128_ps256:
3710   case X86::BI__builtin_ia32_vextractf128_si256:
3711   case X86::BI__builtin_ia32_extract128i256:
3712   case X86::BI__builtin_ia32_extractf64x4_mask:
3713   case X86::BI__builtin_ia32_extracti64x4_mask:
3714   case X86::BI__builtin_ia32_extractf32x8_mask:
3715   case X86::BI__builtin_ia32_extracti32x8_mask:
3716   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3717   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3718   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3719   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3720     i = 1; l = 0; u = 1;
3721     break;
3722   case X86::BI__builtin_ia32_vec_set_v2di:
3723   case X86::BI__builtin_ia32_vinsertf128_pd256:
3724   case X86::BI__builtin_ia32_vinsertf128_ps256:
3725   case X86::BI__builtin_ia32_vinsertf128_si256:
3726   case X86::BI__builtin_ia32_insert128i256:
3727   case X86::BI__builtin_ia32_insertf32x8:
3728   case X86::BI__builtin_ia32_inserti32x8:
3729   case X86::BI__builtin_ia32_insertf64x4:
3730   case X86::BI__builtin_ia32_inserti64x4:
3731   case X86::BI__builtin_ia32_insertf64x2_256:
3732   case X86::BI__builtin_ia32_inserti64x2_256:
3733   case X86::BI__builtin_ia32_insertf32x4_256:
3734   case X86::BI__builtin_ia32_inserti32x4_256:
3735     i = 2; l = 0; u = 1;
3736     break;
3737   case X86::BI__builtin_ia32_vpermilpd:
3738   case X86::BI__builtin_ia32_vec_ext_v4hi:
3739   case X86::BI__builtin_ia32_vec_ext_v4si:
3740   case X86::BI__builtin_ia32_vec_ext_v4sf:
3741   case X86::BI__builtin_ia32_vec_ext_v4di:
3742   case X86::BI__builtin_ia32_extractf32x4_mask:
3743   case X86::BI__builtin_ia32_extracti32x4_mask:
3744   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3745   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3746     i = 1; l = 0; u = 3;
3747     break;
3748   case X86::BI_mm_prefetch:
3749   case X86::BI__builtin_ia32_vec_ext_v8hi:
3750   case X86::BI__builtin_ia32_vec_ext_v8si:
3751     i = 1; l = 0; u = 7;
3752     break;
3753   case X86::BI__builtin_ia32_sha1rnds4:
3754   case X86::BI__builtin_ia32_blendpd:
3755   case X86::BI__builtin_ia32_shufpd:
3756   case X86::BI__builtin_ia32_vec_set_v4hi:
3757   case X86::BI__builtin_ia32_vec_set_v4si:
3758   case X86::BI__builtin_ia32_vec_set_v4di:
3759   case X86::BI__builtin_ia32_shuf_f32x4_256:
3760   case X86::BI__builtin_ia32_shuf_f64x2_256:
3761   case X86::BI__builtin_ia32_shuf_i32x4_256:
3762   case X86::BI__builtin_ia32_shuf_i64x2_256:
3763   case X86::BI__builtin_ia32_insertf64x2_512:
3764   case X86::BI__builtin_ia32_inserti64x2_512:
3765   case X86::BI__builtin_ia32_insertf32x4:
3766   case X86::BI__builtin_ia32_inserti32x4:
3767     i = 2; l = 0; u = 3;
3768     break;
3769   case X86::BI__builtin_ia32_vpermil2pd:
3770   case X86::BI__builtin_ia32_vpermil2pd256:
3771   case X86::BI__builtin_ia32_vpermil2ps:
3772   case X86::BI__builtin_ia32_vpermil2ps256:
3773     i = 3; l = 0; u = 3;
3774     break;
3775   case X86::BI__builtin_ia32_cmpb128_mask:
3776   case X86::BI__builtin_ia32_cmpw128_mask:
3777   case X86::BI__builtin_ia32_cmpd128_mask:
3778   case X86::BI__builtin_ia32_cmpq128_mask:
3779   case X86::BI__builtin_ia32_cmpb256_mask:
3780   case X86::BI__builtin_ia32_cmpw256_mask:
3781   case X86::BI__builtin_ia32_cmpd256_mask:
3782   case X86::BI__builtin_ia32_cmpq256_mask:
3783   case X86::BI__builtin_ia32_cmpb512_mask:
3784   case X86::BI__builtin_ia32_cmpw512_mask:
3785   case X86::BI__builtin_ia32_cmpd512_mask:
3786   case X86::BI__builtin_ia32_cmpq512_mask:
3787   case X86::BI__builtin_ia32_ucmpb128_mask:
3788   case X86::BI__builtin_ia32_ucmpw128_mask:
3789   case X86::BI__builtin_ia32_ucmpd128_mask:
3790   case X86::BI__builtin_ia32_ucmpq128_mask:
3791   case X86::BI__builtin_ia32_ucmpb256_mask:
3792   case X86::BI__builtin_ia32_ucmpw256_mask:
3793   case X86::BI__builtin_ia32_ucmpd256_mask:
3794   case X86::BI__builtin_ia32_ucmpq256_mask:
3795   case X86::BI__builtin_ia32_ucmpb512_mask:
3796   case X86::BI__builtin_ia32_ucmpw512_mask:
3797   case X86::BI__builtin_ia32_ucmpd512_mask:
3798   case X86::BI__builtin_ia32_ucmpq512_mask:
3799   case X86::BI__builtin_ia32_vpcomub:
3800   case X86::BI__builtin_ia32_vpcomuw:
3801   case X86::BI__builtin_ia32_vpcomud:
3802   case X86::BI__builtin_ia32_vpcomuq:
3803   case X86::BI__builtin_ia32_vpcomb:
3804   case X86::BI__builtin_ia32_vpcomw:
3805   case X86::BI__builtin_ia32_vpcomd:
3806   case X86::BI__builtin_ia32_vpcomq:
3807   case X86::BI__builtin_ia32_vec_set_v8hi:
3808   case X86::BI__builtin_ia32_vec_set_v8si:
3809     i = 2; l = 0; u = 7;
3810     break;
3811   case X86::BI__builtin_ia32_vpermilpd256:
3812   case X86::BI__builtin_ia32_roundps:
3813   case X86::BI__builtin_ia32_roundpd:
3814   case X86::BI__builtin_ia32_roundps256:
3815   case X86::BI__builtin_ia32_roundpd256:
3816   case X86::BI__builtin_ia32_getmantpd128_mask:
3817   case X86::BI__builtin_ia32_getmantpd256_mask:
3818   case X86::BI__builtin_ia32_getmantps128_mask:
3819   case X86::BI__builtin_ia32_getmantps256_mask:
3820   case X86::BI__builtin_ia32_getmantpd512_mask:
3821   case X86::BI__builtin_ia32_getmantps512_mask:
3822   case X86::BI__builtin_ia32_vec_ext_v16qi:
3823   case X86::BI__builtin_ia32_vec_ext_v16hi:
3824     i = 1; l = 0; u = 15;
3825     break;
3826   case X86::BI__builtin_ia32_pblendd128:
3827   case X86::BI__builtin_ia32_blendps:
3828   case X86::BI__builtin_ia32_blendpd256:
3829   case X86::BI__builtin_ia32_shufpd256:
3830   case X86::BI__builtin_ia32_roundss:
3831   case X86::BI__builtin_ia32_roundsd:
3832   case X86::BI__builtin_ia32_rangepd128_mask:
3833   case X86::BI__builtin_ia32_rangepd256_mask:
3834   case X86::BI__builtin_ia32_rangepd512_mask:
3835   case X86::BI__builtin_ia32_rangeps128_mask:
3836   case X86::BI__builtin_ia32_rangeps256_mask:
3837   case X86::BI__builtin_ia32_rangeps512_mask:
3838   case X86::BI__builtin_ia32_getmantsd_round_mask:
3839   case X86::BI__builtin_ia32_getmantss_round_mask:
3840   case X86::BI__builtin_ia32_vec_set_v16qi:
3841   case X86::BI__builtin_ia32_vec_set_v16hi:
3842     i = 2; l = 0; u = 15;
3843     break;
3844   case X86::BI__builtin_ia32_vec_ext_v32qi:
3845     i = 1; l = 0; u = 31;
3846     break;
3847   case X86::BI__builtin_ia32_cmpps:
3848   case X86::BI__builtin_ia32_cmpss:
3849   case X86::BI__builtin_ia32_cmppd:
3850   case X86::BI__builtin_ia32_cmpsd:
3851   case X86::BI__builtin_ia32_cmpps256:
3852   case X86::BI__builtin_ia32_cmppd256:
3853   case X86::BI__builtin_ia32_cmpps128_mask:
3854   case X86::BI__builtin_ia32_cmppd128_mask:
3855   case X86::BI__builtin_ia32_cmpps256_mask:
3856   case X86::BI__builtin_ia32_cmppd256_mask:
3857   case X86::BI__builtin_ia32_cmpps512_mask:
3858   case X86::BI__builtin_ia32_cmppd512_mask:
3859   case X86::BI__builtin_ia32_cmpsd_mask:
3860   case X86::BI__builtin_ia32_cmpss_mask:
3861   case X86::BI__builtin_ia32_vec_set_v32qi:
3862     i = 2; l = 0; u = 31;
3863     break;
3864   case X86::BI__builtin_ia32_permdf256:
3865   case X86::BI__builtin_ia32_permdi256:
3866   case X86::BI__builtin_ia32_permdf512:
3867   case X86::BI__builtin_ia32_permdi512:
3868   case X86::BI__builtin_ia32_vpermilps:
3869   case X86::BI__builtin_ia32_vpermilps256:
3870   case X86::BI__builtin_ia32_vpermilpd512:
3871   case X86::BI__builtin_ia32_vpermilps512:
3872   case X86::BI__builtin_ia32_pshufd:
3873   case X86::BI__builtin_ia32_pshufd256:
3874   case X86::BI__builtin_ia32_pshufd512:
3875   case X86::BI__builtin_ia32_pshufhw:
3876   case X86::BI__builtin_ia32_pshufhw256:
3877   case X86::BI__builtin_ia32_pshufhw512:
3878   case X86::BI__builtin_ia32_pshuflw:
3879   case X86::BI__builtin_ia32_pshuflw256:
3880   case X86::BI__builtin_ia32_pshuflw512:
3881   case X86::BI__builtin_ia32_vcvtps2ph:
3882   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3883   case X86::BI__builtin_ia32_vcvtps2ph256:
3884   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3885   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3886   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3887   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3888   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3889   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3890   case X86::BI__builtin_ia32_rndscaleps_mask:
3891   case X86::BI__builtin_ia32_rndscalepd_mask:
3892   case X86::BI__builtin_ia32_reducepd128_mask:
3893   case X86::BI__builtin_ia32_reducepd256_mask:
3894   case X86::BI__builtin_ia32_reducepd512_mask:
3895   case X86::BI__builtin_ia32_reduceps128_mask:
3896   case X86::BI__builtin_ia32_reduceps256_mask:
3897   case X86::BI__builtin_ia32_reduceps512_mask:
3898   case X86::BI__builtin_ia32_prold512:
3899   case X86::BI__builtin_ia32_prolq512:
3900   case X86::BI__builtin_ia32_prold128:
3901   case X86::BI__builtin_ia32_prold256:
3902   case X86::BI__builtin_ia32_prolq128:
3903   case X86::BI__builtin_ia32_prolq256:
3904   case X86::BI__builtin_ia32_prord512:
3905   case X86::BI__builtin_ia32_prorq512:
3906   case X86::BI__builtin_ia32_prord128:
3907   case X86::BI__builtin_ia32_prord256:
3908   case X86::BI__builtin_ia32_prorq128:
3909   case X86::BI__builtin_ia32_prorq256:
3910   case X86::BI__builtin_ia32_fpclasspd128_mask:
3911   case X86::BI__builtin_ia32_fpclasspd256_mask:
3912   case X86::BI__builtin_ia32_fpclassps128_mask:
3913   case X86::BI__builtin_ia32_fpclassps256_mask:
3914   case X86::BI__builtin_ia32_fpclassps512_mask:
3915   case X86::BI__builtin_ia32_fpclasspd512_mask:
3916   case X86::BI__builtin_ia32_fpclasssd_mask:
3917   case X86::BI__builtin_ia32_fpclassss_mask:
3918   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3919   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3920   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3921   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3922   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3923   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3924   case X86::BI__builtin_ia32_kshiftliqi:
3925   case X86::BI__builtin_ia32_kshiftlihi:
3926   case X86::BI__builtin_ia32_kshiftlisi:
3927   case X86::BI__builtin_ia32_kshiftlidi:
3928   case X86::BI__builtin_ia32_kshiftriqi:
3929   case X86::BI__builtin_ia32_kshiftrihi:
3930   case X86::BI__builtin_ia32_kshiftrisi:
3931   case X86::BI__builtin_ia32_kshiftridi:
3932     i = 1; l = 0; u = 255;
3933     break;
3934   case X86::BI__builtin_ia32_vperm2f128_pd256:
3935   case X86::BI__builtin_ia32_vperm2f128_ps256:
3936   case X86::BI__builtin_ia32_vperm2f128_si256:
3937   case X86::BI__builtin_ia32_permti256:
3938   case X86::BI__builtin_ia32_pblendw128:
3939   case X86::BI__builtin_ia32_pblendw256:
3940   case X86::BI__builtin_ia32_blendps256:
3941   case X86::BI__builtin_ia32_pblendd256:
3942   case X86::BI__builtin_ia32_palignr128:
3943   case X86::BI__builtin_ia32_palignr256:
3944   case X86::BI__builtin_ia32_palignr512:
3945   case X86::BI__builtin_ia32_alignq512:
3946   case X86::BI__builtin_ia32_alignd512:
3947   case X86::BI__builtin_ia32_alignd128:
3948   case X86::BI__builtin_ia32_alignd256:
3949   case X86::BI__builtin_ia32_alignq128:
3950   case X86::BI__builtin_ia32_alignq256:
3951   case X86::BI__builtin_ia32_vcomisd:
3952   case X86::BI__builtin_ia32_vcomiss:
3953   case X86::BI__builtin_ia32_shuf_f32x4:
3954   case X86::BI__builtin_ia32_shuf_f64x2:
3955   case X86::BI__builtin_ia32_shuf_i32x4:
3956   case X86::BI__builtin_ia32_shuf_i64x2:
3957   case X86::BI__builtin_ia32_shufpd512:
3958   case X86::BI__builtin_ia32_shufps:
3959   case X86::BI__builtin_ia32_shufps256:
3960   case X86::BI__builtin_ia32_shufps512:
3961   case X86::BI__builtin_ia32_dbpsadbw128:
3962   case X86::BI__builtin_ia32_dbpsadbw256:
3963   case X86::BI__builtin_ia32_dbpsadbw512:
3964   case X86::BI__builtin_ia32_vpshldd128:
3965   case X86::BI__builtin_ia32_vpshldd256:
3966   case X86::BI__builtin_ia32_vpshldd512:
3967   case X86::BI__builtin_ia32_vpshldq128:
3968   case X86::BI__builtin_ia32_vpshldq256:
3969   case X86::BI__builtin_ia32_vpshldq512:
3970   case X86::BI__builtin_ia32_vpshldw128:
3971   case X86::BI__builtin_ia32_vpshldw256:
3972   case X86::BI__builtin_ia32_vpshldw512:
3973   case X86::BI__builtin_ia32_vpshrdd128:
3974   case X86::BI__builtin_ia32_vpshrdd256:
3975   case X86::BI__builtin_ia32_vpshrdd512:
3976   case X86::BI__builtin_ia32_vpshrdq128:
3977   case X86::BI__builtin_ia32_vpshrdq256:
3978   case X86::BI__builtin_ia32_vpshrdq512:
3979   case X86::BI__builtin_ia32_vpshrdw128:
3980   case X86::BI__builtin_ia32_vpshrdw256:
3981   case X86::BI__builtin_ia32_vpshrdw512:
3982     i = 2; l = 0; u = 255;
3983     break;
3984   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3985   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3986   case X86::BI__builtin_ia32_fixupimmps512_mask:
3987   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3988   case X86::BI__builtin_ia32_fixupimmsd_mask:
3989   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3990   case X86::BI__builtin_ia32_fixupimmss_mask:
3991   case X86::BI__builtin_ia32_fixupimmss_maskz:
3992   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3993   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3994   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3995   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3996   case X86::BI__builtin_ia32_fixupimmps128_mask:
3997   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3998   case X86::BI__builtin_ia32_fixupimmps256_mask:
3999   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4000   case X86::BI__builtin_ia32_pternlogd512_mask:
4001   case X86::BI__builtin_ia32_pternlogd512_maskz:
4002   case X86::BI__builtin_ia32_pternlogq512_mask:
4003   case X86::BI__builtin_ia32_pternlogq512_maskz:
4004   case X86::BI__builtin_ia32_pternlogd128_mask:
4005   case X86::BI__builtin_ia32_pternlogd128_maskz:
4006   case X86::BI__builtin_ia32_pternlogd256_mask:
4007   case X86::BI__builtin_ia32_pternlogd256_maskz:
4008   case X86::BI__builtin_ia32_pternlogq128_mask:
4009   case X86::BI__builtin_ia32_pternlogq128_maskz:
4010   case X86::BI__builtin_ia32_pternlogq256_mask:
4011   case X86::BI__builtin_ia32_pternlogq256_maskz:
4012     i = 3; l = 0; u = 255;
4013     break;
4014   case X86::BI__builtin_ia32_gatherpfdpd:
4015   case X86::BI__builtin_ia32_gatherpfdps:
4016   case X86::BI__builtin_ia32_gatherpfqpd:
4017   case X86::BI__builtin_ia32_gatherpfqps:
4018   case X86::BI__builtin_ia32_scatterpfdpd:
4019   case X86::BI__builtin_ia32_scatterpfdps:
4020   case X86::BI__builtin_ia32_scatterpfqpd:
4021   case X86::BI__builtin_ia32_scatterpfqps:
4022     i = 4; l = 2; u = 3;
4023     break;
4024   case X86::BI__builtin_ia32_reducesd_mask:
4025   case X86::BI__builtin_ia32_reducess_mask:
4026   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4027   case X86::BI__builtin_ia32_rndscaless_round_mask:
4028     i = 4; l = 0; u = 255;
4029     break;
4030   }
4031 
4032   // Note that we don't force a hard error on the range check here, allowing
4033   // template-generated or macro-generated dead code to potentially have out-of-
4034   // range values. These need to code generate, but don't need to necessarily
4035   // make any sense. We use a warning that defaults to an error.
4036   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4037 }
4038 
4039 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4040 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4041 /// Returns true when the format fits the function and the FormatStringInfo has
4042 /// been populated.
4043 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4044                                FormatStringInfo *FSI) {
4045   FSI->HasVAListArg = Format->getFirstArg() == 0;
4046   FSI->FormatIdx = Format->getFormatIdx() - 1;
4047   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4048 
4049   // The way the format attribute works in GCC, the implicit this argument
4050   // of member functions is counted. However, it doesn't appear in our own
4051   // lists, so decrement format_idx in that case.
4052   if (IsCXXMember) {
4053     if(FSI->FormatIdx == 0)
4054       return false;
4055     --FSI->FormatIdx;
4056     if (FSI->FirstDataArg != 0)
4057       --FSI->FirstDataArg;
4058   }
4059   return true;
4060 }
4061 
4062 /// Checks if a the given expression evaluates to null.
4063 ///
4064 /// Returns true if the value evaluates to null.
4065 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4066   // If the expression has non-null type, it doesn't evaluate to null.
4067   if (auto nullability
4068         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4069     if (*nullability == NullabilityKind::NonNull)
4070       return false;
4071   }
4072 
4073   // As a special case, transparent unions initialized with zero are
4074   // considered null for the purposes of the nonnull attribute.
4075   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4076     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4077       if (const CompoundLiteralExpr *CLE =
4078           dyn_cast<CompoundLiteralExpr>(Expr))
4079         if (const InitListExpr *ILE =
4080             dyn_cast<InitListExpr>(CLE->getInitializer()))
4081           Expr = ILE->getInit(0);
4082   }
4083 
4084   bool Result;
4085   return (!Expr->isValueDependent() &&
4086           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4087           !Result);
4088 }
4089 
4090 static void CheckNonNullArgument(Sema &S,
4091                                  const Expr *ArgExpr,
4092                                  SourceLocation CallSiteLoc) {
4093   if (CheckNonNullExpr(S, ArgExpr))
4094     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4095                           S.PDiag(diag::warn_null_arg)
4096                               << ArgExpr->getSourceRange());
4097 }
4098 
4099 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4100   FormatStringInfo FSI;
4101   if ((GetFormatStringType(Format) == FST_NSString) &&
4102       getFormatStringInfo(Format, false, &FSI)) {
4103     Idx = FSI.FormatIdx;
4104     return true;
4105   }
4106   return false;
4107 }
4108 
4109 /// Diagnose use of %s directive in an NSString which is being passed
4110 /// as formatting string to formatting method.
4111 static void
4112 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4113                                         const NamedDecl *FDecl,
4114                                         Expr **Args,
4115                                         unsigned NumArgs) {
4116   unsigned Idx = 0;
4117   bool Format = false;
4118   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4119   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4120     Idx = 2;
4121     Format = true;
4122   }
4123   else
4124     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4125       if (S.GetFormatNSStringIdx(I, Idx)) {
4126         Format = true;
4127         break;
4128       }
4129     }
4130   if (!Format || NumArgs <= Idx)
4131     return;
4132   const Expr *FormatExpr = Args[Idx];
4133   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4134     FormatExpr = CSCE->getSubExpr();
4135   const StringLiteral *FormatString;
4136   if (const ObjCStringLiteral *OSL =
4137       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4138     FormatString = OSL->getString();
4139   else
4140     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4141   if (!FormatString)
4142     return;
4143   if (S.FormatStringHasSArg(FormatString)) {
4144     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4145       << "%s" << 1 << 1;
4146     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4147       << FDecl->getDeclName();
4148   }
4149 }
4150 
4151 /// Determine whether the given type has a non-null nullability annotation.
4152 static bool isNonNullType(ASTContext &ctx, QualType type) {
4153   if (auto nullability = type->getNullability(ctx))
4154     return *nullability == NullabilityKind::NonNull;
4155 
4156   return false;
4157 }
4158 
4159 static void CheckNonNullArguments(Sema &S,
4160                                   const NamedDecl *FDecl,
4161                                   const FunctionProtoType *Proto,
4162                                   ArrayRef<const Expr *> Args,
4163                                   SourceLocation CallSiteLoc) {
4164   assert((FDecl || Proto) && "Need a function declaration or prototype");
4165 
4166   // Already checked by by constant evaluator.
4167   if (S.isConstantEvaluated())
4168     return;
4169   // Check the attributes attached to the method/function itself.
4170   llvm::SmallBitVector NonNullArgs;
4171   if (FDecl) {
4172     // Handle the nonnull attribute on the function/method declaration itself.
4173     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4174       if (!NonNull->args_size()) {
4175         // Easy case: all pointer arguments are nonnull.
4176         for (const auto *Arg : Args)
4177           if (S.isValidPointerAttrType(Arg->getType()))
4178             CheckNonNullArgument(S, Arg, CallSiteLoc);
4179         return;
4180       }
4181 
4182       for (const ParamIdx &Idx : NonNull->args()) {
4183         unsigned IdxAST = Idx.getASTIndex();
4184         if (IdxAST >= Args.size())
4185           continue;
4186         if (NonNullArgs.empty())
4187           NonNullArgs.resize(Args.size());
4188         NonNullArgs.set(IdxAST);
4189       }
4190     }
4191   }
4192 
4193   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4194     // Handle the nonnull attribute on the parameters of the
4195     // function/method.
4196     ArrayRef<ParmVarDecl*> parms;
4197     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4198       parms = FD->parameters();
4199     else
4200       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4201 
4202     unsigned ParamIndex = 0;
4203     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4204          I != E; ++I, ++ParamIndex) {
4205       const ParmVarDecl *PVD = *I;
4206       if (PVD->hasAttr<NonNullAttr>() ||
4207           isNonNullType(S.Context, PVD->getType())) {
4208         if (NonNullArgs.empty())
4209           NonNullArgs.resize(Args.size());
4210 
4211         NonNullArgs.set(ParamIndex);
4212       }
4213     }
4214   } else {
4215     // If we have a non-function, non-method declaration but no
4216     // function prototype, try to dig out the function prototype.
4217     if (!Proto) {
4218       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4219         QualType type = VD->getType().getNonReferenceType();
4220         if (auto pointerType = type->getAs<PointerType>())
4221           type = pointerType->getPointeeType();
4222         else if (auto blockType = type->getAs<BlockPointerType>())
4223           type = blockType->getPointeeType();
4224         // FIXME: data member pointers?
4225 
4226         // Dig out the function prototype, if there is one.
4227         Proto = type->getAs<FunctionProtoType>();
4228       }
4229     }
4230 
4231     // Fill in non-null argument information from the nullability
4232     // information on the parameter types (if we have them).
4233     if (Proto) {
4234       unsigned Index = 0;
4235       for (auto paramType : Proto->getParamTypes()) {
4236         if (isNonNullType(S.Context, paramType)) {
4237           if (NonNullArgs.empty())
4238             NonNullArgs.resize(Args.size());
4239 
4240           NonNullArgs.set(Index);
4241         }
4242 
4243         ++Index;
4244       }
4245     }
4246   }
4247 
4248   // Check for non-null arguments.
4249   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4250        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4251     if (NonNullArgs[ArgIndex])
4252       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4253   }
4254 }
4255 
4256 /// Handles the checks for format strings, non-POD arguments to vararg
4257 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4258 /// attributes.
4259 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4260                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4261                      bool IsMemberFunction, SourceLocation Loc,
4262                      SourceRange Range, VariadicCallType CallType) {
4263   // FIXME: We should check as much as we can in the template definition.
4264   if (CurContext->isDependentContext())
4265     return;
4266 
4267   // Printf and scanf checking.
4268   llvm::SmallBitVector CheckedVarArgs;
4269   if (FDecl) {
4270     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4271       // Only create vector if there are format attributes.
4272       CheckedVarArgs.resize(Args.size());
4273 
4274       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4275                            CheckedVarArgs);
4276     }
4277   }
4278 
4279   // Refuse POD arguments that weren't caught by the format string
4280   // checks above.
4281   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4282   if (CallType != VariadicDoesNotApply &&
4283       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4284     unsigned NumParams = Proto ? Proto->getNumParams()
4285                        : FDecl && isa<FunctionDecl>(FDecl)
4286                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4287                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4288                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4289                        : 0;
4290 
4291     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4292       // Args[ArgIdx] can be null in malformed code.
4293       if (const Expr *Arg = Args[ArgIdx]) {
4294         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4295           checkVariadicArgument(Arg, CallType);
4296       }
4297     }
4298   }
4299 
4300   if (FDecl || Proto) {
4301     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4302 
4303     // Type safety checking.
4304     if (FDecl) {
4305       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4306         CheckArgumentWithTypeTag(I, Args, Loc);
4307     }
4308   }
4309 
4310   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4311     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4312     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4313     if (!Arg->isValueDependent()) {
4314       Expr::EvalResult Align;
4315       if (Arg->EvaluateAsInt(Align, Context)) {
4316         const llvm::APSInt &I = Align.Val.getInt();
4317         if (!I.isPowerOf2())
4318           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4319               << Arg->getSourceRange();
4320 
4321         if (I > Sema::MaximumAlignment)
4322           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4323               << Arg->getSourceRange() << Sema::MaximumAlignment;
4324       }
4325     }
4326   }
4327 
4328   if (FD)
4329     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4330 }
4331 
4332 /// CheckConstructorCall - Check a constructor call for correctness and safety
4333 /// properties not enforced by the C type system.
4334 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4335                                 ArrayRef<const Expr *> Args,
4336                                 const FunctionProtoType *Proto,
4337                                 SourceLocation Loc) {
4338   VariadicCallType CallType =
4339     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4340   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4341             Loc, SourceRange(), CallType);
4342 }
4343 
4344 /// CheckFunctionCall - Check a direct function call for various correctness
4345 /// and safety properties not strictly enforced by the C type system.
4346 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4347                              const FunctionProtoType *Proto) {
4348   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4349                               isa<CXXMethodDecl>(FDecl);
4350   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4351                           IsMemberOperatorCall;
4352   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4353                                                   TheCall->getCallee());
4354   Expr** Args = TheCall->getArgs();
4355   unsigned NumArgs = TheCall->getNumArgs();
4356 
4357   Expr *ImplicitThis = nullptr;
4358   if (IsMemberOperatorCall) {
4359     // If this is a call to a member operator, hide the first argument
4360     // from checkCall.
4361     // FIXME: Our choice of AST representation here is less than ideal.
4362     ImplicitThis = Args[0];
4363     ++Args;
4364     --NumArgs;
4365   } else if (IsMemberFunction)
4366     ImplicitThis =
4367         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4368 
4369   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4370             IsMemberFunction, TheCall->getRParenLoc(),
4371             TheCall->getCallee()->getSourceRange(), CallType);
4372 
4373   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4374   // None of the checks below are needed for functions that don't have
4375   // simple names (e.g., C++ conversion functions).
4376   if (!FnInfo)
4377     return false;
4378 
4379   CheckAbsoluteValueFunction(TheCall, FDecl);
4380   CheckMaxUnsignedZero(TheCall, FDecl);
4381 
4382   if (getLangOpts().ObjC)
4383     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4384 
4385   unsigned CMId = FDecl->getMemoryFunctionKind();
4386   if (CMId == 0)
4387     return false;
4388 
4389   // Handle memory setting and copying functions.
4390   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4391     CheckStrlcpycatArguments(TheCall, FnInfo);
4392   else if (CMId == Builtin::BIstrncat)
4393     CheckStrncatArguments(TheCall, FnInfo);
4394   else
4395     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4396 
4397   return false;
4398 }
4399 
4400 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4401                                ArrayRef<const Expr *> Args) {
4402   VariadicCallType CallType =
4403       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4404 
4405   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4406             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4407             CallType);
4408 
4409   return false;
4410 }
4411 
4412 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4413                             const FunctionProtoType *Proto) {
4414   QualType Ty;
4415   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4416     Ty = V->getType().getNonReferenceType();
4417   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4418     Ty = F->getType().getNonReferenceType();
4419   else
4420     return false;
4421 
4422   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4423       !Ty->isFunctionProtoType())
4424     return false;
4425 
4426   VariadicCallType CallType;
4427   if (!Proto || !Proto->isVariadic()) {
4428     CallType = VariadicDoesNotApply;
4429   } else if (Ty->isBlockPointerType()) {
4430     CallType = VariadicBlock;
4431   } else { // Ty->isFunctionPointerType()
4432     CallType = VariadicFunction;
4433   }
4434 
4435   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4436             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4437             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4438             TheCall->getCallee()->getSourceRange(), CallType);
4439 
4440   return false;
4441 }
4442 
4443 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4444 /// such as function pointers returned from functions.
4445 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4446   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4447                                                   TheCall->getCallee());
4448   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4449             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4450             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4451             TheCall->getCallee()->getSourceRange(), CallType);
4452 
4453   return false;
4454 }
4455 
4456 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4457   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4458     return false;
4459 
4460   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4461   switch (Op) {
4462   case AtomicExpr::AO__c11_atomic_init:
4463   case AtomicExpr::AO__opencl_atomic_init:
4464     llvm_unreachable("There is no ordering argument for an init");
4465 
4466   case AtomicExpr::AO__c11_atomic_load:
4467   case AtomicExpr::AO__opencl_atomic_load:
4468   case AtomicExpr::AO__atomic_load_n:
4469   case AtomicExpr::AO__atomic_load:
4470     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4471            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4472 
4473   case AtomicExpr::AO__c11_atomic_store:
4474   case AtomicExpr::AO__opencl_atomic_store:
4475   case AtomicExpr::AO__atomic_store:
4476   case AtomicExpr::AO__atomic_store_n:
4477     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4478            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4479            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4480 
4481   default:
4482     return true;
4483   }
4484 }
4485 
4486 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4487                                          AtomicExpr::AtomicOp Op) {
4488   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4489   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4490   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4491   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4492                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4493                          Op);
4494 }
4495 
4496 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4497                                  SourceLocation RParenLoc, MultiExprArg Args,
4498                                  AtomicExpr::AtomicOp Op,
4499                                  AtomicArgumentOrder ArgOrder) {
4500   // All the non-OpenCL operations take one of the following forms.
4501   // The OpenCL operations take the __c11 forms with one extra argument for
4502   // synchronization scope.
4503   enum {
4504     // C    __c11_atomic_init(A *, C)
4505     Init,
4506 
4507     // C    __c11_atomic_load(A *, int)
4508     Load,
4509 
4510     // void __atomic_load(A *, CP, int)
4511     LoadCopy,
4512 
4513     // void __atomic_store(A *, CP, int)
4514     Copy,
4515 
4516     // C    __c11_atomic_add(A *, M, int)
4517     Arithmetic,
4518 
4519     // C    __atomic_exchange_n(A *, CP, int)
4520     Xchg,
4521 
4522     // void __atomic_exchange(A *, C *, CP, int)
4523     GNUXchg,
4524 
4525     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4526     C11CmpXchg,
4527 
4528     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4529     GNUCmpXchg
4530   } Form = Init;
4531 
4532   const unsigned NumForm = GNUCmpXchg + 1;
4533   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4534   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4535   // where:
4536   //   C is an appropriate type,
4537   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4538   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4539   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4540   //   the int parameters are for orderings.
4541 
4542   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4543       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4544       "need to update code for modified forms");
4545   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4546                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4547                         AtomicExpr::AO__atomic_load,
4548                 "need to update code for modified C11 atomics");
4549   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4550                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4551   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4552                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4553                IsOpenCL;
4554   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4555              Op == AtomicExpr::AO__atomic_store_n ||
4556              Op == AtomicExpr::AO__atomic_exchange_n ||
4557              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4558   bool IsAddSub = false;
4559 
4560   switch (Op) {
4561   case AtomicExpr::AO__c11_atomic_init:
4562   case AtomicExpr::AO__opencl_atomic_init:
4563     Form = Init;
4564     break;
4565 
4566   case AtomicExpr::AO__c11_atomic_load:
4567   case AtomicExpr::AO__opencl_atomic_load:
4568   case AtomicExpr::AO__atomic_load_n:
4569     Form = Load;
4570     break;
4571 
4572   case AtomicExpr::AO__atomic_load:
4573     Form = LoadCopy;
4574     break;
4575 
4576   case AtomicExpr::AO__c11_atomic_store:
4577   case AtomicExpr::AO__opencl_atomic_store:
4578   case AtomicExpr::AO__atomic_store:
4579   case AtomicExpr::AO__atomic_store_n:
4580     Form = Copy;
4581     break;
4582 
4583   case AtomicExpr::AO__c11_atomic_fetch_add:
4584   case AtomicExpr::AO__c11_atomic_fetch_sub:
4585   case AtomicExpr::AO__opencl_atomic_fetch_add:
4586   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4587   case AtomicExpr::AO__atomic_fetch_add:
4588   case AtomicExpr::AO__atomic_fetch_sub:
4589   case AtomicExpr::AO__atomic_add_fetch:
4590   case AtomicExpr::AO__atomic_sub_fetch:
4591     IsAddSub = true;
4592     LLVM_FALLTHROUGH;
4593   case AtomicExpr::AO__c11_atomic_fetch_and:
4594   case AtomicExpr::AO__c11_atomic_fetch_or:
4595   case AtomicExpr::AO__c11_atomic_fetch_xor:
4596   case AtomicExpr::AO__opencl_atomic_fetch_and:
4597   case AtomicExpr::AO__opencl_atomic_fetch_or:
4598   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4599   case AtomicExpr::AO__atomic_fetch_and:
4600   case AtomicExpr::AO__atomic_fetch_or:
4601   case AtomicExpr::AO__atomic_fetch_xor:
4602   case AtomicExpr::AO__atomic_fetch_nand:
4603   case AtomicExpr::AO__atomic_and_fetch:
4604   case AtomicExpr::AO__atomic_or_fetch:
4605   case AtomicExpr::AO__atomic_xor_fetch:
4606   case AtomicExpr::AO__atomic_nand_fetch:
4607   case AtomicExpr::AO__c11_atomic_fetch_min:
4608   case AtomicExpr::AO__c11_atomic_fetch_max:
4609   case AtomicExpr::AO__opencl_atomic_fetch_min:
4610   case AtomicExpr::AO__opencl_atomic_fetch_max:
4611   case AtomicExpr::AO__atomic_min_fetch:
4612   case AtomicExpr::AO__atomic_max_fetch:
4613   case AtomicExpr::AO__atomic_fetch_min:
4614   case AtomicExpr::AO__atomic_fetch_max:
4615     Form = Arithmetic;
4616     break;
4617 
4618   case AtomicExpr::AO__c11_atomic_exchange:
4619   case AtomicExpr::AO__opencl_atomic_exchange:
4620   case AtomicExpr::AO__atomic_exchange_n:
4621     Form = Xchg;
4622     break;
4623 
4624   case AtomicExpr::AO__atomic_exchange:
4625     Form = GNUXchg;
4626     break;
4627 
4628   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4629   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4630   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4631   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4632     Form = C11CmpXchg;
4633     break;
4634 
4635   case AtomicExpr::AO__atomic_compare_exchange:
4636   case AtomicExpr::AO__atomic_compare_exchange_n:
4637     Form = GNUCmpXchg;
4638     break;
4639   }
4640 
4641   unsigned AdjustedNumArgs = NumArgs[Form];
4642   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4643     ++AdjustedNumArgs;
4644   // Check we have the right number of arguments.
4645   if (Args.size() < AdjustedNumArgs) {
4646     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4647         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4648         << ExprRange;
4649     return ExprError();
4650   } else if (Args.size() > AdjustedNumArgs) {
4651     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4652          diag::err_typecheck_call_too_many_args)
4653         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4654         << ExprRange;
4655     return ExprError();
4656   }
4657 
4658   // Inspect the first argument of the atomic operation.
4659   Expr *Ptr = Args[0];
4660   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4661   if (ConvertedPtr.isInvalid())
4662     return ExprError();
4663 
4664   Ptr = ConvertedPtr.get();
4665   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4666   if (!pointerType) {
4667     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4668         << Ptr->getType() << Ptr->getSourceRange();
4669     return ExprError();
4670   }
4671 
4672   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4673   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4674   QualType ValType = AtomTy; // 'C'
4675   if (IsC11) {
4676     if (!AtomTy->isAtomicType()) {
4677       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4678           << Ptr->getType() << Ptr->getSourceRange();
4679       return ExprError();
4680     }
4681     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4682         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4683       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4684           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4685           << Ptr->getSourceRange();
4686       return ExprError();
4687     }
4688     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4689   } else if (Form != Load && Form != LoadCopy) {
4690     if (ValType.isConstQualified()) {
4691       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4692           << Ptr->getType() << Ptr->getSourceRange();
4693       return ExprError();
4694     }
4695   }
4696 
4697   // For an arithmetic operation, the implied arithmetic must be well-formed.
4698   if (Form == Arithmetic) {
4699     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4700     if (IsAddSub && !ValType->isIntegerType()
4701         && !ValType->isPointerType()) {
4702       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4703           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4704       return ExprError();
4705     }
4706     if (!IsAddSub && !ValType->isIntegerType()) {
4707       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4708           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4709       return ExprError();
4710     }
4711     if (IsC11 && ValType->isPointerType() &&
4712         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4713                             diag::err_incomplete_type)) {
4714       return ExprError();
4715     }
4716   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4717     // For __atomic_*_n operations, the value type must be a scalar integral or
4718     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4719     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4720         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4721     return ExprError();
4722   }
4723 
4724   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4725       !AtomTy->isScalarType()) {
4726     // For GNU atomics, require a trivially-copyable type. This is not part of
4727     // the GNU atomics specification, but we enforce it for sanity.
4728     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4729         << Ptr->getType() << Ptr->getSourceRange();
4730     return ExprError();
4731   }
4732 
4733   switch (ValType.getObjCLifetime()) {
4734   case Qualifiers::OCL_None:
4735   case Qualifiers::OCL_ExplicitNone:
4736     // okay
4737     break;
4738 
4739   case Qualifiers::OCL_Weak:
4740   case Qualifiers::OCL_Strong:
4741   case Qualifiers::OCL_Autoreleasing:
4742     // FIXME: Can this happen? By this point, ValType should be known
4743     // to be trivially copyable.
4744     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4745         << ValType << Ptr->getSourceRange();
4746     return ExprError();
4747   }
4748 
4749   // All atomic operations have an overload which takes a pointer to a volatile
4750   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4751   // into the result or the other operands. Similarly atomic_load takes a
4752   // pointer to a const 'A'.
4753   ValType.removeLocalVolatile();
4754   ValType.removeLocalConst();
4755   QualType ResultType = ValType;
4756   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4757       Form == Init)
4758     ResultType = Context.VoidTy;
4759   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4760     ResultType = Context.BoolTy;
4761 
4762   // The type of a parameter passed 'by value'. In the GNU atomics, such
4763   // arguments are actually passed as pointers.
4764   QualType ByValType = ValType; // 'CP'
4765   bool IsPassedByAddress = false;
4766   if (!IsC11 && !IsN) {
4767     ByValType = Ptr->getType();
4768     IsPassedByAddress = true;
4769   }
4770 
4771   SmallVector<Expr *, 5> APIOrderedArgs;
4772   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4773     APIOrderedArgs.push_back(Args[0]);
4774     switch (Form) {
4775     case Init:
4776     case Load:
4777       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4778       break;
4779     case LoadCopy:
4780     case Copy:
4781     case Arithmetic:
4782     case Xchg:
4783       APIOrderedArgs.push_back(Args[2]); // Val1
4784       APIOrderedArgs.push_back(Args[1]); // Order
4785       break;
4786     case GNUXchg:
4787       APIOrderedArgs.push_back(Args[2]); // Val1
4788       APIOrderedArgs.push_back(Args[3]); // Val2
4789       APIOrderedArgs.push_back(Args[1]); // Order
4790       break;
4791     case C11CmpXchg:
4792       APIOrderedArgs.push_back(Args[2]); // Val1
4793       APIOrderedArgs.push_back(Args[4]); // Val2
4794       APIOrderedArgs.push_back(Args[1]); // Order
4795       APIOrderedArgs.push_back(Args[3]); // OrderFail
4796       break;
4797     case GNUCmpXchg:
4798       APIOrderedArgs.push_back(Args[2]); // Val1
4799       APIOrderedArgs.push_back(Args[4]); // Val2
4800       APIOrderedArgs.push_back(Args[5]); // Weak
4801       APIOrderedArgs.push_back(Args[1]); // Order
4802       APIOrderedArgs.push_back(Args[3]); // OrderFail
4803       break;
4804     }
4805   } else
4806     APIOrderedArgs.append(Args.begin(), Args.end());
4807 
4808   // The first argument's non-CV pointer type is used to deduce the type of
4809   // subsequent arguments, except for:
4810   //  - weak flag (always converted to bool)
4811   //  - memory order (always converted to int)
4812   //  - scope  (always converted to int)
4813   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4814     QualType Ty;
4815     if (i < NumVals[Form] + 1) {
4816       switch (i) {
4817       case 0:
4818         // The first argument is always a pointer. It has a fixed type.
4819         // It is always dereferenced, a nullptr is undefined.
4820         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4821         // Nothing else to do: we already know all we want about this pointer.
4822         continue;
4823       case 1:
4824         // The second argument is the non-atomic operand. For arithmetic, this
4825         // is always passed by value, and for a compare_exchange it is always
4826         // passed by address. For the rest, GNU uses by-address and C11 uses
4827         // by-value.
4828         assert(Form != Load);
4829         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4830           Ty = ValType;
4831         else if (Form == Copy || Form == Xchg) {
4832           if (IsPassedByAddress) {
4833             // The value pointer is always dereferenced, a nullptr is undefined.
4834             CheckNonNullArgument(*this, APIOrderedArgs[i],
4835                                  ExprRange.getBegin());
4836           }
4837           Ty = ByValType;
4838         } else if (Form == Arithmetic)
4839           Ty = Context.getPointerDiffType();
4840         else {
4841           Expr *ValArg = APIOrderedArgs[i];
4842           // The value pointer is always dereferenced, a nullptr is undefined.
4843           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4844           LangAS AS = LangAS::Default;
4845           // Keep address space of non-atomic pointer type.
4846           if (const PointerType *PtrTy =
4847                   ValArg->getType()->getAs<PointerType>()) {
4848             AS = PtrTy->getPointeeType().getAddressSpace();
4849           }
4850           Ty = Context.getPointerType(
4851               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4852         }
4853         break;
4854       case 2:
4855         // The third argument to compare_exchange / GNU exchange is the desired
4856         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4857         if (IsPassedByAddress)
4858           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4859         Ty = ByValType;
4860         break;
4861       case 3:
4862         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4863         Ty = Context.BoolTy;
4864         break;
4865       }
4866     } else {
4867       // The order(s) and scope are always converted to int.
4868       Ty = Context.IntTy;
4869     }
4870 
4871     InitializedEntity Entity =
4872         InitializedEntity::InitializeParameter(Context, Ty, false);
4873     ExprResult Arg = APIOrderedArgs[i];
4874     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4875     if (Arg.isInvalid())
4876       return true;
4877     APIOrderedArgs[i] = Arg.get();
4878   }
4879 
4880   // Permute the arguments into a 'consistent' order.
4881   SmallVector<Expr*, 5> SubExprs;
4882   SubExprs.push_back(Ptr);
4883   switch (Form) {
4884   case Init:
4885     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4886     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4887     break;
4888   case Load:
4889     SubExprs.push_back(APIOrderedArgs[1]); // Order
4890     break;
4891   case LoadCopy:
4892   case Copy:
4893   case Arithmetic:
4894   case Xchg:
4895     SubExprs.push_back(APIOrderedArgs[2]); // Order
4896     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4897     break;
4898   case GNUXchg:
4899     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4900     SubExprs.push_back(APIOrderedArgs[3]); // Order
4901     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4902     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4903     break;
4904   case C11CmpXchg:
4905     SubExprs.push_back(APIOrderedArgs[3]); // Order
4906     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4907     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4908     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4909     break;
4910   case GNUCmpXchg:
4911     SubExprs.push_back(APIOrderedArgs[4]); // Order
4912     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4913     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4914     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4915     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4916     break;
4917   }
4918 
4919   if (SubExprs.size() >= 2 && Form != Init) {
4920     if (Optional<llvm::APSInt> Result =
4921             SubExprs[1]->getIntegerConstantExpr(Context))
4922       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
4923         Diag(SubExprs[1]->getBeginLoc(),
4924              diag::warn_atomic_op_has_invalid_memory_order)
4925             << SubExprs[1]->getSourceRange();
4926   }
4927 
4928   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4929     auto *Scope = Args[Args.size() - 1];
4930     if (Optional<llvm::APSInt> Result =
4931             Scope->getIntegerConstantExpr(Context)) {
4932       if (!ScopeModel->isValid(Result->getZExtValue()))
4933         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4934             << Scope->getSourceRange();
4935     }
4936     SubExprs.push_back(Scope);
4937   }
4938 
4939   AtomicExpr *AE = new (Context)
4940       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4941 
4942   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4943        Op == AtomicExpr::AO__c11_atomic_store ||
4944        Op == AtomicExpr::AO__opencl_atomic_load ||
4945        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4946       Context.AtomicUsesUnsupportedLibcall(AE))
4947     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4948         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4949              Op == AtomicExpr::AO__opencl_atomic_load)
4950                 ? 0
4951                 : 1);
4952 
4953   return AE;
4954 }
4955 
4956 /// checkBuiltinArgument - Given a call to a builtin function, perform
4957 /// normal type-checking on the given argument, updating the call in
4958 /// place.  This is useful when a builtin function requires custom
4959 /// type-checking for some of its arguments but not necessarily all of
4960 /// them.
4961 ///
4962 /// Returns true on error.
4963 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4964   FunctionDecl *Fn = E->getDirectCallee();
4965   assert(Fn && "builtin call without direct callee!");
4966 
4967   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4968   InitializedEntity Entity =
4969     InitializedEntity::InitializeParameter(S.Context, Param);
4970 
4971   ExprResult Arg = E->getArg(0);
4972   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4973   if (Arg.isInvalid())
4974     return true;
4975 
4976   E->setArg(ArgIndex, Arg.get());
4977   return false;
4978 }
4979 
4980 /// We have a call to a function like __sync_fetch_and_add, which is an
4981 /// overloaded function based on the pointer type of its first argument.
4982 /// The main BuildCallExpr routines have already promoted the types of
4983 /// arguments because all of these calls are prototyped as void(...).
4984 ///
4985 /// This function goes through and does final semantic checking for these
4986 /// builtins, as well as generating any warnings.
4987 ExprResult
4988 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4989   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4990   Expr *Callee = TheCall->getCallee();
4991   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4992   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4993 
4994   // Ensure that we have at least one argument to do type inference from.
4995   if (TheCall->getNumArgs() < 1) {
4996     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4997         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4998     return ExprError();
4999   }
5000 
5001   // Inspect the first argument of the atomic builtin.  This should always be
5002   // a pointer type, whose element is an integral scalar or pointer type.
5003   // Because it is a pointer type, we don't have to worry about any implicit
5004   // casts here.
5005   // FIXME: We don't allow floating point scalars as input.
5006   Expr *FirstArg = TheCall->getArg(0);
5007   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5008   if (FirstArgResult.isInvalid())
5009     return ExprError();
5010   FirstArg = FirstArgResult.get();
5011   TheCall->setArg(0, FirstArg);
5012 
5013   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5014   if (!pointerType) {
5015     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5016         << FirstArg->getType() << FirstArg->getSourceRange();
5017     return ExprError();
5018   }
5019 
5020   QualType ValType = pointerType->getPointeeType();
5021   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5022       !ValType->isBlockPointerType()) {
5023     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5024         << FirstArg->getType() << FirstArg->getSourceRange();
5025     return ExprError();
5026   }
5027 
5028   if (ValType.isConstQualified()) {
5029     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5030         << FirstArg->getType() << FirstArg->getSourceRange();
5031     return ExprError();
5032   }
5033 
5034   switch (ValType.getObjCLifetime()) {
5035   case Qualifiers::OCL_None:
5036   case Qualifiers::OCL_ExplicitNone:
5037     // okay
5038     break;
5039 
5040   case Qualifiers::OCL_Weak:
5041   case Qualifiers::OCL_Strong:
5042   case Qualifiers::OCL_Autoreleasing:
5043     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5044         << ValType << FirstArg->getSourceRange();
5045     return ExprError();
5046   }
5047 
5048   // Strip any qualifiers off ValType.
5049   ValType = ValType.getUnqualifiedType();
5050 
5051   // The majority of builtins return a value, but a few have special return
5052   // types, so allow them to override appropriately below.
5053   QualType ResultType = ValType;
5054 
5055   // We need to figure out which concrete builtin this maps onto.  For example,
5056   // __sync_fetch_and_add with a 2 byte object turns into
5057   // __sync_fetch_and_add_2.
5058 #define BUILTIN_ROW(x) \
5059   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5060     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5061 
5062   static const unsigned BuiltinIndices[][5] = {
5063     BUILTIN_ROW(__sync_fetch_and_add),
5064     BUILTIN_ROW(__sync_fetch_and_sub),
5065     BUILTIN_ROW(__sync_fetch_and_or),
5066     BUILTIN_ROW(__sync_fetch_and_and),
5067     BUILTIN_ROW(__sync_fetch_and_xor),
5068     BUILTIN_ROW(__sync_fetch_and_nand),
5069 
5070     BUILTIN_ROW(__sync_add_and_fetch),
5071     BUILTIN_ROW(__sync_sub_and_fetch),
5072     BUILTIN_ROW(__sync_and_and_fetch),
5073     BUILTIN_ROW(__sync_or_and_fetch),
5074     BUILTIN_ROW(__sync_xor_and_fetch),
5075     BUILTIN_ROW(__sync_nand_and_fetch),
5076 
5077     BUILTIN_ROW(__sync_val_compare_and_swap),
5078     BUILTIN_ROW(__sync_bool_compare_and_swap),
5079     BUILTIN_ROW(__sync_lock_test_and_set),
5080     BUILTIN_ROW(__sync_lock_release),
5081     BUILTIN_ROW(__sync_swap)
5082   };
5083 #undef BUILTIN_ROW
5084 
5085   // Determine the index of the size.
5086   unsigned SizeIndex;
5087   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5088   case 1: SizeIndex = 0; break;
5089   case 2: SizeIndex = 1; break;
5090   case 4: SizeIndex = 2; break;
5091   case 8: SizeIndex = 3; break;
5092   case 16: SizeIndex = 4; break;
5093   default:
5094     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5095         << FirstArg->getType() << FirstArg->getSourceRange();
5096     return ExprError();
5097   }
5098 
5099   // Each of these builtins has one pointer argument, followed by some number of
5100   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5101   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5102   // as the number of fixed args.
5103   unsigned BuiltinID = FDecl->getBuiltinID();
5104   unsigned BuiltinIndex, NumFixed = 1;
5105   bool WarnAboutSemanticsChange = false;
5106   switch (BuiltinID) {
5107   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5108   case Builtin::BI__sync_fetch_and_add:
5109   case Builtin::BI__sync_fetch_and_add_1:
5110   case Builtin::BI__sync_fetch_and_add_2:
5111   case Builtin::BI__sync_fetch_and_add_4:
5112   case Builtin::BI__sync_fetch_and_add_8:
5113   case Builtin::BI__sync_fetch_and_add_16:
5114     BuiltinIndex = 0;
5115     break;
5116 
5117   case Builtin::BI__sync_fetch_and_sub:
5118   case Builtin::BI__sync_fetch_and_sub_1:
5119   case Builtin::BI__sync_fetch_and_sub_2:
5120   case Builtin::BI__sync_fetch_and_sub_4:
5121   case Builtin::BI__sync_fetch_and_sub_8:
5122   case Builtin::BI__sync_fetch_and_sub_16:
5123     BuiltinIndex = 1;
5124     break;
5125 
5126   case Builtin::BI__sync_fetch_and_or:
5127   case Builtin::BI__sync_fetch_and_or_1:
5128   case Builtin::BI__sync_fetch_and_or_2:
5129   case Builtin::BI__sync_fetch_and_or_4:
5130   case Builtin::BI__sync_fetch_and_or_8:
5131   case Builtin::BI__sync_fetch_and_or_16:
5132     BuiltinIndex = 2;
5133     break;
5134 
5135   case Builtin::BI__sync_fetch_and_and:
5136   case Builtin::BI__sync_fetch_and_and_1:
5137   case Builtin::BI__sync_fetch_and_and_2:
5138   case Builtin::BI__sync_fetch_and_and_4:
5139   case Builtin::BI__sync_fetch_and_and_8:
5140   case Builtin::BI__sync_fetch_and_and_16:
5141     BuiltinIndex = 3;
5142     break;
5143 
5144   case Builtin::BI__sync_fetch_and_xor:
5145   case Builtin::BI__sync_fetch_and_xor_1:
5146   case Builtin::BI__sync_fetch_and_xor_2:
5147   case Builtin::BI__sync_fetch_and_xor_4:
5148   case Builtin::BI__sync_fetch_and_xor_8:
5149   case Builtin::BI__sync_fetch_and_xor_16:
5150     BuiltinIndex = 4;
5151     break;
5152 
5153   case Builtin::BI__sync_fetch_and_nand:
5154   case Builtin::BI__sync_fetch_and_nand_1:
5155   case Builtin::BI__sync_fetch_and_nand_2:
5156   case Builtin::BI__sync_fetch_and_nand_4:
5157   case Builtin::BI__sync_fetch_and_nand_8:
5158   case Builtin::BI__sync_fetch_and_nand_16:
5159     BuiltinIndex = 5;
5160     WarnAboutSemanticsChange = true;
5161     break;
5162 
5163   case Builtin::BI__sync_add_and_fetch:
5164   case Builtin::BI__sync_add_and_fetch_1:
5165   case Builtin::BI__sync_add_and_fetch_2:
5166   case Builtin::BI__sync_add_and_fetch_4:
5167   case Builtin::BI__sync_add_and_fetch_8:
5168   case Builtin::BI__sync_add_and_fetch_16:
5169     BuiltinIndex = 6;
5170     break;
5171 
5172   case Builtin::BI__sync_sub_and_fetch:
5173   case Builtin::BI__sync_sub_and_fetch_1:
5174   case Builtin::BI__sync_sub_and_fetch_2:
5175   case Builtin::BI__sync_sub_and_fetch_4:
5176   case Builtin::BI__sync_sub_and_fetch_8:
5177   case Builtin::BI__sync_sub_and_fetch_16:
5178     BuiltinIndex = 7;
5179     break;
5180 
5181   case Builtin::BI__sync_and_and_fetch:
5182   case Builtin::BI__sync_and_and_fetch_1:
5183   case Builtin::BI__sync_and_and_fetch_2:
5184   case Builtin::BI__sync_and_and_fetch_4:
5185   case Builtin::BI__sync_and_and_fetch_8:
5186   case Builtin::BI__sync_and_and_fetch_16:
5187     BuiltinIndex = 8;
5188     break;
5189 
5190   case Builtin::BI__sync_or_and_fetch:
5191   case Builtin::BI__sync_or_and_fetch_1:
5192   case Builtin::BI__sync_or_and_fetch_2:
5193   case Builtin::BI__sync_or_and_fetch_4:
5194   case Builtin::BI__sync_or_and_fetch_8:
5195   case Builtin::BI__sync_or_and_fetch_16:
5196     BuiltinIndex = 9;
5197     break;
5198 
5199   case Builtin::BI__sync_xor_and_fetch:
5200   case Builtin::BI__sync_xor_and_fetch_1:
5201   case Builtin::BI__sync_xor_and_fetch_2:
5202   case Builtin::BI__sync_xor_and_fetch_4:
5203   case Builtin::BI__sync_xor_and_fetch_8:
5204   case Builtin::BI__sync_xor_and_fetch_16:
5205     BuiltinIndex = 10;
5206     break;
5207 
5208   case Builtin::BI__sync_nand_and_fetch:
5209   case Builtin::BI__sync_nand_and_fetch_1:
5210   case Builtin::BI__sync_nand_and_fetch_2:
5211   case Builtin::BI__sync_nand_and_fetch_4:
5212   case Builtin::BI__sync_nand_and_fetch_8:
5213   case Builtin::BI__sync_nand_and_fetch_16:
5214     BuiltinIndex = 11;
5215     WarnAboutSemanticsChange = true;
5216     break;
5217 
5218   case Builtin::BI__sync_val_compare_and_swap:
5219   case Builtin::BI__sync_val_compare_and_swap_1:
5220   case Builtin::BI__sync_val_compare_and_swap_2:
5221   case Builtin::BI__sync_val_compare_and_swap_4:
5222   case Builtin::BI__sync_val_compare_and_swap_8:
5223   case Builtin::BI__sync_val_compare_and_swap_16:
5224     BuiltinIndex = 12;
5225     NumFixed = 2;
5226     break;
5227 
5228   case Builtin::BI__sync_bool_compare_and_swap:
5229   case Builtin::BI__sync_bool_compare_and_swap_1:
5230   case Builtin::BI__sync_bool_compare_and_swap_2:
5231   case Builtin::BI__sync_bool_compare_and_swap_4:
5232   case Builtin::BI__sync_bool_compare_and_swap_8:
5233   case Builtin::BI__sync_bool_compare_and_swap_16:
5234     BuiltinIndex = 13;
5235     NumFixed = 2;
5236     ResultType = Context.BoolTy;
5237     break;
5238 
5239   case Builtin::BI__sync_lock_test_and_set:
5240   case Builtin::BI__sync_lock_test_and_set_1:
5241   case Builtin::BI__sync_lock_test_and_set_2:
5242   case Builtin::BI__sync_lock_test_and_set_4:
5243   case Builtin::BI__sync_lock_test_and_set_8:
5244   case Builtin::BI__sync_lock_test_and_set_16:
5245     BuiltinIndex = 14;
5246     break;
5247 
5248   case Builtin::BI__sync_lock_release:
5249   case Builtin::BI__sync_lock_release_1:
5250   case Builtin::BI__sync_lock_release_2:
5251   case Builtin::BI__sync_lock_release_4:
5252   case Builtin::BI__sync_lock_release_8:
5253   case Builtin::BI__sync_lock_release_16:
5254     BuiltinIndex = 15;
5255     NumFixed = 0;
5256     ResultType = Context.VoidTy;
5257     break;
5258 
5259   case Builtin::BI__sync_swap:
5260   case Builtin::BI__sync_swap_1:
5261   case Builtin::BI__sync_swap_2:
5262   case Builtin::BI__sync_swap_4:
5263   case Builtin::BI__sync_swap_8:
5264   case Builtin::BI__sync_swap_16:
5265     BuiltinIndex = 16;
5266     break;
5267   }
5268 
5269   // Now that we know how many fixed arguments we expect, first check that we
5270   // have at least that many.
5271   if (TheCall->getNumArgs() < 1+NumFixed) {
5272     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5273         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5274         << Callee->getSourceRange();
5275     return ExprError();
5276   }
5277 
5278   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5279       << Callee->getSourceRange();
5280 
5281   if (WarnAboutSemanticsChange) {
5282     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5283         << Callee->getSourceRange();
5284   }
5285 
5286   // Get the decl for the concrete builtin from this, we can tell what the
5287   // concrete integer type we should convert to is.
5288   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5289   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5290   FunctionDecl *NewBuiltinDecl;
5291   if (NewBuiltinID == BuiltinID)
5292     NewBuiltinDecl = FDecl;
5293   else {
5294     // Perform builtin lookup to avoid redeclaring it.
5295     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5296     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5297     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5298     assert(Res.getFoundDecl());
5299     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5300     if (!NewBuiltinDecl)
5301       return ExprError();
5302   }
5303 
5304   // The first argument --- the pointer --- has a fixed type; we
5305   // deduce the types of the rest of the arguments accordingly.  Walk
5306   // the remaining arguments, converting them to the deduced value type.
5307   for (unsigned i = 0; i != NumFixed; ++i) {
5308     ExprResult Arg = TheCall->getArg(i+1);
5309 
5310     // GCC does an implicit conversion to the pointer or integer ValType.  This
5311     // can fail in some cases (1i -> int**), check for this error case now.
5312     // Initialize the argument.
5313     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5314                                                    ValType, /*consume*/ false);
5315     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5316     if (Arg.isInvalid())
5317       return ExprError();
5318 
5319     // Okay, we have something that *can* be converted to the right type.  Check
5320     // to see if there is a potentially weird extension going on here.  This can
5321     // happen when you do an atomic operation on something like an char* and
5322     // pass in 42.  The 42 gets converted to char.  This is even more strange
5323     // for things like 45.123 -> char, etc.
5324     // FIXME: Do this check.
5325     TheCall->setArg(i+1, Arg.get());
5326   }
5327 
5328   // Create a new DeclRefExpr to refer to the new decl.
5329   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5330       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5331       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5332       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5333 
5334   // Set the callee in the CallExpr.
5335   // FIXME: This loses syntactic information.
5336   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5337   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5338                                               CK_BuiltinFnToFnPtr);
5339   TheCall->setCallee(PromotedCall.get());
5340 
5341   // Change the result type of the call to match the original value type. This
5342   // is arbitrary, but the codegen for these builtins ins design to handle it
5343   // gracefully.
5344   TheCall->setType(ResultType);
5345 
5346   // Prohibit use of _ExtInt with atomic builtins.
5347   // The arguments would have already been converted to the first argument's
5348   // type, so only need to check the first argument.
5349   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5350   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5351     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5352     return ExprError();
5353   }
5354 
5355   return TheCallResult;
5356 }
5357 
5358 /// SemaBuiltinNontemporalOverloaded - We have a call to
5359 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5360 /// overloaded function based on the pointer type of its last argument.
5361 ///
5362 /// This function goes through and does final semantic checking for these
5363 /// builtins.
5364 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5365   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5366   DeclRefExpr *DRE =
5367       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5368   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5369   unsigned BuiltinID = FDecl->getBuiltinID();
5370   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5371           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5372          "Unexpected nontemporal load/store builtin!");
5373   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5374   unsigned numArgs = isStore ? 2 : 1;
5375 
5376   // Ensure that we have the proper number of arguments.
5377   if (checkArgCount(*this, TheCall, numArgs))
5378     return ExprError();
5379 
5380   // Inspect the last argument of the nontemporal builtin.  This should always
5381   // be a pointer type, from which we imply the type of the memory access.
5382   // Because it is a pointer type, we don't have to worry about any implicit
5383   // casts here.
5384   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5385   ExprResult PointerArgResult =
5386       DefaultFunctionArrayLvalueConversion(PointerArg);
5387 
5388   if (PointerArgResult.isInvalid())
5389     return ExprError();
5390   PointerArg = PointerArgResult.get();
5391   TheCall->setArg(numArgs - 1, PointerArg);
5392 
5393   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5394   if (!pointerType) {
5395     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5396         << PointerArg->getType() << PointerArg->getSourceRange();
5397     return ExprError();
5398   }
5399 
5400   QualType ValType = pointerType->getPointeeType();
5401 
5402   // Strip any qualifiers off ValType.
5403   ValType = ValType.getUnqualifiedType();
5404   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5405       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5406       !ValType->isVectorType()) {
5407     Diag(DRE->getBeginLoc(),
5408          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5409         << PointerArg->getType() << PointerArg->getSourceRange();
5410     return ExprError();
5411   }
5412 
5413   if (!isStore) {
5414     TheCall->setType(ValType);
5415     return TheCallResult;
5416   }
5417 
5418   ExprResult ValArg = TheCall->getArg(0);
5419   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5420       Context, ValType, /*consume*/ false);
5421   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5422   if (ValArg.isInvalid())
5423     return ExprError();
5424 
5425   TheCall->setArg(0, ValArg.get());
5426   TheCall->setType(Context.VoidTy);
5427   return TheCallResult;
5428 }
5429 
5430 /// CheckObjCString - Checks that the argument to the builtin
5431 /// CFString constructor is correct
5432 /// Note: It might also make sense to do the UTF-16 conversion here (would
5433 /// simplify the backend).
5434 bool Sema::CheckObjCString(Expr *Arg) {
5435   Arg = Arg->IgnoreParenCasts();
5436   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5437 
5438   if (!Literal || !Literal->isAscii()) {
5439     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5440         << Arg->getSourceRange();
5441     return true;
5442   }
5443 
5444   if (Literal->containsNonAsciiOrNull()) {
5445     StringRef String = Literal->getString();
5446     unsigned NumBytes = String.size();
5447     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5448     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5449     llvm::UTF16 *ToPtr = &ToBuf[0];
5450 
5451     llvm::ConversionResult Result =
5452         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5453                                  ToPtr + NumBytes, llvm::strictConversion);
5454     // Check for conversion failure.
5455     if (Result != llvm::conversionOK)
5456       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5457           << Arg->getSourceRange();
5458   }
5459   return false;
5460 }
5461 
5462 /// CheckObjCString - Checks that the format string argument to the os_log()
5463 /// and os_trace() functions is correct, and converts it to const char *.
5464 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5465   Arg = Arg->IgnoreParenCasts();
5466   auto *Literal = dyn_cast<StringLiteral>(Arg);
5467   if (!Literal) {
5468     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5469       Literal = ObjcLiteral->getString();
5470     }
5471   }
5472 
5473   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5474     return ExprError(
5475         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5476         << Arg->getSourceRange());
5477   }
5478 
5479   ExprResult Result(Literal);
5480   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5481   InitializedEntity Entity =
5482       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5483   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5484   return Result;
5485 }
5486 
5487 /// Check that the user is calling the appropriate va_start builtin for the
5488 /// target and calling convention.
5489 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5490   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5491   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5492   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5493                     TT.getArch() == llvm::Triple::aarch64_32);
5494   bool IsWindows = TT.isOSWindows();
5495   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5496   if (IsX64 || IsAArch64) {
5497     CallingConv CC = CC_C;
5498     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5499       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5500     if (IsMSVAStart) {
5501       // Don't allow this in System V ABI functions.
5502       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5503         return S.Diag(Fn->getBeginLoc(),
5504                       diag::err_ms_va_start_used_in_sysv_function);
5505     } else {
5506       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5507       // On x64 Windows, don't allow this in System V ABI functions.
5508       // (Yes, that means there's no corresponding way to support variadic
5509       // System V ABI functions on Windows.)
5510       if ((IsWindows && CC == CC_X86_64SysV) ||
5511           (!IsWindows && CC == CC_Win64))
5512         return S.Diag(Fn->getBeginLoc(),
5513                       diag::err_va_start_used_in_wrong_abi_function)
5514                << !IsWindows;
5515     }
5516     return false;
5517   }
5518 
5519   if (IsMSVAStart)
5520     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5521   return false;
5522 }
5523 
5524 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5525                                              ParmVarDecl **LastParam = nullptr) {
5526   // Determine whether the current function, block, or obj-c method is variadic
5527   // and get its parameter list.
5528   bool IsVariadic = false;
5529   ArrayRef<ParmVarDecl *> Params;
5530   DeclContext *Caller = S.CurContext;
5531   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5532     IsVariadic = Block->isVariadic();
5533     Params = Block->parameters();
5534   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5535     IsVariadic = FD->isVariadic();
5536     Params = FD->parameters();
5537   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5538     IsVariadic = MD->isVariadic();
5539     // FIXME: This isn't correct for methods (results in bogus warning).
5540     Params = MD->parameters();
5541   } else if (isa<CapturedDecl>(Caller)) {
5542     // We don't support va_start in a CapturedDecl.
5543     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5544     return true;
5545   } else {
5546     // This must be some other declcontext that parses exprs.
5547     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5548     return true;
5549   }
5550 
5551   if (!IsVariadic) {
5552     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5553     return true;
5554   }
5555 
5556   if (LastParam)
5557     *LastParam = Params.empty() ? nullptr : Params.back();
5558 
5559   return false;
5560 }
5561 
5562 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5563 /// for validity.  Emit an error and return true on failure; return false
5564 /// on success.
5565 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5566   Expr *Fn = TheCall->getCallee();
5567 
5568   if (checkVAStartABI(*this, BuiltinID, Fn))
5569     return true;
5570 
5571   if (TheCall->getNumArgs() > 2) {
5572     Diag(TheCall->getArg(2)->getBeginLoc(),
5573          diag::err_typecheck_call_too_many_args)
5574         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5575         << Fn->getSourceRange()
5576         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5577                        (*(TheCall->arg_end() - 1))->getEndLoc());
5578     return true;
5579   }
5580 
5581   if (TheCall->getNumArgs() < 2) {
5582     return Diag(TheCall->getEndLoc(),
5583                 diag::err_typecheck_call_too_few_args_at_least)
5584            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5585   }
5586 
5587   // Type-check the first argument normally.
5588   if (checkBuiltinArgument(*this, TheCall, 0))
5589     return true;
5590 
5591   // Check that the current function is variadic, and get its last parameter.
5592   ParmVarDecl *LastParam;
5593   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5594     return true;
5595 
5596   // Verify that the second argument to the builtin is the last argument of the
5597   // current function or method.
5598   bool SecondArgIsLastNamedArgument = false;
5599   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5600 
5601   // These are valid if SecondArgIsLastNamedArgument is false after the next
5602   // block.
5603   QualType Type;
5604   SourceLocation ParamLoc;
5605   bool IsCRegister = false;
5606 
5607   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5608     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5609       SecondArgIsLastNamedArgument = PV == LastParam;
5610 
5611       Type = PV->getType();
5612       ParamLoc = PV->getLocation();
5613       IsCRegister =
5614           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5615     }
5616   }
5617 
5618   if (!SecondArgIsLastNamedArgument)
5619     Diag(TheCall->getArg(1)->getBeginLoc(),
5620          diag::warn_second_arg_of_va_start_not_last_named_param);
5621   else if (IsCRegister || Type->isReferenceType() ||
5622            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5623              // Promotable integers are UB, but enumerations need a bit of
5624              // extra checking to see what their promotable type actually is.
5625              if (!Type->isPromotableIntegerType())
5626                return false;
5627              if (!Type->isEnumeralType())
5628                return true;
5629              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5630              return !(ED &&
5631                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5632            }()) {
5633     unsigned Reason = 0;
5634     if (Type->isReferenceType())  Reason = 1;
5635     else if (IsCRegister)         Reason = 2;
5636     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5637     Diag(ParamLoc, diag::note_parameter_type) << Type;
5638   }
5639 
5640   TheCall->setType(Context.VoidTy);
5641   return false;
5642 }
5643 
5644 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5645   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5646   //                 const char *named_addr);
5647 
5648   Expr *Func = Call->getCallee();
5649 
5650   if (Call->getNumArgs() < 3)
5651     return Diag(Call->getEndLoc(),
5652                 diag::err_typecheck_call_too_few_args_at_least)
5653            << 0 /*function call*/ << 3 << Call->getNumArgs();
5654 
5655   // Type-check the first argument normally.
5656   if (checkBuiltinArgument(*this, Call, 0))
5657     return true;
5658 
5659   // Check that the current function is variadic.
5660   if (checkVAStartIsInVariadicFunction(*this, Func))
5661     return true;
5662 
5663   // __va_start on Windows does not validate the parameter qualifiers
5664 
5665   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5666   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5667 
5668   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5669   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5670 
5671   const QualType &ConstCharPtrTy =
5672       Context.getPointerType(Context.CharTy.withConst());
5673   if (!Arg1Ty->isPointerType() ||
5674       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5675     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5676         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5677         << 0                                      /* qualifier difference */
5678         << 3                                      /* parameter mismatch */
5679         << 2 << Arg1->getType() << ConstCharPtrTy;
5680 
5681   const QualType SizeTy = Context.getSizeType();
5682   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5683     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5684         << Arg2->getType() << SizeTy << 1 /* different class */
5685         << 0                              /* qualifier difference */
5686         << 3                              /* parameter mismatch */
5687         << 3 << Arg2->getType() << SizeTy;
5688 
5689   return false;
5690 }
5691 
5692 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5693 /// friends.  This is declared to take (...), so we have to check everything.
5694 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5695   if (TheCall->getNumArgs() < 2)
5696     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5697            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5698   if (TheCall->getNumArgs() > 2)
5699     return Diag(TheCall->getArg(2)->getBeginLoc(),
5700                 diag::err_typecheck_call_too_many_args)
5701            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5702            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5703                           (*(TheCall->arg_end() - 1))->getEndLoc());
5704 
5705   ExprResult OrigArg0 = TheCall->getArg(0);
5706   ExprResult OrigArg1 = TheCall->getArg(1);
5707 
5708   // Do standard promotions between the two arguments, returning their common
5709   // type.
5710   QualType Res = UsualArithmeticConversions(
5711       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5712   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5713     return true;
5714 
5715   // Make sure any conversions are pushed back into the call; this is
5716   // type safe since unordered compare builtins are declared as "_Bool
5717   // foo(...)".
5718   TheCall->setArg(0, OrigArg0.get());
5719   TheCall->setArg(1, OrigArg1.get());
5720 
5721   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5722     return false;
5723 
5724   // If the common type isn't a real floating type, then the arguments were
5725   // invalid for this operation.
5726   if (Res.isNull() || !Res->isRealFloatingType())
5727     return Diag(OrigArg0.get()->getBeginLoc(),
5728                 diag::err_typecheck_call_invalid_ordered_compare)
5729            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5730            << SourceRange(OrigArg0.get()->getBeginLoc(),
5731                           OrigArg1.get()->getEndLoc());
5732 
5733   return false;
5734 }
5735 
5736 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5737 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5738 /// to check everything. We expect the last argument to be a floating point
5739 /// value.
5740 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5741   if (TheCall->getNumArgs() < NumArgs)
5742     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5743            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5744   if (TheCall->getNumArgs() > NumArgs)
5745     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5746                 diag::err_typecheck_call_too_many_args)
5747            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5748            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5749                           (*(TheCall->arg_end() - 1))->getEndLoc());
5750 
5751   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5752   // on all preceding parameters just being int.  Try all of those.
5753   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5754     Expr *Arg = TheCall->getArg(i);
5755 
5756     if (Arg->isTypeDependent())
5757       return false;
5758 
5759     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5760 
5761     if (Res.isInvalid())
5762       return true;
5763     TheCall->setArg(i, Res.get());
5764   }
5765 
5766   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5767 
5768   if (OrigArg->isTypeDependent())
5769     return false;
5770 
5771   // Usual Unary Conversions will convert half to float, which we want for
5772   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5773   // type how it is, but do normal L->Rvalue conversions.
5774   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5775     OrigArg = UsualUnaryConversions(OrigArg).get();
5776   else
5777     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5778   TheCall->setArg(NumArgs - 1, OrigArg);
5779 
5780   // This operation requires a non-_Complex floating-point number.
5781   if (!OrigArg->getType()->isRealFloatingType())
5782     return Diag(OrigArg->getBeginLoc(),
5783                 diag::err_typecheck_call_invalid_unary_fp)
5784            << OrigArg->getType() << OrigArg->getSourceRange();
5785 
5786   return false;
5787 }
5788 
5789 // Customized Sema Checking for VSX builtins that have the following signature:
5790 // vector [...] builtinName(vector [...], vector [...], const int);
5791 // Which takes the same type of vectors (any legal vector type) for the first
5792 // two arguments and takes compile time constant for the third argument.
5793 // Example builtins are :
5794 // vector double vec_xxpermdi(vector double, vector double, int);
5795 // vector short vec_xxsldwi(vector short, vector short, int);
5796 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5797   unsigned ExpectedNumArgs = 3;
5798   if (TheCall->getNumArgs() < ExpectedNumArgs)
5799     return Diag(TheCall->getEndLoc(),
5800                 diag::err_typecheck_call_too_few_args_at_least)
5801            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5802            << TheCall->getSourceRange();
5803 
5804   if (TheCall->getNumArgs() > ExpectedNumArgs)
5805     return Diag(TheCall->getEndLoc(),
5806                 diag::err_typecheck_call_too_many_args_at_most)
5807            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5808            << TheCall->getSourceRange();
5809 
5810   // Check the third argument is a compile time constant
5811   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
5812     return Diag(TheCall->getBeginLoc(),
5813                 diag::err_vsx_builtin_nonconstant_argument)
5814            << 3 /* argument index */ << TheCall->getDirectCallee()
5815            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5816                           TheCall->getArg(2)->getEndLoc());
5817 
5818   QualType Arg1Ty = TheCall->getArg(0)->getType();
5819   QualType Arg2Ty = TheCall->getArg(1)->getType();
5820 
5821   // Check the type of argument 1 and argument 2 are vectors.
5822   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5823   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5824       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5825     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5826            << TheCall->getDirectCallee()
5827            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5828                           TheCall->getArg(1)->getEndLoc());
5829   }
5830 
5831   // Check the first two arguments are the same type.
5832   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5833     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5834            << TheCall->getDirectCallee()
5835            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5836                           TheCall->getArg(1)->getEndLoc());
5837   }
5838 
5839   // When default clang type checking is turned off and the customized type
5840   // checking is used, the returning type of the function must be explicitly
5841   // set. Otherwise it is _Bool by default.
5842   TheCall->setType(Arg1Ty);
5843 
5844   return false;
5845 }
5846 
5847 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5848 // This is declared to take (...), so we have to check everything.
5849 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5850   if (TheCall->getNumArgs() < 2)
5851     return ExprError(Diag(TheCall->getEndLoc(),
5852                           diag::err_typecheck_call_too_few_args_at_least)
5853                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5854                      << TheCall->getSourceRange());
5855 
5856   // Determine which of the following types of shufflevector we're checking:
5857   // 1) unary, vector mask: (lhs, mask)
5858   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5859   QualType resType = TheCall->getArg(0)->getType();
5860   unsigned numElements = 0;
5861 
5862   if (!TheCall->getArg(0)->isTypeDependent() &&
5863       !TheCall->getArg(1)->isTypeDependent()) {
5864     QualType LHSType = TheCall->getArg(0)->getType();
5865     QualType RHSType = TheCall->getArg(1)->getType();
5866 
5867     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5868       return ExprError(
5869           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5870           << TheCall->getDirectCallee()
5871           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5872                          TheCall->getArg(1)->getEndLoc()));
5873 
5874     numElements = LHSType->castAs<VectorType>()->getNumElements();
5875     unsigned numResElements = TheCall->getNumArgs() - 2;
5876 
5877     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5878     // with mask.  If so, verify that RHS is an integer vector type with the
5879     // same number of elts as lhs.
5880     if (TheCall->getNumArgs() == 2) {
5881       if (!RHSType->hasIntegerRepresentation() ||
5882           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5883         return ExprError(Diag(TheCall->getBeginLoc(),
5884                               diag::err_vec_builtin_incompatible_vector)
5885                          << TheCall->getDirectCallee()
5886                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5887                                         TheCall->getArg(1)->getEndLoc()));
5888     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5889       return ExprError(Diag(TheCall->getBeginLoc(),
5890                             diag::err_vec_builtin_incompatible_vector)
5891                        << TheCall->getDirectCallee()
5892                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5893                                       TheCall->getArg(1)->getEndLoc()));
5894     } else if (numElements != numResElements) {
5895       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5896       resType = Context.getVectorType(eltType, numResElements,
5897                                       VectorType::GenericVector);
5898     }
5899   }
5900 
5901   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5902     if (TheCall->getArg(i)->isTypeDependent() ||
5903         TheCall->getArg(i)->isValueDependent())
5904       continue;
5905 
5906     Optional<llvm::APSInt> Result;
5907     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
5908       return ExprError(Diag(TheCall->getBeginLoc(),
5909                             diag::err_shufflevector_nonconstant_argument)
5910                        << TheCall->getArg(i)->getSourceRange());
5911 
5912     // Allow -1 which will be translated to undef in the IR.
5913     if (Result->isSigned() && Result->isAllOnesValue())
5914       continue;
5915 
5916     if (Result->getActiveBits() > 64 ||
5917         Result->getZExtValue() >= numElements * 2)
5918       return ExprError(Diag(TheCall->getBeginLoc(),
5919                             diag::err_shufflevector_argument_too_large)
5920                        << TheCall->getArg(i)->getSourceRange());
5921   }
5922 
5923   SmallVector<Expr*, 32> exprs;
5924 
5925   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5926     exprs.push_back(TheCall->getArg(i));
5927     TheCall->setArg(i, nullptr);
5928   }
5929 
5930   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5931                                          TheCall->getCallee()->getBeginLoc(),
5932                                          TheCall->getRParenLoc());
5933 }
5934 
5935 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5936 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5937                                        SourceLocation BuiltinLoc,
5938                                        SourceLocation RParenLoc) {
5939   ExprValueKind VK = VK_RValue;
5940   ExprObjectKind OK = OK_Ordinary;
5941   QualType DstTy = TInfo->getType();
5942   QualType SrcTy = E->getType();
5943 
5944   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5945     return ExprError(Diag(BuiltinLoc,
5946                           diag::err_convertvector_non_vector)
5947                      << E->getSourceRange());
5948   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5949     return ExprError(Diag(BuiltinLoc,
5950                           diag::err_convertvector_non_vector_type));
5951 
5952   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5953     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5954     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5955     if (SrcElts != DstElts)
5956       return ExprError(Diag(BuiltinLoc,
5957                             diag::err_convertvector_incompatible_vector)
5958                        << E->getSourceRange());
5959   }
5960 
5961   return new (Context)
5962       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5963 }
5964 
5965 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5966 // This is declared to take (const void*, ...) and can take two
5967 // optional constant int args.
5968 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5969   unsigned NumArgs = TheCall->getNumArgs();
5970 
5971   if (NumArgs > 3)
5972     return Diag(TheCall->getEndLoc(),
5973                 diag::err_typecheck_call_too_many_args_at_most)
5974            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5975 
5976   // Argument 0 is checked for us and the remaining arguments must be
5977   // constant integers.
5978   for (unsigned i = 1; i != NumArgs; ++i)
5979     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5980       return true;
5981 
5982   return false;
5983 }
5984 
5985 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5986 // __assume does not evaluate its arguments, and should warn if its argument
5987 // has side effects.
5988 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5989   Expr *Arg = TheCall->getArg(0);
5990   if (Arg->isInstantiationDependent()) return false;
5991 
5992   if (Arg->HasSideEffects(Context))
5993     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5994         << Arg->getSourceRange()
5995         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5996 
5997   return false;
5998 }
5999 
6000 /// Handle __builtin_alloca_with_align. This is declared
6001 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6002 /// than 8.
6003 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6004   // The alignment must be a constant integer.
6005   Expr *Arg = TheCall->getArg(1);
6006 
6007   // We can't check the value of a dependent argument.
6008   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6009     if (const auto *UE =
6010             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6011       if (UE->getKind() == UETT_AlignOf ||
6012           UE->getKind() == UETT_PreferredAlignOf)
6013         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6014             << Arg->getSourceRange();
6015 
6016     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6017 
6018     if (!Result.isPowerOf2())
6019       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6020              << Arg->getSourceRange();
6021 
6022     if (Result < Context.getCharWidth())
6023       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6024              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6025 
6026     if (Result > std::numeric_limits<int32_t>::max())
6027       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6028              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6029   }
6030 
6031   return false;
6032 }
6033 
6034 /// Handle __builtin_assume_aligned. This is declared
6035 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6036 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6037   unsigned NumArgs = TheCall->getNumArgs();
6038 
6039   if (NumArgs > 3)
6040     return Diag(TheCall->getEndLoc(),
6041                 diag::err_typecheck_call_too_many_args_at_most)
6042            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6043 
6044   // The alignment must be a constant integer.
6045   Expr *Arg = TheCall->getArg(1);
6046 
6047   // We can't check the value of a dependent argument.
6048   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6049     llvm::APSInt Result;
6050     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6051       return true;
6052 
6053     if (!Result.isPowerOf2())
6054       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6055              << Arg->getSourceRange();
6056 
6057     if (Result > Sema::MaximumAlignment)
6058       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6059           << Arg->getSourceRange() << Sema::MaximumAlignment;
6060   }
6061 
6062   if (NumArgs > 2) {
6063     ExprResult Arg(TheCall->getArg(2));
6064     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6065       Context.getSizeType(), false);
6066     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6067     if (Arg.isInvalid()) return true;
6068     TheCall->setArg(2, Arg.get());
6069   }
6070 
6071   return false;
6072 }
6073 
6074 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6075   unsigned BuiltinID =
6076       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6077   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6078 
6079   unsigned NumArgs = TheCall->getNumArgs();
6080   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6081   if (NumArgs < NumRequiredArgs) {
6082     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6083            << 0 /* function call */ << NumRequiredArgs << NumArgs
6084            << TheCall->getSourceRange();
6085   }
6086   if (NumArgs >= NumRequiredArgs + 0x100) {
6087     return Diag(TheCall->getEndLoc(),
6088                 diag::err_typecheck_call_too_many_args_at_most)
6089            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6090            << TheCall->getSourceRange();
6091   }
6092   unsigned i = 0;
6093 
6094   // For formatting call, check buffer arg.
6095   if (!IsSizeCall) {
6096     ExprResult Arg(TheCall->getArg(i));
6097     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6098         Context, Context.VoidPtrTy, false);
6099     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6100     if (Arg.isInvalid())
6101       return true;
6102     TheCall->setArg(i, Arg.get());
6103     i++;
6104   }
6105 
6106   // Check string literal arg.
6107   unsigned FormatIdx = i;
6108   {
6109     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6110     if (Arg.isInvalid())
6111       return true;
6112     TheCall->setArg(i, Arg.get());
6113     i++;
6114   }
6115 
6116   // Make sure variadic args are scalar.
6117   unsigned FirstDataArg = i;
6118   while (i < NumArgs) {
6119     ExprResult Arg = DefaultVariadicArgumentPromotion(
6120         TheCall->getArg(i), VariadicFunction, nullptr);
6121     if (Arg.isInvalid())
6122       return true;
6123     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6124     if (ArgSize.getQuantity() >= 0x100) {
6125       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6126              << i << (int)ArgSize.getQuantity() << 0xff
6127              << TheCall->getSourceRange();
6128     }
6129     TheCall->setArg(i, Arg.get());
6130     i++;
6131   }
6132 
6133   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6134   // call to avoid duplicate diagnostics.
6135   if (!IsSizeCall) {
6136     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6137     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6138     bool Success = CheckFormatArguments(
6139         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6140         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6141         CheckedVarArgs);
6142     if (!Success)
6143       return true;
6144   }
6145 
6146   if (IsSizeCall) {
6147     TheCall->setType(Context.getSizeType());
6148   } else {
6149     TheCall->setType(Context.VoidPtrTy);
6150   }
6151   return false;
6152 }
6153 
6154 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6155 /// TheCall is a constant expression.
6156 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6157                                   llvm::APSInt &Result) {
6158   Expr *Arg = TheCall->getArg(ArgNum);
6159   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6160   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6161 
6162   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6163 
6164   Optional<llvm::APSInt> R;
6165   if (!(R = Arg->getIntegerConstantExpr(Context)))
6166     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6167            << FDecl->getDeclName() << Arg->getSourceRange();
6168   Result = *R;
6169   return false;
6170 }
6171 
6172 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6173 /// TheCall is a constant expression in the range [Low, High].
6174 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6175                                        int Low, int High, bool RangeIsError) {
6176   if (isConstantEvaluated())
6177     return false;
6178   llvm::APSInt Result;
6179 
6180   // We can't check the value of a dependent argument.
6181   Expr *Arg = TheCall->getArg(ArgNum);
6182   if (Arg->isTypeDependent() || Arg->isValueDependent())
6183     return false;
6184 
6185   // Check constant-ness first.
6186   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6187     return true;
6188 
6189   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6190     if (RangeIsError)
6191       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6192              << Result.toString(10) << Low << High << Arg->getSourceRange();
6193     else
6194       // Defer the warning until we know if the code will be emitted so that
6195       // dead code can ignore this.
6196       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6197                           PDiag(diag::warn_argument_invalid_range)
6198                               << Result.toString(10) << Low << High
6199                               << Arg->getSourceRange());
6200   }
6201 
6202   return false;
6203 }
6204 
6205 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6206 /// TheCall is a constant expression is a multiple of Num..
6207 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6208                                           unsigned Num) {
6209   llvm::APSInt Result;
6210 
6211   // We can't check the value of a dependent argument.
6212   Expr *Arg = TheCall->getArg(ArgNum);
6213   if (Arg->isTypeDependent() || Arg->isValueDependent())
6214     return false;
6215 
6216   // Check constant-ness first.
6217   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6218     return true;
6219 
6220   if (Result.getSExtValue() % Num != 0)
6221     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6222            << Num << Arg->getSourceRange();
6223 
6224   return false;
6225 }
6226 
6227 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6228 /// constant expression representing a power of 2.
6229 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6230   llvm::APSInt Result;
6231 
6232   // We can't check the value of a dependent argument.
6233   Expr *Arg = TheCall->getArg(ArgNum);
6234   if (Arg->isTypeDependent() || Arg->isValueDependent())
6235     return false;
6236 
6237   // Check constant-ness first.
6238   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6239     return true;
6240 
6241   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6242   // and only if x is a power of 2.
6243   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6244     return false;
6245 
6246   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6247          << Arg->getSourceRange();
6248 }
6249 
6250 static bool IsShiftedByte(llvm::APSInt Value) {
6251   if (Value.isNegative())
6252     return false;
6253 
6254   // Check if it's a shifted byte, by shifting it down
6255   while (true) {
6256     // If the value fits in the bottom byte, the check passes.
6257     if (Value < 0x100)
6258       return true;
6259 
6260     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6261     // fails.
6262     if ((Value & 0xFF) != 0)
6263       return false;
6264 
6265     // If the bottom 8 bits are all 0, but something above that is nonzero,
6266     // then shifting the value right by 8 bits won't affect whether it's a
6267     // shifted byte or not. So do that, and go round again.
6268     Value >>= 8;
6269   }
6270 }
6271 
6272 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6273 /// a constant expression representing an arbitrary byte value shifted left by
6274 /// a multiple of 8 bits.
6275 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6276                                              unsigned ArgBits) {
6277   llvm::APSInt Result;
6278 
6279   // We can't check the value of a dependent argument.
6280   Expr *Arg = TheCall->getArg(ArgNum);
6281   if (Arg->isTypeDependent() || Arg->isValueDependent())
6282     return false;
6283 
6284   // Check constant-ness first.
6285   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6286     return true;
6287 
6288   // Truncate to the given size.
6289   Result = Result.getLoBits(ArgBits);
6290   Result.setIsUnsigned(true);
6291 
6292   if (IsShiftedByte(Result))
6293     return false;
6294 
6295   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6296          << Arg->getSourceRange();
6297 }
6298 
6299 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6300 /// TheCall is a constant expression representing either a shifted byte value,
6301 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6302 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6303 /// Arm MVE intrinsics.
6304 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6305                                                    int ArgNum,
6306                                                    unsigned ArgBits) {
6307   llvm::APSInt Result;
6308 
6309   // We can't check the value of a dependent argument.
6310   Expr *Arg = TheCall->getArg(ArgNum);
6311   if (Arg->isTypeDependent() || Arg->isValueDependent())
6312     return false;
6313 
6314   // Check constant-ness first.
6315   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6316     return true;
6317 
6318   // Truncate to the given size.
6319   Result = Result.getLoBits(ArgBits);
6320   Result.setIsUnsigned(true);
6321 
6322   // Check to see if it's in either of the required forms.
6323   if (IsShiftedByte(Result) ||
6324       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6325     return false;
6326 
6327   return Diag(TheCall->getBeginLoc(),
6328               diag::err_argument_not_shifted_byte_or_xxff)
6329          << Arg->getSourceRange();
6330 }
6331 
6332 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6333 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6334   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6335     if (checkArgCount(*this, TheCall, 2))
6336       return true;
6337     Expr *Arg0 = TheCall->getArg(0);
6338     Expr *Arg1 = TheCall->getArg(1);
6339 
6340     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6341     if (FirstArg.isInvalid())
6342       return true;
6343     QualType FirstArgType = FirstArg.get()->getType();
6344     if (!FirstArgType->isAnyPointerType())
6345       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6346                << "first" << FirstArgType << Arg0->getSourceRange();
6347     TheCall->setArg(0, FirstArg.get());
6348 
6349     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6350     if (SecArg.isInvalid())
6351       return true;
6352     QualType SecArgType = SecArg.get()->getType();
6353     if (!SecArgType->isIntegerType())
6354       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6355                << "second" << SecArgType << Arg1->getSourceRange();
6356 
6357     // Derive the return type from the pointer argument.
6358     TheCall->setType(FirstArgType);
6359     return false;
6360   }
6361 
6362   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6363     if (checkArgCount(*this, TheCall, 2))
6364       return true;
6365 
6366     Expr *Arg0 = TheCall->getArg(0);
6367     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6368     if (FirstArg.isInvalid())
6369       return true;
6370     QualType FirstArgType = FirstArg.get()->getType();
6371     if (!FirstArgType->isAnyPointerType())
6372       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6373                << "first" << FirstArgType << Arg0->getSourceRange();
6374     TheCall->setArg(0, FirstArg.get());
6375 
6376     // Derive the return type from the pointer argument.
6377     TheCall->setType(FirstArgType);
6378 
6379     // Second arg must be an constant in range [0,15]
6380     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6381   }
6382 
6383   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6384     if (checkArgCount(*this, TheCall, 2))
6385       return true;
6386     Expr *Arg0 = TheCall->getArg(0);
6387     Expr *Arg1 = TheCall->getArg(1);
6388 
6389     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6390     if (FirstArg.isInvalid())
6391       return true;
6392     QualType FirstArgType = FirstArg.get()->getType();
6393     if (!FirstArgType->isAnyPointerType())
6394       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6395                << "first" << FirstArgType << Arg0->getSourceRange();
6396 
6397     QualType SecArgType = Arg1->getType();
6398     if (!SecArgType->isIntegerType())
6399       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6400                << "second" << SecArgType << Arg1->getSourceRange();
6401     TheCall->setType(Context.IntTy);
6402     return false;
6403   }
6404 
6405   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6406       BuiltinID == AArch64::BI__builtin_arm_stg) {
6407     if (checkArgCount(*this, TheCall, 1))
6408       return true;
6409     Expr *Arg0 = TheCall->getArg(0);
6410     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6411     if (FirstArg.isInvalid())
6412       return true;
6413 
6414     QualType FirstArgType = FirstArg.get()->getType();
6415     if (!FirstArgType->isAnyPointerType())
6416       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6417                << "first" << FirstArgType << Arg0->getSourceRange();
6418     TheCall->setArg(0, FirstArg.get());
6419 
6420     // Derive the return type from the pointer argument.
6421     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6422       TheCall->setType(FirstArgType);
6423     return false;
6424   }
6425 
6426   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6427     Expr *ArgA = TheCall->getArg(0);
6428     Expr *ArgB = TheCall->getArg(1);
6429 
6430     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6431     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6432 
6433     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6434       return true;
6435 
6436     QualType ArgTypeA = ArgExprA.get()->getType();
6437     QualType ArgTypeB = ArgExprB.get()->getType();
6438 
6439     auto isNull = [&] (Expr *E) -> bool {
6440       return E->isNullPointerConstant(
6441                         Context, Expr::NPC_ValueDependentIsNotNull); };
6442 
6443     // argument should be either a pointer or null
6444     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6445       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6446         << "first" << ArgTypeA << ArgA->getSourceRange();
6447 
6448     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6449       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6450         << "second" << ArgTypeB << ArgB->getSourceRange();
6451 
6452     // Ensure Pointee types are compatible
6453     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6454         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6455       QualType pointeeA = ArgTypeA->getPointeeType();
6456       QualType pointeeB = ArgTypeB->getPointeeType();
6457       if (!Context.typesAreCompatible(
6458              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6459              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6460         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6461           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6462           << ArgB->getSourceRange();
6463       }
6464     }
6465 
6466     // at least one argument should be pointer type
6467     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6468       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6469         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6470 
6471     if (isNull(ArgA)) // adopt type of the other pointer
6472       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6473 
6474     if (isNull(ArgB))
6475       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6476 
6477     TheCall->setArg(0, ArgExprA.get());
6478     TheCall->setArg(1, ArgExprB.get());
6479     TheCall->setType(Context.LongLongTy);
6480     return false;
6481   }
6482   assert(false && "Unhandled ARM MTE intrinsic");
6483   return true;
6484 }
6485 
6486 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6487 /// TheCall is an ARM/AArch64 special register string literal.
6488 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6489                                     int ArgNum, unsigned ExpectedFieldNum,
6490                                     bool AllowName) {
6491   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6492                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6493                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6494                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6495                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6496                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6497   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6498                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6499                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6500                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6501                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6502                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6503   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6504 
6505   // We can't check the value of a dependent argument.
6506   Expr *Arg = TheCall->getArg(ArgNum);
6507   if (Arg->isTypeDependent() || Arg->isValueDependent())
6508     return false;
6509 
6510   // Check if the argument is a string literal.
6511   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6512     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6513            << Arg->getSourceRange();
6514 
6515   // Check the type of special register given.
6516   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6517   SmallVector<StringRef, 6> Fields;
6518   Reg.split(Fields, ":");
6519 
6520   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6521     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6522            << Arg->getSourceRange();
6523 
6524   // If the string is the name of a register then we cannot check that it is
6525   // valid here but if the string is of one the forms described in ACLE then we
6526   // can check that the supplied fields are integers and within the valid
6527   // ranges.
6528   if (Fields.size() > 1) {
6529     bool FiveFields = Fields.size() == 5;
6530 
6531     bool ValidString = true;
6532     if (IsARMBuiltin) {
6533       ValidString &= Fields[0].startswith_lower("cp") ||
6534                      Fields[0].startswith_lower("p");
6535       if (ValidString)
6536         Fields[0] =
6537           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6538 
6539       ValidString &= Fields[2].startswith_lower("c");
6540       if (ValidString)
6541         Fields[2] = Fields[2].drop_front(1);
6542 
6543       if (FiveFields) {
6544         ValidString &= Fields[3].startswith_lower("c");
6545         if (ValidString)
6546           Fields[3] = Fields[3].drop_front(1);
6547       }
6548     }
6549 
6550     SmallVector<int, 5> Ranges;
6551     if (FiveFields)
6552       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6553     else
6554       Ranges.append({15, 7, 15});
6555 
6556     for (unsigned i=0; i<Fields.size(); ++i) {
6557       int IntField;
6558       ValidString &= !Fields[i].getAsInteger(10, IntField);
6559       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6560     }
6561 
6562     if (!ValidString)
6563       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6564              << Arg->getSourceRange();
6565   } else if (IsAArch64Builtin && Fields.size() == 1) {
6566     // If the register name is one of those that appear in the condition below
6567     // and the special register builtin being used is one of the write builtins,
6568     // then we require that the argument provided for writing to the register
6569     // is an integer constant expression. This is because it will be lowered to
6570     // an MSR (immediate) instruction, so we need to know the immediate at
6571     // compile time.
6572     if (TheCall->getNumArgs() != 2)
6573       return false;
6574 
6575     std::string RegLower = Reg.lower();
6576     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6577         RegLower != "pan" && RegLower != "uao")
6578       return false;
6579 
6580     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6581   }
6582 
6583   return false;
6584 }
6585 
6586 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6587 /// This checks that the target supports __builtin_longjmp and
6588 /// that val is a constant 1.
6589 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6590   if (!Context.getTargetInfo().hasSjLjLowering())
6591     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6592            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6593 
6594   Expr *Arg = TheCall->getArg(1);
6595   llvm::APSInt Result;
6596 
6597   // TODO: This is less than ideal. Overload this to take a value.
6598   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6599     return true;
6600 
6601   if (Result != 1)
6602     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6603            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6604 
6605   return false;
6606 }
6607 
6608 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6609 /// This checks that the target supports __builtin_setjmp.
6610 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6611   if (!Context.getTargetInfo().hasSjLjLowering())
6612     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6613            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6614   return false;
6615 }
6616 
6617 namespace {
6618 
6619 class UncoveredArgHandler {
6620   enum { Unknown = -1, AllCovered = -2 };
6621 
6622   signed FirstUncoveredArg = Unknown;
6623   SmallVector<const Expr *, 4> DiagnosticExprs;
6624 
6625 public:
6626   UncoveredArgHandler() = default;
6627 
6628   bool hasUncoveredArg() const {
6629     return (FirstUncoveredArg >= 0);
6630   }
6631 
6632   unsigned getUncoveredArg() const {
6633     assert(hasUncoveredArg() && "no uncovered argument");
6634     return FirstUncoveredArg;
6635   }
6636 
6637   void setAllCovered() {
6638     // A string has been found with all arguments covered, so clear out
6639     // the diagnostics.
6640     DiagnosticExprs.clear();
6641     FirstUncoveredArg = AllCovered;
6642   }
6643 
6644   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6645     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6646 
6647     // Don't update if a previous string covers all arguments.
6648     if (FirstUncoveredArg == AllCovered)
6649       return;
6650 
6651     // UncoveredArgHandler tracks the highest uncovered argument index
6652     // and with it all the strings that match this index.
6653     if (NewFirstUncoveredArg == FirstUncoveredArg)
6654       DiagnosticExprs.push_back(StrExpr);
6655     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6656       DiagnosticExprs.clear();
6657       DiagnosticExprs.push_back(StrExpr);
6658       FirstUncoveredArg = NewFirstUncoveredArg;
6659     }
6660   }
6661 
6662   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6663 };
6664 
6665 enum StringLiteralCheckType {
6666   SLCT_NotALiteral,
6667   SLCT_UncheckedLiteral,
6668   SLCT_CheckedLiteral
6669 };
6670 
6671 } // namespace
6672 
6673 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6674                                      BinaryOperatorKind BinOpKind,
6675                                      bool AddendIsRight) {
6676   unsigned BitWidth = Offset.getBitWidth();
6677   unsigned AddendBitWidth = Addend.getBitWidth();
6678   // There might be negative interim results.
6679   if (Addend.isUnsigned()) {
6680     Addend = Addend.zext(++AddendBitWidth);
6681     Addend.setIsSigned(true);
6682   }
6683   // Adjust the bit width of the APSInts.
6684   if (AddendBitWidth > BitWidth) {
6685     Offset = Offset.sext(AddendBitWidth);
6686     BitWidth = AddendBitWidth;
6687   } else if (BitWidth > AddendBitWidth) {
6688     Addend = Addend.sext(BitWidth);
6689   }
6690 
6691   bool Ov = false;
6692   llvm::APSInt ResOffset = Offset;
6693   if (BinOpKind == BO_Add)
6694     ResOffset = Offset.sadd_ov(Addend, Ov);
6695   else {
6696     assert(AddendIsRight && BinOpKind == BO_Sub &&
6697            "operator must be add or sub with addend on the right");
6698     ResOffset = Offset.ssub_ov(Addend, Ov);
6699   }
6700 
6701   // We add an offset to a pointer here so we should support an offset as big as
6702   // possible.
6703   if (Ov) {
6704     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6705            "index (intermediate) result too big");
6706     Offset = Offset.sext(2 * BitWidth);
6707     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6708     return;
6709   }
6710 
6711   Offset = ResOffset;
6712 }
6713 
6714 namespace {
6715 
6716 // This is a wrapper class around StringLiteral to support offsetted string
6717 // literals as format strings. It takes the offset into account when returning
6718 // the string and its length or the source locations to display notes correctly.
6719 class FormatStringLiteral {
6720   const StringLiteral *FExpr;
6721   int64_t Offset;
6722 
6723  public:
6724   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6725       : FExpr(fexpr), Offset(Offset) {}
6726 
6727   StringRef getString() const {
6728     return FExpr->getString().drop_front(Offset);
6729   }
6730 
6731   unsigned getByteLength() const {
6732     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6733   }
6734 
6735   unsigned getLength() const { return FExpr->getLength() - Offset; }
6736   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6737 
6738   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6739 
6740   QualType getType() const { return FExpr->getType(); }
6741 
6742   bool isAscii() const { return FExpr->isAscii(); }
6743   bool isWide() const { return FExpr->isWide(); }
6744   bool isUTF8() const { return FExpr->isUTF8(); }
6745   bool isUTF16() const { return FExpr->isUTF16(); }
6746   bool isUTF32() const { return FExpr->isUTF32(); }
6747   bool isPascal() const { return FExpr->isPascal(); }
6748 
6749   SourceLocation getLocationOfByte(
6750       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6751       const TargetInfo &Target, unsigned *StartToken = nullptr,
6752       unsigned *StartTokenByteOffset = nullptr) const {
6753     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6754                                     StartToken, StartTokenByteOffset);
6755   }
6756 
6757   SourceLocation getBeginLoc() const LLVM_READONLY {
6758     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6759   }
6760 
6761   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6762 };
6763 
6764 }  // namespace
6765 
6766 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6767                               const Expr *OrigFormatExpr,
6768                               ArrayRef<const Expr *> Args,
6769                               bool HasVAListArg, unsigned format_idx,
6770                               unsigned firstDataArg,
6771                               Sema::FormatStringType Type,
6772                               bool inFunctionCall,
6773                               Sema::VariadicCallType CallType,
6774                               llvm::SmallBitVector &CheckedVarArgs,
6775                               UncoveredArgHandler &UncoveredArg,
6776                               bool IgnoreStringsWithoutSpecifiers);
6777 
6778 // Determine if an expression is a string literal or constant string.
6779 // If this function returns false on the arguments to a function expecting a
6780 // format string, we will usually need to emit a warning.
6781 // True string literals are then checked by CheckFormatString.
6782 static StringLiteralCheckType
6783 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6784                       bool HasVAListArg, unsigned format_idx,
6785                       unsigned firstDataArg, Sema::FormatStringType Type,
6786                       Sema::VariadicCallType CallType, bool InFunctionCall,
6787                       llvm::SmallBitVector &CheckedVarArgs,
6788                       UncoveredArgHandler &UncoveredArg,
6789                       llvm::APSInt Offset,
6790                       bool IgnoreStringsWithoutSpecifiers = false) {
6791   if (S.isConstantEvaluated())
6792     return SLCT_NotALiteral;
6793  tryAgain:
6794   assert(Offset.isSigned() && "invalid offset");
6795 
6796   if (E->isTypeDependent() || E->isValueDependent())
6797     return SLCT_NotALiteral;
6798 
6799   E = E->IgnoreParenCasts();
6800 
6801   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6802     // Technically -Wformat-nonliteral does not warn about this case.
6803     // The behavior of printf and friends in this case is implementation
6804     // dependent.  Ideally if the format string cannot be null then
6805     // it should have a 'nonnull' attribute in the function prototype.
6806     return SLCT_UncheckedLiteral;
6807 
6808   switch (E->getStmtClass()) {
6809   case Stmt::BinaryConditionalOperatorClass:
6810   case Stmt::ConditionalOperatorClass: {
6811     // The expression is a literal if both sub-expressions were, and it was
6812     // completely checked only if both sub-expressions were checked.
6813     const AbstractConditionalOperator *C =
6814         cast<AbstractConditionalOperator>(E);
6815 
6816     // Determine whether it is necessary to check both sub-expressions, for
6817     // example, because the condition expression is a constant that can be
6818     // evaluated at compile time.
6819     bool CheckLeft = true, CheckRight = true;
6820 
6821     bool Cond;
6822     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6823                                                  S.isConstantEvaluated())) {
6824       if (Cond)
6825         CheckRight = false;
6826       else
6827         CheckLeft = false;
6828     }
6829 
6830     // We need to maintain the offsets for the right and the left hand side
6831     // separately to check if every possible indexed expression is a valid
6832     // string literal. They might have different offsets for different string
6833     // literals in the end.
6834     StringLiteralCheckType Left;
6835     if (!CheckLeft)
6836       Left = SLCT_UncheckedLiteral;
6837     else {
6838       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6839                                    HasVAListArg, format_idx, firstDataArg,
6840                                    Type, CallType, InFunctionCall,
6841                                    CheckedVarArgs, UncoveredArg, Offset,
6842                                    IgnoreStringsWithoutSpecifiers);
6843       if (Left == SLCT_NotALiteral || !CheckRight) {
6844         return Left;
6845       }
6846     }
6847 
6848     StringLiteralCheckType Right = checkFormatStringExpr(
6849         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6850         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6851         IgnoreStringsWithoutSpecifiers);
6852 
6853     return (CheckLeft && Left < Right) ? Left : Right;
6854   }
6855 
6856   case Stmt::ImplicitCastExprClass:
6857     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6858     goto tryAgain;
6859 
6860   case Stmt::OpaqueValueExprClass:
6861     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6862       E = src;
6863       goto tryAgain;
6864     }
6865     return SLCT_NotALiteral;
6866 
6867   case Stmt::PredefinedExprClass:
6868     // While __func__, etc., are technically not string literals, they
6869     // cannot contain format specifiers and thus are not a security
6870     // liability.
6871     return SLCT_UncheckedLiteral;
6872 
6873   case Stmt::DeclRefExprClass: {
6874     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6875 
6876     // As an exception, do not flag errors for variables binding to
6877     // const string literals.
6878     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6879       bool isConstant = false;
6880       QualType T = DR->getType();
6881 
6882       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6883         isConstant = AT->getElementType().isConstant(S.Context);
6884       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6885         isConstant = T.isConstant(S.Context) &&
6886                      PT->getPointeeType().isConstant(S.Context);
6887       } else if (T->isObjCObjectPointerType()) {
6888         // In ObjC, there is usually no "const ObjectPointer" type,
6889         // so don't check if the pointee type is constant.
6890         isConstant = T.isConstant(S.Context);
6891       }
6892 
6893       if (isConstant) {
6894         if (const Expr *Init = VD->getAnyInitializer()) {
6895           // Look through initializers like const char c[] = { "foo" }
6896           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6897             if (InitList->isStringLiteralInit())
6898               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6899           }
6900           return checkFormatStringExpr(S, Init, Args,
6901                                        HasVAListArg, format_idx,
6902                                        firstDataArg, Type, CallType,
6903                                        /*InFunctionCall*/ false, CheckedVarArgs,
6904                                        UncoveredArg, Offset);
6905         }
6906       }
6907 
6908       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6909       // special check to see if the format string is a function parameter
6910       // of the function calling the printf function.  If the function
6911       // has an attribute indicating it is a printf-like function, then we
6912       // should suppress warnings concerning non-literals being used in a call
6913       // to a vprintf function.  For example:
6914       //
6915       // void
6916       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6917       //      va_list ap;
6918       //      va_start(ap, fmt);
6919       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6920       //      ...
6921       // }
6922       if (HasVAListArg) {
6923         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6924           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6925             int PVIndex = PV->getFunctionScopeIndex() + 1;
6926             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6927               // adjust for implicit parameter
6928               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6929                 if (MD->isInstance())
6930                   ++PVIndex;
6931               // We also check if the formats are compatible.
6932               // We can't pass a 'scanf' string to a 'printf' function.
6933               if (PVIndex == PVFormat->getFormatIdx() &&
6934                   Type == S.GetFormatStringType(PVFormat))
6935                 return SLCT_UncheckedLiteral;
6936             }
6937           }
6938         }
6939       }
6940     }
6941 
6942     return SLCT_NotALiteral;
6943   }
6944 
6945   case Stmt::CallExprClass:
6946   case Stmt::CXXMemberCallExprClass: {
6947     const CallExpr *CE = cast<CallExpr>(E);
6948     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6949       bool IsFirst = true;
6950       StringLiteralCheckType CommonResult;
6951       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6952         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6953         StringLiteralCheckType Result = checkFormatStringExpr(
6954             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6955             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6956             IgnoreStringsWithoutSpecifiers);
6957         if (IsFirst) {
6958           CommonResult = Result;
6959           IsFirst = false;
6960         }
6961       }
6962       if (!IsFirst)
6963         return CommonResult;
6964 
6965       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6966         unsigned BuiltinID = FD->getBuiltinID();
6967         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6968             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6969           const Expr *Arg = CE->getArg(0);
6970           return checkFormatStringExpr(S, Arg, Args,
6971                                        HasVAListArg, format_idx,
6972                                        firstDataArg, Type, CallType,
6973                                        InFunctionCall, CheckedVarArgs,
6974                                        UncoveredArg, Offset,
6975                                        IgnoreStringsWithoutSpecifiers);
6976         }
6977       }
6978     }
6979 
6980     return SLCT_NotALiteral;
6981   }
6982   case Stmt::ObjCMessageExprClass: {
6983     const auto *ME = cast<ObjCMessageExpr>(E);
6984     if (const auto *MD = ME->getMethodDecl()) {
6985       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6986         // As a special case heuristic, if we're using the method -[NSBundle
6987         // localizedStringForKey:value:table:], ignore any key strings that lack
6988         // format specifiers. The idea is that if the key doesn't have any
6989         // format specifiers then its probably just a key to map to the
6990         // localized strings. If it does have format specifiers though, then its
6991         // likely that the text of the key is the format string in the
6992         // programmer's language, and should be checked.
6993         const ObjCInterfaceDecl *IFace;
6994         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6995             IFace->getIdentifier()->isStr("NSBundle") &&
6996             MD->getSelector().isKeywordSelector(
6997                 {"localizedStringForKey", "value", "table"})) {
6998           IgnoreStringsWithoutSpecifiers = true;
6999         }
7000 
7001         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7002         return checkFormatStringExpr(
7003             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7004             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7005             IgnoreStringsWithoutSpecifiers);
7006       }
7007     }
7008 
7009     return SLCT_NotALiteral;
7010   }
7011   case Stmt::ObjCStringLiteralClass:
7012   case Stmt::StringLiteralClass: {
7013     const StringLiteral *StrE = nullptr;
7014 
7015     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7016       StrE = ObjCFExpr->getString();
7017     else
7018       StrE = cast<StringLiteral>(E);
7019 
7020     if (StrE) {
7021       if (Offset.isNegative() || Offset > StrE->getLength()) {
7022         // TODO: It would be better to have an explicit warning for out of
7023         // bounds literals.
7024         return SLCT_NotALiteral;
7025       }
7026       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7027       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7028                         firstDataArg, Type, InFunctionCall, CallType,
7029                         CheckedVarArgs, UncoveredArg,
7030                         IgnoreStringsWithoutSpecifiers);
7031       return SLCT_CheckedLiteral;
7032     }
7033 
7034     return SLCT_NotALiteral;
7035   }
7036   case Stmt::BinaryOperatorClass: {
7037     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7038 
7039     // A string literal + an int offset is still a string literal.
7040     if (BinOp->isAdditiveOp()) {
7041       Expr::EvalResult LResult, RResult;
7042 
7043       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7044           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7045       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7046           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7047 
7048       if (LIsInt != RIsInt) {
7049         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7050 
7051         if (LIsInt) {
7052           if (BinOpKind == BO_Add) {
7053             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7054             E = BinOp->getRHS();
7055             goto tryAgain;
7056           }
7057         } else {
7058           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7059           E = BinOp->getLHS();
7060           goto tryAgain;
7061         }
7062       }
7063     }
7064 
7065     return SLCT_NotALiteral;
7066   }
7067   case Stmt::UnaryOperatorClass: {
7068     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7069     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7070     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7071       Expr::EvalResult IndexResult;
7072       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7073                                        Expr::SE_NoSideEffects,
7074                                        S.isConstantEvaluated())) {
7075         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7076                    /*RHS is int*/ true);
7077         E = ASE->getBase();
7078         goto tryAgain;
7079       }
7080     }
7081 
7082     return SLCT_NotALiteral;
7083   }
7084 
7085   default:
7086     return SLCT_NotALiteral;
7087   }
7088 }
7089 
7090 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7091   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7092       .Case("scanf", FST_Scanf)
7093       .Cases("printf", "printf0", FST_Printf)
7094       .Cases("NSString", "CFString", FST_NSString)
7095       .Case("strftime", FST_Strftime)
7096       .Case("strfmon", FST_Strfmon)
7097       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7098       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7099       .Case("os_trace", FST_OSLog)
7100       .Case("os_log", FST_OSLog)
7101       .Default(FST_Unknown);
7102 }
7103 
7104 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7105 /// functions) for correct use of format strings.
7106 /// Returns true if a format string has been fully checked.
7107 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7108                                 ArrayRef<const Expr *> Args,
7109                                 bool IsCXXMember,
7110                                 VariadicCallType CallType,
7111                                 SourceLocation Loc, SourceRange Range,
7112                                 llvm::SmallBitVector &CheckedVarArgs) {
7113   FormatStringInfo FSI;
7114   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7115     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7116                                 FSI.FirstDataArg, GetFormatStringType(Format),
7117                                 CallType, Loc, Range, CheckedVarArgs);
7118   return false;
7119 }
7120 
7121 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7122                                 bool HasVAListArg, unsigned format_idx,
7123                                 unsigned firstDataArg, FormatStringType Type,
7124                                 VariadicCallType CallType,
7125                                 SourceLocation Loc, SourceRange Range,
7126                                 llvm::SmallBitVector &CheckedVarArgs) {
7127   // CHECK: printf/scanf-like function is called with no format string.
7128   if (format_idx >= Args.size()) {
7129     Diag(Loc, diag::warn_missing_format_string) << Range;
7130     return false;
7131   }
7132 
7133   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7134 
7135   // CHECK: format string is not a string literal.
7136   //
7137   // Dynamically generated format strings are difficult to
7138   // automatically vet at compile time.  Requiring that format strings
7139   // are string literals: (1) permits the checking of format strings by
7140   // the compiler and thereby (2) can practically remove the source of
7141   // many format string exploits.
7142 
7143   // Format string can be either ObjC string (e.g. @"%d") or
7144   // C string (e.g. "%d")
7145   // ObjC string uses the same format specifiers as C string, so we can use
7146   // the same format string checking logic for both ObjC and C strings.
7147   UncoveredArgHandler UncoveredArg;
7148   StringLiteralCheckType CT =
7149       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7150                             format_idx, firstDataArg, Type, CallType,
7151                             /*IsFunctionCall*/ true, CheckedVarArgs,
7152                             UncoveredArg,
7153                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7154 
7155   // Generate a diagnostic where an uncovered argument is detected.
7156   if (UncoveredArg.hasUncoveredArg()) {
7157     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7158     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7159     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7160   }
7161 
7162   if (CT != SLCT_NotALiteral)
7163     // Literal format string found, check done!
7164     return CT == SLCT_CheckedLiteral;
7165 
7166   // Strftime is particular as it always uses a single 'time' argument,
7167   // so it is safe to pass a non-literal string.
7168   if (Type == FST_Strftime)
7169     return false;
7170 
7171   // Do not emit diag when the string param is a macro expansion and the
7172   // format is either NSString or CFString. This is a hack to prevent
7173   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7174   // which are usually used in place of NS and CF string literals.
7175   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7176   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7177     return false;
7178 
7179   // If there are no arguments specified, warn with -Wformat-security, otherwise
7180   // warn only with -Wformat-nonliteral.
7181   if (Args.size() == firstDataArg) {
7182     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7183       << OrigFormatExpr->getSourceRange();
7184     switch (Type) {
7185     default:
7186       break;
7187     case FST_Kprintf:
7188     case FST_FreeBSDKPrintf:
7189     case FST_Printf:
7190       Diag(FormatLoc, diag::note_format_security_fixit)
7191         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7192       break;
7193     case FST_NSString:
7194       Diag(FormatLoc, diag::note_format_security_fixit)
7195         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7196       break;
7197     }
7198   } else {
7199     Diag(FormatLoc, diag::warn_format_nonliteral)
7200       << OrigFormatExpr->getSourceRange();
7201   }
7202   return false;
7203 }
7204 
7205 namespace {
7206 
7207 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7208 protected:
7209   Sema &S;
7210   const FormatStringLiteral *FExpr;
7211   const Expr *OrigFormatExpr;
7212   const Sema::FormatStringType FSType;
7213   const unsigned FirstDataArg;
7214   const unsigned NumDataArgs;
7215   const char *Beg; // Start of format string.
7216   const bool HasVAListArg;
7217   ArrayRef<const Expr *> Args;
7218   unsigned FormatIdx;
7219   llvm::SmallBitVector CoveredArgs;
7220   bool usesPositionalArgs = false;
7221   bool atFirstArg = true;
7222   bool inFunctionCall;
7223   Sema::VariadicCallType CallType;
7224   llvm::SmallBitVector &CheckedVarArgs;
7225   UncoveredArgHandler &UncoveredArg;
7226 
7227 public:
7228   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7229                      const Expr *origFormatExpr,
7230                      const Sema::FormatStringType type, unsigned firstDataArg,
7231                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7232                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7233                      bool inFunctionCall, Sema::VariadicCallType callType,
7234                      llvm::SmallBitVector &CheckedVarArgs,
7235                      UncoveredArgHandler &UncoveredArg)
7236       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7237         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7238         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7239         inFunctionCall(inFunctionCall), CallType(callType),
7240         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7241     CoveredArgs.resize(numDataArgs);
7242     CoveredArgs.reset();
7243   }
7244 
7245   void DoneProcessing();
7246 
7247   void HandleIncompleteSpecifier(const char *startSpecifier,
7248                                  unsigned specifierLen) override;
7249 
7250   void HandleInvalidLengthModifier(
7251                            const analyze_format_string::FormatSpecifier &FS,
7252                            const analyze_format_string::ConversionSpecifier &CS,
7253                            const char *startSpecifier, unsigned specifierLen,
7254                            unsigned DiagID);
7255 
7256   void HandleNonStandardLengthModifier(
7257                     const analyze_format_string::FormatSpecifier &FS,
7258                     const char *startSpecifier, unsigned specifierLen);
7259 
7260   void HandleNonStandardConversionSpecifier(
7261                     const analyze_format_string::ConversionSpecifier &CS,
7262                     const char *startSpecifier, unsigned specifierLen);
7263 
7264   void HandlePosition(const char *startPos, unsigned posLen) override;
7265 
7266   void HandleInvalidPosition(const char *startSpecifier,
7267                              unsigned specifierLen,
7268                              analyze_format_string::PositionContext p) override;
7269 
7270   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7271 
7272   void HandleNullChar(const char *nullCharacter) override;
7273 
7274   template <typename Range>
7275   static void
7276   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7277                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7278                        bool IsStringLocation, Range StringRange,
7279                        ArrayRef<FixItHint> Fixit = None);
7280 
7281 protected:
7282   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7283                                         const char *startSpec,
7284                                         unsigned specifierLen,
7285                                         const char *csStart, unsigned csLen);
7286 
7287   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7288                                          const char *startSpec,
7289                                          unsigned specifierLen);
7290 
7291   SourceRange getFormatStringRange();
7292   CharSourceRange getSpecifierRange(const char *startSpecifier,
7293                                     unsigned specifierLen);
7294   SourceLocation getLocationOfByte(const char *x);
7295 
7296   const Expr *getDataArg(unsigned i) const;
7297 
7298   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7299                     const analyze_format_string::ConversionSpecifier &CS,
7300                     const char *startSpecifier, unsigned specifierLen,
7301                     unsigned argIndex);
7302 
7303   template <typename Range>
7304   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7305                             bool IsStringLocation, Range StringRange,
7306                             ArrayRef<FixItHint> Fixit = None);
7307 };
7308 
7309 } // namespace
7310 
7311 SourceRange CheckFormatHandler::getFormatStringRange() {
7312   return OrigFormatExpr->getSourceRange();
7313 }
7314 
7315 CharSourceRange CheckFormatHandler::
7316 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7317   SourceLocation Start = getLocationOfByte(startSpecifier);
7318   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7319 
7320   // Advance the end SourceLocation by one due to half-open ranges.
7321   End = End.getLocWithOffset(1);
7322 
7323   return CharSourceRange::getCharRange(Start, End);
7324 }
7325 
7326 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7327   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7328                                   S.getLangOpts(), S.Context.getTargetInfo());
7329 }
7330 
7331 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7332                                                    unsigned specifierLen){
7333   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7334                        getLocationOfByte(startSpecifier),
7335                        /*IsStringLocation*/true,
7336                        getSpecifierRange(startSpecifier, specifierLen));
7337 }
7338 
7339 void CheckFormatHandler::HandleInvalidLengthModifier(
7340     const analyze_format_string::FormatSpecifier &FS,
7341     const analyze_format_string::ConversionSpecifier &CS,
7342     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7343   using namespace analyze_format_string;
7344 
7345   const LengthModifier &LM = FS.getLengthModifier();
7346   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7347 
7348   // See if we know how to fix this length modifier.
7349   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7350   if (FixedLM) {
7351     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7352                          getLocationOfByte(LM.getStart()),
7353                          /*IsStringLocation*/true,
7354                          getSpecifierRange(startSpecifier, specifierLen));
7355 
7356     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7357       << FixedLM->toString()
7358       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7359 
7360   } else {
7361     FixItHint Hint;
7362     if (DiagID == diag::warn_format_nonsensical_length)
7363       Hint = FixItHint::CreateRemoval(LMRange);
7364 
7365     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7366                          getLocationOfByte(LM.getStart()),
7367                          /*IsStringLocation*/true,
7368                          getSpecifierRange(startSpecifier, specifierLen),
7369                          Hint);
7370   }
7371 }
7372 
7373 void CheckFormatHandler::HandleNonStandardLengthModifier(
7374     const analyze_format_string::FormatSpecifier &FS,
7375     const char *startSpecifier, unsigned specifierLen) {
7376   using namespace analyze_format_string;
7377 
7378   const LengthModifier &LM = FS.getLengthModifier();
7379   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7380 
7381   // See if we know how to fix this length modifier.
7382   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7383   if (FixedLM) {
7384     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7385                            << LM.toString() << 0,
7386                          getLocationOfByte(LM.getStart()),
7387                          /*IsStringLocation*/true,
7388                          getSpecifierRange(startSpecifier, specifierLen));
7389 
7390     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7391       << FixedLM->toString()
7392       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7393 
7394   } else {
7395     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7396                            << LM.toString() << 0,
7397                          getLocationOfByte(LM.getStart()),
7398                          /*IsStringLocation*/true,
7399                          getSpecifierRange(startSpecifier, specifierLen));
7400   }
7401 }
7402 
7403 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7404     const analyze_format_string::ConversionSpecifier &CS,
7405     const char *startSpecifier, unsigned specifierLen) {
7406   using namespace analyze_format_string;
7407 
7408   // See if we know how to fix this conversion specifier.
7409   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7410   if (FixedCS) {
7411     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7412                           << CS.toString() << /*conversion specifier*/1,
7413                          getLocationOfByte(CS.getStart()),
7414                          /*IsStringLocation*/true,
7415                          getSpecifierRange(startSpecifier, specifierLen));
7416 
7417     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7418     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7419       << FixedCS->toString()
7420       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7421   } else {
7422     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7423                           << CS.toString() << /*conversion specifier*/1,
7424                          getLocationOfByte(CS.getStart()),
7425                          /*IsStringLocation*/true,
7426                          getSpecifierRange(startSpecifier, specifierLen));
7427   }
7428 }
7429 
7430 void CheckFormatHandler::HandlePosition(const char *startPos,
7431                                         unsigned posLen) {
7432   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7433                                getLocationOfByte(startPos),
7434                                /*IsStringLocation*/true,
7435                                getSpecifierRange(startPos, posLen));
7436 }
7437 
7438 void
7439 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7440                                      analyze_format_string::PositionContext p) {
7441   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7442                          << (unsigned) p,
7443                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7444                        getSpecifierRange(startPos, posLen));
7445 }
7446 
7447 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7448                                             unsigned posLen) {
7449   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7450                                getLocationOfByte(startPos),
7451                                /*IsStringLocation*/true,
7452                                getSpecifierRange(startPos, posLen));
7453 }
7454 
7455 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7456   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7457     // The presence of a null character is likely an error.
7458     EmitFormatDiagnostic(
7459       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7460       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7461       getFormatStringRange());
7462   }
7463 }
7464 
7465 // Note that this may return NULL if there was an error parsing or building
7466 // one of the argument expressions.
7467 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7468   return Args[FirstDataArg + i];
7469 }
7470 
7471 void CheckFormatHandler::DoneProcessing() {
7472   // Does the number of data arguments exceed the number of
7473   // format conversions in the format string?
7474   if (!HasVAListArg) {
7475       // Find any arguments that weren't covered.
7476     CoveredArgs.flip();
7477     signed notCoveredArg = CoveredArgs.find_first();
7478     if (notCoveredArg >= 0) {
7479       assert((unsigned)notCoveredArg < NumDataArgs);
7480       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7481     } else {
7482       UncoveredArg.setAllCovered();
7483     }
7484   }
7485 }
7486 
7487 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7488                                    const Expr *ArgExpr) {
7489   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7490          "Invalid state");
7491 
7492   if (!ArgExpr)
7493     return;
7494 
7495   SourceLocation Loc = ArgExpr->getBeginLoc();
7496 
7497   if (S.getSourceManager().isInSystemMacro(Loc))
7498     return;
7499 
7500   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7501   for (auto E : DiagnosticExprs)
7502     PDiag << E->getSourceRange();
7503 
7504   CheckFormatHandler::EmitFormatDiagnostic(
7505                                   S, IsFunctionCall, DiagnosticExprs[0],
7506                                   PDiag, Loc, /*IsStringLocation*/false,
7507                                   DiagnosticExprs[0]->getSourceRange());
7508 }
7509 
7510 bool
7511 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7512                                                      SourceLocation Loc,
7513                                                      const char *startSpec,
7514                                                      unsigned specifierLen,
7515                                                      const char *csStart,
7516                                                      unsigned csLen) {
7517   bool keepGoing = true;
7518   if (argIndex < NumDataArgs) {
7519     // Consider the argument coverered, even though the specifier doesn't
7520     // make sense.
7521     CoveredArgs.set(argIndex);
7522   }
7523   else {
7524     // If argIndex exceeds the number of data arguments we
7525     // don't issue a warning because that is just a cascade of warnings (and
7526     // they may have intended '%%' anyway). We don't want to continue processing
7527     // the format string after this point, however, as we will like just get
7528     // gibberish when trying to match arguments.
7529     keepGoing = false;
7530   }
7531 
7532   StringRef Specifier(csStart, csLen);
7533 
7534   // If the specifier in non-printable, it could be the first byte of a UTF-8
7535   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7536   // hex value.
7537   std::string CodePointStr;
7538   if (!llvm::sys::locale::isPrint(*csStart)) {
7539     llvm::UTF32 CodePoint;
7540     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7541     const llvm::UTF8 *E =
7542         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7543     llvm::ConversionResult Result =
7544         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7545 
7546     if (Result != llvm::conversionOK) {
7547       unsigned char FirstChar = *csStart;
7548       CodePoint = (llvm::UTF32)FirstChar;
7549     }
7550 
7551     llvm::raw_string_ostream OS(CodePointStr);
7552     if (CodePoint < 256)
7553       OS << "\\x" << llvm::format("%02x", CodePoint);
7554     else if (CodePoint <= 0xFFFF)
7555       OS << "\\u" << llvm::format("%04x", CodePoint);
7556     else
7557       OS << "\\U" << llvm::format("%08x", CodePoint);
7558     OS.flush();
7559     Specifier = CodePointStr;
7560   }
7561 
7562   EmitFormatDiagnostic(
7563       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7564       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7565 
7566   return keepGoing;
7567 }
7568 
7569 void
7570 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7571                                                       const char *startSpec,
7572                                                       unsigned specifierLen) {
7573   EmitFormatDiagnostic(
7574     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7575     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7576 }
7577 
7578 bool
7579 CheckFormatHandler::CheckNumArgs(
7580   const analyze_format_string::FormatSpecifier &FS,
7581   const analyze_format_string::ConversionSpecifier &CS,
7582   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7583 
7584   if (argIndex >= NumDataArgs) {
7585     PartialDiagnostic PDiag = FS.usesPositionalArg()
7586       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7587            << (argIndex+1) << NumDataArgs)
7588       : S.PDiag(diag::warn_printf_insufficient_data_args);
7589     EmitFormatDiagnostic(
7590       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7591       getSpecifierRange(startSpecifier, specifierLen));
7592 
7593     // Since more arguments than conversion tokens are given, by extension
7594     // all arguments are covered, so mark this as so.
7595     UncoveredArg.setAllCovered();
7596     return false;
7597   }
7598   return true;
7599 }
7600 
7601 template<typename Range>
7602 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7603                                               SourceLocation Loc,
7604                                               bool IsStringLocation,
7605                                               Range StringRange,
7606                                               ArrayRef<FixItHint> FixIt) {
7607   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7608                        Loc, IsStringLocation, StringRange, FixIt);
7609 }
7610 
7611 /// If the format string is not within the function call, emit a note
7612 /// so that the function call and string are in diagnostic messages.
7613 ///
7614 /// \param InFunctionCall if true, the format string is within the function
7615 /// call and only one diagnostic message will be produced.  Otherwise, an
7616 /// extra note will be emitted pointing to location of the format string.
7617 ///
7618 /// \param ArgumentExpr the expression that is passed as the format string
7619 /// argument in the function call.  Used for getting locations when two
7620 /// diagnostics are emitted.
7621 ///
7622 /// \param PDiag the callee should already have provided any strings for the
7623 /// diagnostic message.  This function only adds locations and fixits
7624 /// to diagnostics.
7625 ///
7626 /// \param Loc primary location for diagnostic.  If two diagnostics are
7627 /// required, one will be at Loc and a new SourceLocation will be created for
7628 /// the other one.
7629 ///
7630 /// \param IsStringLocation if true, Loc points to the format string should be
7631 /// used for the note.  Otherwise, Loc points to the argument list and will
7632 /// be used with PDiag.
7633 ///
7634 /// \param StringRange some or all of the string to highlight.  This is
7635 /// templated so it can accept either a CharSourceRange or a SourceRange.
7636 ///
7637 /// \param FixIt optional fix it hint for the format string.
7638 template <typename Range>
7639 void CheckFormatHandler::EmitFormatDiagnostic(
7640     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7641     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7642     Range StringRange, ArrayRef<FixItHint> FixIt) {
7643   if (InFunctionCall) {
7644     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7645     D << StringRange;
7646     D << FixIt;
7647   } else {
7648     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7649       << ArgumentExpr->getSourceRange();
7650 
7651     const Sema::SemaDiagnosticBuilder &Note =
7652       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7653              diag::note_format_string_defined);
7654 
7655     Note << StringRange;
7656     Note << FixIt;
7657   }
7658 }
7659 
7660 //===--- CHECK: Printf format string checking ------------------------------===//
7661 
7662 namespace {
7663 
7664 class CheckPrintfHandler : public CheckFormatHandler {
7665 public:
7666   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7667                      const Expr *origFormatExpr,
7668                      const Sema::FormatStringType type, unsigned firstDataArg,
7669                      unsigned numDataArgs, bool isObjC, const char *beg,
7670                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7671                      unsigned formatIdx, bool inFunctionCall,
7672                      Sema::VariadicCallType CallType,
7673                      llvm::SmallBitVector &CheckedVarArgs,
7674                      UncoveredArgHandler &UncoveredArg)
7675       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7676                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7677                            inFunctionCall, CallType, CheckedVarArgs,
7678                            UncoveredArg) {}
7679 
7680   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7681 
7682   /// Returns true if '%@' specifiers are allowed in the format string.
7683   bool allowsObjCArg() const {
7684     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7685            FSType == Sema::FST_OSTrace;
7686   }
7687 
7688   bool HandleInvalidPrintfConversionSpecifier(
7689                                       const analyze_printf::PrintfSpecifier &FS,
7690                                       const char *startSpecifier,
7691                                       unsigned specifierLen) override;
7692 
7693   void handleInvalidMaskType(StringRef MaskType) override;
7694 
7695   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7696                              const char *startSpecifier,
7697                              unsigned specifierLen) override;
7698   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7699                        const char *StartSpecifier,
7700                        unsigned SpecifierLen,
7701                        const Expr *E);
7702 
7703   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7704                     const char *startSpecifier, unsigned specifierLen);
7705   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7706                            const analyze_printf::OptionalAmount &Amt,
7707                            unsigned type,
7708                            const char *startSpecifier, unsigned specifierLen);
7709   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7710                   const analyze_printf::OptionalFlag &flag,
7711                   const char *startSpecifier, unsigned specifierLen);
7712   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7713                          const analyze_printf::OptionalFlag &ignoredFlag,
7714                          const analyze_printf::OptionalFlag &flag,
7715                          const char *startSpecifier, unsigned specifierLen);
7716   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7717                            const Expr *E);
7718 
7719   void HandleEmptyObjCModifierFlag(const char *startFlag,
7720                                    unsigned flagLen) override;
7721 
7722   void HandleInvalidObjCModifierFlag(const char *startFlag,
7723                                             unsigned flagLen) override;
7724 
7725   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7726                                            const char *flagsEnd,
7727                                            const char *conversionPosition)
7728                                              override;
7729 };
7730 
7731 } // namespace
7732 
7733 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7734                                       const analyze_printf::PrintfSpecifier &FS,
7735                                       const char *startSpecifier,
7736                                       unsigned specifierLen) {
7737   const analyze_printf::PrintfConversionSpecifier &CS =
7738     FS.getConversionSpecifier();
7739 
7740   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7741                                           getLocationOfByte(CS.getStart()),
7742                                           startSpecifier, specifierLen,
7743                                           CS.getStart(), CS.getLength());
7744 }
7745 
7746 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7747   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7748 }
7749 
7750 bool CheckPrintfHandler::HandleAmount(
7751                                const analyze_format_string::OptionalAmount &Amt,
7752                                unsigned k, const char *startSpecifier,
7753                                unsigned specifierLen) {
7754   if (Amt.hasDataArgument()) {
7755     if (!HasVAListArg) {
7756       unsigned argIndex = Amt.getArgIndex();
7757       if (argIndex >= NumDataArgs) {
7758         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7759                                << k,
7760                              getLocationOfByte(Amt.getStart()),
7761                              /*IsStringLocation*/true,
7762                              getSpecifierRange(startSpecifier, specifierLen));
7763         // Don't do any more checking.  We will just emit
7764         // spurious errors.
7765         return false;
7766       }
7767 
7768       // Type check the data argument.  It should be an 'int'.
7769       // Although not in conformance with C99, we also allow the argument to be
7770       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7771       // doesn't emit a warning for that case.
7772       CoveredArgs.set(argIndex);
7773       const Expr *Arg = getDataArg(argIndex);
7774       if (!Arg)
7775         return false;
7776 
7777       QualType T = Arg->getType();
7778 
7779       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7780       assert(AT.isValid());
7781 
7782       if (!AT.matchesType(S.Context, T)) {
7783         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7784                                << k << AT.getRepresentativeTypeName(S.Context)
7785                                << T << Arg->getSourceRange(),
7786                              getLocationOfByte(Amt.getStart()),
7787                              /*IsStringLocation*/true,
7788                              getSpecifierRange(startSpecifier, specifierLen));
7789         // Don't do any more checking.  We will just emit
7790         // spurious errors.
7791         return false;
7792       }
7793     }
7794   }
7795   return true;
7796 }
7797 
7798 void CheckPrintfHandler::HandleInvalidAmount(
7799                                       const analyze_printf::PrintfSpecifier &FS,
7800                                       const analyze_printf::OptionalAmount &Amt,
7801                                       unsigned type,
7802                                       const char *startSpecifier,
7803                                       unsigned specifierLen) {
7804   const analyze_printf::PrintfConversionSpecifier &CS =
7805     FS.getConversionSpecifier();
7806 
7807   FixItHint fixit =
7808     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7809       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7810                                  Amt.getConstantLength()))
7811       : FixItHint();
7812 
7813   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7814                          << type << CS.toString(),
7815                        getLocationOfByte(Amt.getStart()),
7816                        /*IsStringLocation*/true,
7817                        getSpecifierRange(startSpecifier, specifierLen),
7818                        fixit);
7819 }
7820 
7821 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7822                                     const analyze_printf::OptionalFlag &flag,
7823                                     const char *startSpecifier,
7824                                     unsigned specifierLen) {
7825   // Warn about pointless flag with a fixit removal.
7826   const analyze_printf::PrintfConversionSpecifier &CS =
7827     FS.getConversionSpecifier();
7828   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7829                          << flag.toString() << CS.toString(),
7830                        getLocationOfByte(flag.getPosition()),
7831                        /*IsStringLocation*/true,
7832                        getSpecifierRange(startSpecifier, specifierLen),
7833                        FixItHint::CreateRemoval(
7834                          getSpecifierRange(flag.getPosition(), 1)));
7835 }
7836 
7837 void CheckPrintfHandler::HandleIgnoredFlag(
7838                                 const analyze_printf::PrintfSpecifier &FS,
7839                                 const analyze_printf::OptionalFlag &ignoredFlag,
7840                                 const analyze_printf::OptionalFlag &flag,
7841                                 const char *startSpecifier,
7842                                 unsigned specifierLen) {
7843   // Warn about ignored flag with a fixit removal.
7844   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7845                          << ignoredFlag.toString() << flag.toString(),
7846                        getLocationOfByte(ignoredFlag.getPosition()),
7847                        /*IsStringLocation*/true,
7848                        getSpecifierRange(startSpecifier, specifierLen),
7849                        FixItHint::CreateRemoval(
7850                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7851 }
7852 
7853 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7854                                                      unsigned flagLen) {
7855   // Warn about an empty flag.
7856   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7857                        getLocationOfByte(startFlag),
7858                        /*IsStringLocation*/true,
7859                        getSpecifierRange(startFlag, flagLen));
7860 }
7861 
7862 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7863                                                        unsigned flagLen) {
7864   // Warn about an invalid flag.
7865   auto Range = getSpecifierRange(startFlag, flagLen);
7866   StringRef flag(startFlag, flagLen);
7867   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7868                       getLocationOfByte(startFlag),
7869                       /*IsStringLocation*/true,
7870                       Range, FixItHint::CreateRemoval(Range));
7871 }
7872 
7873 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7874     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7875     // Warn about using '[...]' without a '@' conversion.
7876     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7877     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7878     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7879                          getLocationOfByte(conversionPosition),
7880                          /*IsStringLocation*/true,
7881                          Range, FixItHint::CreateRemoval(Range));
7882 }
7883 
7884 // Determines if the specified is a C++ class or struct containing
7885 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7886 // "c_str()").
7887 template<typename MemberKind>
7888 static llvm::SmallPtrSet<MemberKind*, 1>
7889 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7890   const RecordType *RT = Ty->getAs<RecordType>();
7891   llvm::SmallPtrSet<MemberKind*, 1> Results;
7892 
7893   if (!RT)
7894     return Results;
7895   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7896   if (!RD || !RD->getDefinition())
7897     return Results;
7898 
7899   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7900                  Sema::LookupMemberName);
7901   R.suppressDiagnostics();
7902 
7903   // We just need to include all members of the right kind turned up by the
7904   // filter, at this point.
7905   if (S.LookupQualifiedName(R, RT->getDecl()))
7906     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7907       NamedDecl *decl = (*I)->getUnderlyingDecl();
7908       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7909         Results.insert(FK);
7910     }
7911   return Results;
7912 }
7913 
7914 /// Check if we could call '.c_str()' on an object.
7915 ///
7916 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7917 /// allow the call, or if it would be ambiguous).
7918 bool Sema::hasCStrMethod(const Expr *E) {
7919   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7920 
7921   MethodSet Results =
7922       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7923   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7924        MI != ME; ++MI)
7925     if ((*MI)->getMinRequiredArguments() == 0)
7926       return true;
7927   return false;
7928 }
7929 
7930 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7931 // better diagnostic if so. AT is assumed to be valid.
7932 // Returns true when a c_str() conversion method is found.
7933 bool CheckPrintfHandler::checkForCStrMembers(
7934     const analyze_printf::ArgType &AT, const Expr *E) {
7935   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7936 
7937   MethodSet Results =
7938       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7939 
7940   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7941        MI != ME; ++MI) {
7942     const CXXMethodDecl *Method = *MI;
7943     if (Method->getMinRequiredArguments() == 0 &&
7944         AT.matchesType(S.Context, Method->getReturnType())) {
7945       // FIXME: Suggest parens if the expression needs them.
7946       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7947       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7948           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7949       return true;
7950     }
7951   }
7952 
7953   return false;
7954 }
7955 
7956 bool
7957 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7958                                             &FS,
7959                                           const char *startSpecifier,
7960                                           unsigned specifierLen) {
7961   using namespace analyze_format_string;
7962   using namespace analyze_printf;
7963 
7964   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7965 
7966   if (FS.consumesDataArgument()) {
7967     if (atFirstArg) {
7968         atFirstArg = false;
7969         usesPositionalArgs = FS.usesPositionalArg();
7970     }
7971     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7972       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7973                                         startSpecifier, specifierLen);
7974       return false;
7975     }
7976   }
7977 
7978   // First check if the field width, precision, and conversion specifier
7979   // have matching data arguments.
7980   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7981                     startSpecifier, specifierLen)) {
7982     return false;
7983   }
7984 
7985   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7986                     startSpecifier, specifierLen)) {
7987     return false;
7988   }
7989 
7990   if (!CS.consumesDataArgument()) {
7991     // FIXME: Technically specifying a precision or field width here
7992     // makes no sense.  Worth issuing a warning at some point.
7993     return true;
7994   }
7995 
7996   // Consume the argument.
7997   unsigned argIndex = FS.getArgIndex();
7998   if (argIndex < NumDataArgs) {
7999     // The check to see if the argIndex is valid will come later.
8000     // We set the bit here because we may exit early from this
8001     // function if we encounter some other error.
8002     CoveredArgs.set(argIndex);
8003   }
8004 
8005   // FreeBSD kernel extensions.
8006   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8007       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8008     // We need at least two arguments.
8009     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8010       return false;
8011 
8012     // Claim the second argument.
8013     CoveredArgs.set(argIndex + 1);
8014 
8015     // Type check the first argument (int for %b, pointer for %D)
8016     const Expr *Ex = getDataArg(argIndex);
8017     const analyze_printf::ArgType &AT =
8018       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8019         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8020     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8021       EmitFormatDiagnostic(
8022           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8023               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8024               << false << Ex->getSourceRange(),
8025           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8026           getSpecifierRange(startSpecifier, specifierLen));
8027 
8028     // Type check the second argument (char * for both %b and %D)
8029     Ex = getDataArg(argIndex + 1);
8030     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8031     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8032       EmitFormatDiagnostic(
8033           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8034               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8035               << false << Ex->getSourceRange(),
8036           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8037           getSpecifierRange(startSpecifier, specifierLen));
8038 
8039      return true;
8040   }
8041 
8042   // Check for using an Objective-C specific conversion specifier
8043   // in a non-ObjC literal.
8044   if (!allowsObjCArg() && CS.isObjCArg()) {
8045     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8046                                                   specifierLen);
8047   }
8048 
8049   // %P can only be used with os_log.
8050   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8051     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8052                                                   specifierLen);
8053   }
8054 
8055   // %n is not allowed with os_log.
8056   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8057     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8058                          getLocationOfByte(CS.getStart()),
8059                          /*IsStringLocation*/ false,
8060                          getSpecifierRange(startSpecifier, specifierLen));
8061 
8062     return true;
8063   }
8064 
8065   // Only scalars are allowed for os_trace.
8066   if (FSType == Sema::FST_OSTrace &&
8067       (CS.getKind() == ConversionSpecifier::PArg ||
8068        CS.getKind() == ConversionSpecifier::sArg ||
8069        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8070     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8071                                                   specifierLen);
8072   }
8073 
8074   // Check for use of public/private annotation outside of os_log().
8075   if (FSType != Sema::FST_OSLog) {
8076     if (FS.isPublic().isSet()) {
8077       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8078                                << "public",
8079                            getLocationOfByte(FS.isPublic().getPosition()),
8080                            /*IsStringLocation*/ false,
8081                            getSpecifierRange(startSpecifier, specifierLen));
8082     }
8083     if (FS.isPrivate().isSet()) {
8084       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8085                                << "private",
8086                            getLocationOfByte(FS.isPrivate().getPosition()),
8087                            /*IsStringLocation*/ false,
8088                            getSpecifierRange(startSpecifier, specifierLen));
8089     }
8090   }
8091 
8092   // Check for invalid use of field width
8093   if (!FS.hasValidFieldWidth()) {
8094     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8095         startSpecifier, specifierLen);
8096   }
8097 
8098   // Check for invalid use of precision
8099   if (!FS.hasValidPrecision()) {
8100     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8101         startSpecifier, specifierLen);
8102   }
8103 
8104   // Precision is mandatory for %P specifier.
8105   if (CS.getKind() == ConversionSpecifier::PArg &&
8106       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8107     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8108                          getLocationOfByte(startSpecifier),
8109                          /*IsStringLocation*/ false,
8110                          getSpecifierRange(startSpecifier, specifierLen));
8111   }
8112 
8113   // Check each flag does not conflict with any other component.
8114   if (!FS.hasValidThousandsGroupingPrefix())
8115     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8116   if (!FS.hasValidLeadingZeros())
8117     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8118   if (!FS.hasValidPlusPrefix())
8119     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8120   if (!FS.hasValidSpacePrefix())
8121     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8122   if (!FS.hasValidAlternativeForm())
8123     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8124   if (!FS.hasValidLeftJustified())
8125     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8126 
8127   // Check that flags are not ignored by another flag
8128   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8129     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8130         startSpecifier, specifierLen);
8131   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8132     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8133             startSpecifier, specifierLen);
8134 
8135   // Check the length modifier is valid with the given conversion specifier.
8136   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8137                                  S.getLangOpts()))
8138     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8139                                 diag::warn_format_nonsensical_length);
8140   else if (!FS.hasStandardLengthModifier())
8141     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8142   else if (!FS.hasStandardLengthConversionCombination())
8143     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8144                                 diag::warn_format_non_standard_conversion_spec);
8145 
8146   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8147     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8148 
8149   // The remaining checks depend on the data arguments.
8150   if (HasVAListArg)
8151     return true;
8152 
8153   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8154     return false;
8155 
8156   const Expr *Arg = getDataArg(argIndex);
8157   if (!Arg)
8158     return true;
8159 
8160   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8161 }
8162 
8163 static bool requiresParensToAddCast(const Expr *E) {
8164   // FIXME: We should have a general way to reason about operator
8165   // precedence and whether parens are actually needed here.
8166   // Take care of a few common cases where they aren't.
8167   const Expr *Inside = E->IgnoreImpCasts();
8168   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8169     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8170 
8171   switch (Inside->getStmtClass()) {
8172   case Stmt::ArraySubscriptExprClass:
8173   case Stmt::CallExprClass:
8174   case Stmt::CharacterLiteralClass:
8175   case Stmt::CXXBoolLiteralExprClass:
8176   case Stmt::DeclRefExprClass:
8177   case Stmt::FloatingLiteralClass:
8178   case Stmt::IntegerLiteralClass:
8179   case Stmt::MemberExprClass:
8180   case Stmt::ObjCArrayLiteralClass:
8181   case Stmt::ObjCBoolLiteralExprClass:
8182   case Stmt::ObjCBoxedExprClass:
8183   case Stmt::ObjCDictionaryLiteralClass:
8184   case Stmt::ObjCEncodeExprClass:
8185   case Stmt::ObjCIvarRefExprClass:
8186   case Stmt::ObjCMessageExprClass:
8187   case Stmt::ObjCPropertyRefExprClass:
8188   case Stmt::ObjCStringLiteralClass:
8189   case Stmt::ObjCSubscriptRefExprClass:
8190   case Stmt::ParenExprClass:
8191   case Stmt::StringLiteralClass:
8192   case Stmt::UnaryOperatorClass:
8193     return false;
8194   default:
8195     return true;
8196   }
8197 }
8198 
8199 static std::pair<QualType, StringRef>
8200 shouldNotPrintDirectly(const ASTContext &Context,
8201                        QualType IntendedTy,
8202                        const Expr *E) {
8203   // Use a 'while' to peel off layers of typedefs.
8204   QualType TyTy = IntendedTy;
8205   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8206     StringRef Name = UserTy->getDecl()->getName();
8207     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8208       .Case("CFIndex", Context.getNSIntegerType())
8209       .Case("NSInteger", Context.getNSIntegerType())
8210       .Case("NSUInteger", Context.getNSUIntegerType())
8211       .Case("SInt32", Context.IntTy)
8212       .Case("UInt32", Context.UnsignedIntTy)
8213       .Default(QualType());
8214 
8215     if (!CastTy.isNull())
8216       return std::make_pair(CastTy, Name);
8217 
8218     TyTy = UserTy->desugar();
8219   }
8220 
8221   // Strip parens if necessary.
8222   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8223     return shouldNotPrintDirectly(Context,
8224                                   PE->getSubExpr()->getType(),
8225                                   PE->getSubExpr());
8226 
8227   // If this is a conditional expression, then its result type is constructed
8228   // via usual arithmetic conversions and thus there might be no necessary
8229   // typedef sugar there.  Recurse to operands to check for NSInteger &
8230   // Co. usage condition.
8231   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8232     QualType TrueTy, FalseTy;
8233     StringRef TrueName, FalseName;
8234 
8235     std::tie(TrueTy, TrueName) =
8236       shouldNotPrintDirectly(Context,
8237                              CO->getTrueExpr()->getType(),
8238                              CO->getTrueExpr());
8239     std::tie(FalseTy, FalseName) =
8240       shouldNotPrintDirectly(Context,
8241                              CO->getFalseExpr()->getType(),
8242                              CO->getFalseExpr());
8243 
8244     if (TrueTy == FalseTy)
8245       return std::make_pair(TrueTy, TrueName);
8246     else if (TrueTy.isNull())
8247       return std::make_pair(FalseTy, FalseName);
8248     else if (FalseTy.isNull())
8249       return std::make_pair(TrueTy, TrueName);
8250   }
8251 
8252   return std::make_pair(QualType(), StringRef());
8253 }
8254 
8255 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8256 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8257 /// type do not count.
8258 static bool
8259 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8260   QualType From = ICE->getSubExpr()->getType();
8261   QualType To = ICE->getType();
8262   // It's an integer promotion if the destination type is the promoted
8263   // source type.
8264   if (ICE->getCastKind() == CK_IntegralCast &&
8265       From->isPromotableIntegerType() &&
8266       S.Context.getPromotedIntegerType(From) == To)
8267     return true;
8268   // Look through vector types, since we do default argument promotion for
8269   // those in OpenCL.
8270   if (const auto *VecTy = From->getAs<ExtVectorType>())
8271     From = VecTy->getElementType();
8272   if (const auto *VecTy = To->getAs<ExtVectorType>())
8273     To = VecTy->getElementType();
8274   // It's a floating promotion if the source type is a lower rank.
8275   return ICE->getCastKind() == CK_FloatingCast &&
8276          S.Context.getFloatingTypeOrder(From, To) < 0;
8277 }
8278 
8279 bool
8280 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8281                                     const char *StartSpecifier,
8282                                     unsigned SpecifierLen,
8283                                     const Expr *E) {
8284   using namespace analyze_format_string;
8285   using namespace analyze_printf;
8286 
8287   // Now type check the data expression that matches the
8288   // format specifier.
8289   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8290   if (!AT.isValid())
8291     return true;
8292 
8293   QualType ExprTy = E->getType();
8294   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8295     ExprTy = TET->getUnderlyingExpr()->getType();
8296   }
8297 
8298   // Diagnose attempts to print a boolean value as a character. Unlike other
8299   // -Wformat diagnostics, this is fine from a type perspective, but it still
8300   // doesn't make sense.
8301   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8302       E->isKnownToHaveBooleanValue()) {
8303     const CharSourceRange &CSR =
8304         getSpecifierRange(StartSpecifier, SpecifierLen);
8305     SmallString<4> FSString;
8306     llvm::raw_svector_ostream os(FSString);
8307     FS.toString(os);
8308     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8309                              << FSString,
8310                          E->getExprLoc(), false, CSR);
8311     return true;
8312   }
8313 
8314   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8315   if (Match == analyze_printf::ArgType::Match)
8316     return true;
8317 
8318   // Look through argument promotions for our error message's reported type.
8319   // This includes the integral and floating promotions, but excludes array
8320   // and function pointer decay (seeing that an argument intended to be a
8321   // string has type 'char [6]' is probably more confusing than 'char *') and
8322   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8323   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8324     if (isArithmeticArgumentPromotion(S, ICE)) {
8325       E = ICE->getSubExpr();
8326       ExprTy = E->getType();
8327 
8328       // Check if we didn't match because of an implicit cast from a 'char'
8329       // or 'short' to an 'int'.  This is done because printf is a varargs
8330       // function.
8331       if (ICE->getType() == S.Context.IntTy ||
8332           ICE->getType() == S.Context.UnsignedIntTy) {
8333         // All further checking is done on the subexpression
8334         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8335             AT.matchesType(S.Context, ExprTy);
8336         if (ImplicitMatch == analyze_printf::ArgType::Match)
8337           return true;
8338         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8339             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8340           Match = ImplicitMatch;
8341       }
8342     }
8343   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8344     // Special case for 'a', which has type 'int' in C.
8345     // Note, however, that we do /not/ want to treat multibyte constants like
8346     // 'MooV' as characters! This form is deprecated but still exists.
8347     if (ExprTy == S.Context.IntTy)
8348       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8349         ExprTy = S.Context.CharTy;
8350   }
8351 
8352   // Look through enums to their underlying type.
8353   bool IsEnum = false;
8354   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8355     ExprTy = EnumTy->getDecl()->getIntegerType();
8356     IsEnum = true;
8357   }
8358 
8359   // %C in an Objective-C context prints a unichar, not a wchar_t.
8360   // If the argument is an integer of some kind, believe the %C and suggest
8361   // a cast instead of changing the conversion specifier.
8362   QualType IntendedTy = ExprTy;
8363   if (isObjCContext() &&
8364       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8365     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8366         !ExprTy->isCharType()) {
8367       // 'unichar' is defined as a typedef of unsigned short, but we should
8368       // prefer using the typedef if it is visible.
8369       IntendedTy = S.Context.UnsignedShortTy;
8370 
8371       // While we are here, check if the value is an IntegerLiteral that happens
8372       // to be within the valid range.
8373       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8374         const llvm::APInt &V = IL->getValue();
8375         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8376           return true;
8377       }
8378 
8379       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8380                           Sema::LookupOrdinaryName);
8381       if (S.LookupName(Result, S.getCurScope())) {
8382         NamedDecl *ND = Result.getFoundDecl();
8383         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8384           if (TD->getUnderlyingType() == IntendedTy)
8385             IntendedTy = S.Context.getTypedefType(TD);
8386       }
8387     }
8388   }
8389 
8390   // Special-case some of Darwin's platform-independence types by suggesting
8391   // casts to primitive types that are known to be large enough.
8392   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8393   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8394     QualType CastTy;
8395     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8396     if (!CastTy.isNull()) {
8397       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8398       // (long in ASTContext). Only complain to pedants.
8399       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8400           (AT.isSizeT() || AT.isPtrdiffT()) &&
8401           AT.matchesType(S.Context, CastTy))
8402         Match = ArgType::NoMatchPedantic;
8403       IntendedTy = CastTy;
8404       ShouldNotPrintDirectly = true;
8405     }
8406   }
8407 
8408   // We may be able to offer a FixItHint if it is a supported type.
8409   PrintfSpecifier fixedFS = FS;
8410   bool Success =
8411       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8412 
8413   if (Success) {
8414     // Get the fix string from the fixed format specifier
8415     SmallString<16> buf;
8416     llvm::raw_svector_ostream os(buf);
8417     fixedFS.toString(os);
8418 
8419     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8420 
8421     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8422       unsigned Diag;
8423       switch (Match) {
8424       case ArgType::Match: llvm_unreachable("expected non-matching");
8425       case ArgType::NoMatchPedantic:
8426         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8427         break;
8428       case ArgType::NoMatchTypeConfusion:
8429         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8430         break;
8431       case ArgType::NoMatch:
8432         Diag = diag::warn_format_conversion_argument_type_mismatch;
8433         break;
8434       }
8435 
8436       // In this case, the specifier is wrong and should be changed to match
8437       // the argument.
8438       EmitFormatDiagnostic(S.PDiag(Diag)
8439                                << AT.getRepresentativeTypeName(S.Context)
8440                                << IntendedTy << IsEnum << E->getSourceRange(),
8441                            E->getBeginLoc(),
8442                            /*IsStringLocation*/ false, SpecRange,
8443                            FixItHint::CreateReplacement(SpecRange, os.str()));
8444     } else {
8445       // The canonical type for formatting this value is different from the
8446       // actual type of the expression. (This occurs, for example, with Darwin's
8447       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8448       // should be printed as 'long' for 64-bit compatibility.)
8449       // Rather than emitting a normal format/argument mismatch, we want to
8450       // add a cast to the recommended type (and correct the format string
8451       // if necessary).
8452       SmallString<16> CastBuf;
8453       llvm::raw_svector_ostream CastFix(CastBuf);
8454       CastFix << "(";
8455       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8456       CastFix << ")";
8457 
8458       SmallVector<FixItHint,4> Hints;
8459       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8460         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8461 
8462       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8463         // If there's already a cast present, just replace it.
8464         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8465         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8466 
8467       } else if (!requiresParensToAddCast(E)) {
8468         // If the expression has high enough precedence,
8469         // just write the C-style cast.
8470         Hints.push_back(
8471             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8472       } else {
8473         // Otherwise, add parens around the expression as well as the cast.
8474         CastFix << "(";
8475         Hints.push_back(
8476             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8477 
8478         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8479         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8480       }
8481 
8482       if (ShouldNotPrintDirectly) {
8483         // The expression has a type that should not be printed directly.
8484         // We extract the name from the typedef because we don't want to show
8485         // the underlying type in the diagnostic.
8486         StringRef Name;
8487         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8488           Name = TypedefTy->getDecl()->getName();
8489         else
8490           Name = CastTyName;
8491         unsigned Diag = Match == ArgType::NoMatchPedantic
8492                             ? diag::warn_format_argument_needs_cast_pedantic
8493                             : diag::warn_format_argument_needs_cast;
8494         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8495                                            << E->getSourceRange(),
8496                              E->getBeginLoc(), /*IsStringLocation=*/false,
8497                              SpecRange, Hints);
8498       } else {
8499         // In this case, the expression could be printed using a different
8500         // specifier, but we've decided that the specifier is probably correct
8501         // and we should cast instead. Just use the normal warning message.
8502         EmitFormatDiagnostic(
8503             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8504                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8505                 << E->getSourceRange(),
8506             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8507       }
8508     }
8509   } else {
8510     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8511                                                    SpecifierLen);
8512     // Since the warning for passing non-POD types to variadic functions
8513     // was deferred until now, we emit a warning for non-POD
8514     // arguments here.
8515     switch (S.isValidVarArgType(ExprTy)) {
8516     case Sema::VAK_Valid:
8517     case Sema::VAK_ValidInCXX11: {
8518       unsigned Diag;
8519       switch (Match) {
8520       case ArgType::Match: llvm_unreachable("expected non-matching");
8521       case ArgType::NoMatchPedantic:
8522         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8523         break;
8524       case ArgType::NoMatchTypeConfusion:
8525         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8526         break;
8527       case ArgType::NoMatch:
8528         Diag = diag::warn_format_conversion_argument_type_mismatch;
8529         break;
8530       }
8531 
8532       EmitFormatDiagnostic(
8533           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8534                         << IsEnum << CSR << E->getSourceRange(),
8535           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8536       break;
8537     }
8538     case Sema::VAK_Undefined:
8539     case Sema::VAK_MSVCUndefined:
8540       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8541                                << S.getLangOpts().CPlusPlus11 << ExprTy
8542                                << CallType
8543                                << AT.getRepresentativeTypeName(S.Context) << CSR
8544                                << E->getSourceRange(),
8545                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8546       checkForCStrMembers(AT, E);
8547       break;
8548 
8549     case Sema::VAK_Invalid:
8550       if (ExprTy->isObjCObjectType())
8551         EmitFormatDiagnostic(
8552             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8553                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8554                 << AT.getRepresentativeTypeName(S.Context) << CSR
8555                 << E->getSourceRange(),
8556             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8557       else
8558         // FIXME: If this is an initializer list, suggest removing the braces
8559         // or inserting a cast to the target type.
8560         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8561             << isa<InitListExpr>(E) << ExprTy << CallType
8562             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8563       break;
8564     }
8565 
8566     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8567            "format string specifier index out of range");
8568     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8569   }
8570 
8571   return true;
8572 }
8573 
8574 //===--- CHECK: Scanf format string checking ------------------------------===//
8575 
8576 namespace {
8577 
8578 class CheckScanfHandler : public CheckFormatHandler {
8579 public:
8580   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8581                     const Expr *origFormatExpr, Sema::FormatStringType type,
8582                     unsigned firstDataArg, unsigned numDataArgs,
8583                     const char *beg, bool hasVAListArg,
8584                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8585                     bool inFunctionCall, Sema::VariadicCallType CallType,
8586                     llvm::SmallBitVector &CheckedVarArgs,
8587                     UncoveredArgHandler &UncoveredArg)
8588       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8589                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8590                            inFunctionCall, CallType, CheckedVarArgs,
8591                            UncoveredArg) {}
8592 
8593   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8594                             const char *startSpecifier,
8595                             unsigned specifierLen) override;
8596 
8597   bool HandleInvalidScanfConversionSpecifier(
8598           const analyze_scanf::ScanfSpecifier &FS,
8599           const char *startSpecifier,
8600           unsigned specifierLen) override;
8601 
8602   void HandleIncompleteScanList(const char *start, const char *end) override;
8603 };
8604 
8605 } // namespace
8606 
8607 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8608                                                  const char *end) {
8609   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8610                        getLocationOfByte(end), /*IsStringLocation*/true,
8611                        getSpecifierRange(start, end - start));
8612 }
8613 
8614 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8615                                         const analyze_scanf::ScanfSpecifier &FS,
8616                                         const char *startSpecifier,
8617                                         unsigned specifierLen) {
8618   const analyze_scanf::ScanfConversionSpecifier &CS =
8619     FS.getConversionSpecifier();
8620 
8621   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8622                                           getLocationOfByte(CS.getStart()),
8623                                           startSpecifier, specifierLen,
8624                                           CS.getStart(), CS.getLength());
8625 }
8626 
8627 bool CheckScanfHandler::HandleScanfSpecifier(
8628                                        const analyze_scanf::ScanfSpecifier &FS,
8629                                        const char *startSpecifier,
8630                                        unsigned specifierLen) {
8631   using namespace analyze_scanf;
8632   using namespace analyze_format_string;
8633 
8634   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8635 
8636   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8637   // be used to decide if we are using positional arguments consistently.
8638   if (FS.consumesDataArgument()) {
8639     if (atFirstArg) {
8640       atFirstArg = false;
8641       usesPositionalArgs = FS.usesPositionalArg();
8642     }
8643     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8644       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8645                                         startSpecifier, specifierLen);
8646       return false;
8647     }
8648   }
8649 
8650   // Check if the field with is non-zero.
8651   const OptionalAmount &Amt = FS.getFieldWidth();
8652   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8653     if (Amt.getConstantAmount() == 0) {
8654       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8655                                                    Amt.getConstantLength());
8656       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8657                            getLocationOfByte(Amt.getStart()),
8658                            /*IsStringLocation*/true, R,
8659                            FixItHint::CreateRemoval(R));
8660     }
8661   }
8662 
8663   if (!FS.consumesDataArgument()) {
8664     // FIXME: Technically specifying a precision or field width here
8665     // makes no sense.  Worth issuing a warning at some point.
8666     return true;
8667   }
8668 
8669   // Consume the argument.
8670   unsigned argIndex = FS.getArgIndex();
8671   if (argIndex < NumDataArgs) {
8672       // The check to see if the argIndex is valid will come later.
8673       // We set the bit here because we may exit early from this
8674       // function if we encounter some other error.
8675     CoveredArgs.set(argIndex);
8676   }
8677 
8678   // Check the length modifier is valid with the given conversion specifier.
8679   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8680                                  S.getLangOpts()))
8681     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8682                                 diag::warn_format_nonsensical_length);
8683   else if (!FS.hasStandardLengthModifier())
8684     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8685   else if (!FS.hasStandardLengthConversionCombination())
8686     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8687                                 diag::warn_format_non_standard_conversion_spec);
8688 
8689   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8690     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8691 
8692   // The remaining checks depend on the data arguments.
8693   if (HasVAListArg)
8694     return true;
8695 
8696   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8697     return false;
8698 
8699   // Check that the argument type matches the format specifier.
8700   const Expr *Ex = getDataArg(argIndex);
8701   if (!Ex)
8702     return true;
8703 
8704   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8705 
8706   if (!AT.isValid()) {
8707     return true;
8708   }
8709 
8710   analyze_format_string::ArgType::MatchKind Match =
8711       AT.matchesType(S.Context, Ex->getType());
8712   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8713   if (Match == analyze_format_string::ArgType::Match)
8714     return true;
8715 
8716   ScanfSpecifier fixedFS = FS;
8717   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8718                                  S.getLangOpts(), S.Context);
8719 
8720   unsigned Diag =
8721       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8722                : diag::warn_format_conversion_argument_type_mismatch;
8723 
8724   if (Success) {
8725     // Get the fix string from the fixed format specifier.
8726     SmallString<128> buf;
8727     llvm::raw_svector_ostream os(buf);
8728     fixedFS.toString(os);
8729 
8730     EmitFormatDiagnostic(
8731         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8732                       << Ex->getType() << false << Ex->getSourceRange(),
8733         Ex->getBeginLoc(),
8734         /*IsStringLocation*/ false,
8735         getSpecifierRange(startSpecifier, specifierLen),
8736         FixItHint::CreateReplacement(
8737             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8738   } else {
8739     EmitFormatDiagnostic(S.PDiag(Diag)
8740                              << AT.getRepresentativeTypeName(S.Context)
8741                              << Ex->getType() << false << Ex->getSourceRange(),
8742                          Ex->getBeginLoc(),
8743                          /*IsStringLocation*/ false,
8744                          getSpecifierRange(startSpecifier, specifierLen));
8745   }
8746 
8747   return true;
8748 }
8749 
8750 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8751                               const Expr *OrigFormatExpr,
8752                               ArrayRef<const Expr *> Args,
8753                               bool HasVAListArg, unsigned format_idx,
8754                               unsigned firstDataArg,
8755                               Sema::FormatStringType Type,
8756                               bool inFunctionCall,
8757                               Sema::VariadicCallType CallType,
8758                               llvm::SmallBitVector &CheckedVarArgs,
8759                               UncoveredArgHandler &UncoveredArg,
8760                               bool IgnoreStringsWithoutSpecifiers) {
8761   // CHECK: is the format string a wide literal?
8762   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8763     CheckFormatHandler::EmitFormatDiagnostic(
8764         S, inFunctionCall, Args[format_idx],
8765         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8766         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8767     return;
8768   }
8769 
8770   // Str - The format string.  NOTE: this is NOT null-terminated!
8771   StringRef StrRef = FExpr->getString();
8772   const char *Str = StrRef.data();
8773   // Account for cases where the string literal is truncated in a declaration.
8774   const ConstantArrayType *T =
8775     S.Context.getAsConstantArrayType(FExpr->getType());
8776   assert(T && "String literal not of constant array type!");
8777   size_t TypeSize = T->getSize().getZExtValue();
8778   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8779   const unsigned numDataArgs = Args.size() - firstDataArg;
8780 
8781   if (IgnoreStringsWithoutSpecifiers &&
8782       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8783           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8784     return;
8785 
8786   // Emit a warning if the string literal is truncated and does not contain an
8787   // embedded null character.
8788   if (TypeSize <= StrRef.size() &&
8789       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8790     CheckFormatHandler::EmitFormatDiagnostic(
8791         S, inFunctionCall, Args[format_idx],
8792         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8793         FExpr->getBeginLoc(),
8794         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8795     return;
8796   }
8797 
8798   // CHECK: empty format string?
8799   if (StrLen == 0 && numDataArgs > 0) {
8800     CheckFormatHandler::EmitFormatDiagnostic(
8801         S, inFunctionCall, Args[format_idx],
8802         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8803         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8804     return;
8805   }
8806 
8807   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8808       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8809       Type == Sema::FST_OSTrace) {
8810     CheckPrintfHandler H(
8811         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8812         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8813         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8814         CheckedVarArgs, UncoveredArg);
8815 
8816     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8817                                                   S.getLangOpts(),
8818                                                   S.Context.getTargetInfo(),
8819                                             Type == Sema::FST_FreeBSDKPrintf))
8820       H.DoneProcessing();
8821   } else if (Type == Sema::FST_Scanf) {
8822     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8823                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8824                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8825 
8826     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8827                                                  S.getLangOpts(),
8828                                                  S.Context.getTargetInfo()))
8829       H.DoneProcessing();
8830   } // TODO: handle other formats
8831 }
8832 
8833 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8834   // Str - The format string.  NOTE: this is NOT null-terminated!
8835   StringRef StrRef = FExpr->getString();
8836   const char *Str = StrRef.data();
8837   // Account for cases where the string literal is truncated in a declaration.
8838   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8839   assert(T && "String literal not of constant array type!");
8840   size_t TypeSize = T->getSize().getZExtValue();
8841   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8842   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8843                                                          getLangOpts(),
8844                                                          Context.getTargetInfo());
8845 }
8846 
8847 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8848 
8849 // Returns the related absolute value function that is larger, of 0 if one
8850 // does not exist.
8851 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8852   switch (AbsFunction) {
8853   default:
8854     return 0;
8855 
8856   case Builtin::BI__builtin_abs:
8857     return Builtin::BI__builtin_labs;
8858   case Builtin::BI__builtin_labs:
8859     return Builtin::BI__builtin_llabs;
8860   case Builtin::BI__builtin_llabs:
8861     return 0;
8862 
8863   case Builtin::BI__builtin_fabsf:
8864     return Builtin::BI__builtin_fabs;
8865   case Builtin::BI__builtin_fabs:
8866     return Builtin::BI__builtin_fabsl;
8867   case Builtin::BI__builtin_fabsl:
8868     return 0;
8869 
8870   case Builtin::BI__builtin_cabsf:
8871     return Builtin::BI__builtin_cabs;
8872   case Builtin::BI__builtin_cabs:
8873     return Builtin::BI__builtin_cabsl;
8874   case Builtin::BI__builtin_cabsl:
8875     return 0;
8876 
8877   case Builtin::BIabs:
8878     return Builtin::BIlabs;
8879   case Builtin::BIlabs:
8880     return Builtin::BIllabs;
8881   case Builtin::BIllabs:
8882     return 0;
8883 
8884   case Builtin::BIfabsf:
8885     return Builtin::BIfabs;
8886   case Builtin::BIfabs:
8887     return Builtin::BIfabsl;
8888   case Builtin::BIfabsl:
8889     return 0;
8890 
8891   case Builtin::BIcabsf:
8892    return Builtin::BIcabs;
8893   case Builtin::BIcabs:
8894     return Builtin::BIcabsl;
8895   case Builtin::BIcabsl:
8896     return 0;
8897   }
8898 }
8899 
8900 // Returns the argument type of the absolute value function.
8901 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8902                                              unsigned AbsType) {
8903   if (AbsType == 0)
8904     return QualType();
8905 
8906   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8907   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8908   if (Error != ASTContext::GE_None)
8909     return QualType();
8910 
8911   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8912   if (!FT)
8913     return QualType();
8914 
8915   if (FT->getNumParams() != 1)
8916     return QualType();
8917 
8918   return FT->getParamType(0);
8919 }
8920 
8921 // Returns the best absolute value function, or zero, based on type and
8922 // current absolute value function.
8923 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8924                                    unsigned AbsFunctionKind) {
8925   unsigned BestKind = 0;
8926   uint64_t ArgSize = Context.getTypeSize(ArgType);
8927   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8928        Kind = getLargerAbsoluteValueFunction(Kind)) {
8929     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8930     if (Context.getTypeSize(ParamType) >= ArgSize) {
8931       if (BestKind == 0)
8932         BestKind = Kind;
8933       else if (Context.hasSameType(ParamType, ArgType)) {
8934         BestKind = Kind;
8935         break;
8936       }
8937     }
8938   }
8939   return BestKind;
8940 }
8941 
8942 enum AbsoluteValueKind {
8943   AVK_Integer,
8944   AVK_Floating,
8945   AVK_Complex
8946 };
8947 
8948 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8949   if (T->isIntegralOrEnumerationType())
8950     return AVK_Integer;
8951   if (T->isRealFloatingType())
8952     return AVK_Floating;
8953   if (T->isAnyComplexType())
8954     return AVK_Complex;
8955 
8956   llvm_unreachable("Type not integer, floating, or complex");
8957 }
8958 
8959 // Changes the absolute value function to a different type.  Preserves whether
8960 // the function is a builtin.
8961 static unsigned changeAbsFunction(unsigned AbsKind,
8962                                   AbsoluteValueKind ValueKind) {
8963   switch (ValueKind) {
8964   case AVK_Integer:
8965     switch (AbsKind) {
8966     default:
8967       return 0;
8968     case Builtin::BI__builtin_fabsf:
8969     case Builtin::BI__builtin_fabs:
8970     case Builtin::BI__builtin_fabsl:
8971     case Builtin::BI__builtin_cabsf:
8972     case Builtin::BI__builtin_cabs:
8973     case Builtin::BI__builtin_cabsl:
8974       return Builtin::BI__builtin_abs;
8975     case Builtin::BIfabsf:
8976     case Builtin::BIfabs:
8977     case Builtin::BIfabsl:
8978     case Builtin::BIcabsf:
8979     case Builtin::BIcabs:
8980     case Builtin::BIcabsl:
8981       return Builtin::BIabs;
8982     }
8983   case AVK_Floating:
8984     switch (AbsKind) {
8985     default:
8986       return 0;
8987     case Builtin::BI__builtin_abs:
8988     case Builtin::BI__builtin_labs:
8989     case Builtin::BI__builtin_llabs:
8990     case Builtin::BI__builtin_cabsf:
8991     case Builtin::BI__builtin_cabs:
8992     case Builtin::BI__builtin_cabsl:
8993       return Builtin::BI__builtin_fabsf;
8994     case Builtin::BIabs:
8995     case Builtin::BIlabs:
8996     case Builtin::BIllabs:
8997     case Builtin::BIcabsf:
8998     case Builtin::BIcabs:
8999     case Builtin::BIcabsl:
9000       return Builtin::BIfabsf;
9001     }
9002   case AVK_Complex:
9003     switch (AbsKind) {
9004     default:
9005       return 0;
9006     case Builtin::BI__builtin_abs:
9007     case Builtin::BI__builtin_labs:
9008     case Builtin::BI__builtin_llabs:
9009     case Builtin::BI__builtin_fabsf:
9010     case Builtin::BI__builtin_fabs:
9011     case Builtin::BI__builtin_fabsl:
9012       return Builtin::BI__builtin_cabsf;
9013     case Builtin::BIabs:
9014     case Builtin::BIlabs:
9015     case Builtin::BIllabs:
9016     case Builtin::BIfabsf:
9017     case Builtin::BIfabs:
9018     case Builtin::BIfabsl:
9019       return Builtin::BIcabsf;
9020     }
9021   }
9022   llvm_unreachable("Unable to convert function");
9023 }
9024 
9025 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9026   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9027   if (!FnInfo)
9028     return 0;
9029 
9030   switch (FDecl->getBuiltinID()) {
9031   default:
9032     return 0;
9033   case Builtin::BI__builtin_abs:
9034   case Builtin::BI__builtin_fabs:
9035   case Builtin::BI__builtin_fabsf:
9036   case Builtin::BI__builtin_fabsl:
9037   case Builtin::BI__builtin_labs:
9038   case Builtin::BI__builtin_llabs:
9039   case Builtin::BI__builtin_cabs:
9040   case Builtin::BI__builtin_cabsf:
9041   case Builtin::BI__builtin_cabsl:
9042   case Builtin::BIabs:
9043   case Builtin::BIlabs:
9044   case Builtin::BIllabs:
9045   case Builtin::BIfabs:
9046   case Builtin::BIfabsf:
9047   case Builtin::BIfabsl:
9048   case Builtin::BIcabs:
9049   case Builtin::BIcabsf:
9050   case Builtin::BIcabsl:
9051     return FDecl->getBuiltinID();
9052   }
9053   llvm_unreachable("Unknown Builtin type");
9054 }
9055 
9056 // If the replacement is valid, emit a note with replacement function.
9057 // Additionally, suggest including the proper header if not already included.
9058 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9059                             unsigned AbsKind, QualType ArgType) {
9060   bool EmitHeaderHint = true;
9061   const char *HeaderName = nullptr;
9062   const char *FunctionName = nullptr;
9063   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9064     FunctionName = "std::abs";
9065     if (ArgType->isIntegralOrEnumerationType()) {
9066       HeaderName = "cstdlib";
9067     } else if (ArgType->isRealFloatingType()) {
9068       HeaderName = "cmath";
9069     } else {
9070       llvm_unreachable("Invalid Type");
9071     }
9072 
9073     // Lookup all std::abs
9074     if (NamespaceDecl *Std = S.getStdNamespace()) {
9075       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9076       R.suppressDiagnostics();
9077       S.LookupQualifiedName(R, Std);
9078 
9079       for (const auto *I : R) {
9080         const FunctionDecl *FDecl = nullptr;
9081         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9082           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9083         } else {
9084           FDecl = dyn_cast<FunctionDecl>(I);
9085         }
9086         if (!FDecl)
9087           continue;
9088 
9089         // Found std::abs(), check that they are the right ones.
9090         if (FDecl->getNumParams() != 1)
9091           continue;
9092 
9093         // Check that the parameter type can handle the argument.
9094         QualType ParamType = FDecl->getParamDecl(0)->getType();
9095         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9096             S.Context.getTypeSize(ArgType) <=
9097                 S.Context.getTypeSize(ParamType)) {
9098           // Found a function, don't need the header hint.
9099           EmitHeaderHint = false;
9100           break;
9101         }
9102       }
9103     }
9104   } else {
9105     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9106     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9107 
9108     if (HeaderName) {
9109       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9110       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9111       R.suppressDiagnostics();
9112       S.LookupName(R, S.getCurScope());
9113 
9114       if (R.isSingleResult()) {
9115         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9116         if (FD && FD->getBuiltinID() == AbsKind) {
9117           EmitHeaderHint = false;
9118         } else {
9119           return;
9120         }
9121       } else if (!R.empty()) {
9122         return;
9123       }
9124     }
9125   }
9126 
9127   S.Diag(Loc, diag::note_replace_abs_function)
9128       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9129 
9130   if (!HeaderName)
9131     return;
9132 
9133   if (!EmitHeaderHint)
9134     return;
9135 
9136   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9137                                                     << FunctionName;
9138 }
9139 
9140 template <std::size_t StrLen>
9141 static bool IsStdFunction(const FunctionDecl *FDecl,
9142                           const char (&Str)[StrLen]) {
9143   if (!FDecl)
9144     return false;
9145   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9146     return false;
9147   if (!FDecl->isInStdNamespace())
9148     return false;
9149 
9150   return true;
9151 }
9152 
9153 // Warn when using the wrong abs() function.
9154 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9155                                       const FunctionDecl *FDecl) {
9156   if (Call->getNumArgs() != 1)
9157     return;
9158 
9159   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9160   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9161   if (AbsKind == 0 && !IsStdAbs)
9162     return;
9163 
9164   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9165   QualType ParamType = Call->getArg(0)->getType();
9166 
9167   // Unsigned types cannot be negative.  Suggest removing the absolute value
9168   // function call.
9169   if (ArgType->isUnsignedIntegerType()) {
9170     const char *FunctionName =
9171         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9172     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9173     Diag(Call->getExprLoc(), diag::note_remove_abs)
9174         << FunctionName
9175         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9176     return;
9177   }
9178 
9179   // Taking the absolute value of a pointer is very suspicious, they probably
9180   // wanted to index into an array, dereference a pointer, call a function, etc.
9181   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9182     unsigned DiagType = 0;
9183     if (ArgType->isFunctionType())
9184       DiagType = 1;
9185     else if (ArgType->isArrayType())
9186       DiagType = 2;
9187 
9188     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9189     return;
9190   }
9191 
9192   // std::abs has overloads which prevent most of the absolute value problems
9193   // from occurring.
9194   if (IsStdAbs)
9195     return;
9196 
9197   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9198   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9199 
9200   // The argument and parameter are the same kind.  Check if they are the right
9201   // size.
9202   if (ArgValueKind == ParamValueKind) {
9203     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9204       return;
9205 
9206     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9207     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9208         << FDecl << ArgType << ParamType;
9209 
9210     if (NewAbsKind == 0)
9211       return;
9212 
9213     emitReplacement(*this, Call->getExprLoc(),
9214                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9215     return;
9216   }
9217 
9218   // ArgValueKind != ParamValueKind
9219   // The wrong type of absolute value function was used.  Attempt to find the
9220   // proper one.
9221   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9222   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9223   if (NewAbsKind == 0)
9224     return;
9225 
9226   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9227       << FDecl << ParamValueKind << ArgValueKind;
9228 
9229   emitReplacement(*this, Call->getExprLoc(),
9230                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9231 }
9232 
9233 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9234 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9235                                 const FunctionDecl *FDecl) {
9236   if (!Call || !FDecl) return;
9237 
9238   // Ignore template specializations and macros.
9239   if (inTemplateInstantiation()) return;
9240   if (Call->getExprLoc().isMacroID()) return;
9241 
9242   // Only care about the one template argument, two function parameter std::max
9243   if (Call->getNumArgs() != 2) return;
9244   if (!IsStdFunction(FDecl, "max")) return;
9245   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9246   if (!ArgList) return;
9247   if (ArgList->size() != 1) return;
9248 
9249   // Check that template type argument is unsigned integer.
9250   const auto& TA = ArgList->get(0);
9251   if (TA.getKind() != TemplateArgument::Type) return;
9252   QualType ArgType = TA.getAsType();
9253   if (!ArgType->isUnsignedIntegerType()) return;
9254 
9255   // See if either argument is a literal zero.
9256   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9257     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9258     if (!MTE) return false;
9259     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9260     if (!Num) return false;
9261     if (Num->getValue() != 0) return false;
9262     return true;
9263   };
9264 
9265   const Expr *FirstArg = Call->getArg(0);
9266   const Expr *SecondArg = Call->getArg(1);
9267   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9268   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9269 
9270   // Only warn when exactly one argument is zero.
9271   if (IsFirstArgZero == IsSecondArgZero) return;
9272 
9273   SourceRange FirstRange = FirstArg->getSourceRange();
9274   SourceRange SecondRange = SecondArg->getSourceRange();
9275 
9276   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9277 
9278   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9279       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9280 
9281   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9282   SourceRange RemovalRange;
9283   if (IsFirstArgZero) {
9284     RemovalRange = SourceRange(FirstRange.getBegin(),
9285                                SecondRange.getBegin().getLocWithOffset(-1));
9286   } else {
9287     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9288                                SecondRange.getEnd());
9289   }
9290 
9291   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9292         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9293         << FixItHint::CreateRemoval(RemovalRange);
9294 }
9295 
9296 //===--- CHECK: Standard memory functions ---------------------------------===//
9297 
9298 /// Takes the expression passed to the size_t parameter of functions
9299 /// such as memcmp, strncat, etc and warns if it's a comparison.
9300 ///
9301 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9302 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9303                                            IdentifierInfo *FnName,
9304                                            SourceLocation FnLoc,
9305                                            SourceLocation RParenLoc) {
9306   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9307   if (!Size)
9308     return false;
9309 
9310   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9311   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9312     return false;
9313 
9314   SourceRange SizeRange = Size->getSourceRange();
9315   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9316       << SizeRange << FnName;
9317   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9318       << FnName
9319       << FixItHint::CreateInsertion(
9320              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9321       << FixItHint::CreateRemoval(RParenLoc);
9322   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9323       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9324       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9325                                     ")");
9326 
9327   return true;
9328 }
9329 
9330 /// Determine whether the given type is or contains a dynamic class type
9331 /// (e.g., whether it has a vtable).
9332 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9333                                                      bool &IsContained) {
9334   // Look through array types while ignoring qualifiers.
9335   const Type *Ty = T->getBaseElementTypeUnsafe();
9336   IsContained = false;
9337 
9338   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9339   RD = RD ? RD->getDefinition() : nullptr;
9340   if (!RD || RD->isInvalidDecl())
9341     return nullptr;
9342 
9343   if (RD->isDynamicClass())
9344     return RD;
9345 
9346   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9347   // It's impossible for a class to transitively contain itself by value, so
9348   // infinite recursion is impossible.
9349   for (auto *FD : RD->fields()) {
9350     bool SubContained;
9351     if (const CXXRecordDecl *ContainedRD =
9352             getContainedDynamicClass(FD->getType(), SubContained)) {
9353       IsContained = true;
9354       return ContainedRD;
9355     }
9356   }
9357 
9358   return nullptr;
9359 }
9360 
9361 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9362   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9363     if (Unary->getKind() == UETT_SizeOf)
9364       return Unary;
9365   return nullptr;
9366 }
9367 
9368 /// If E is a sizeof expression, returns its argument expression,
9369 /// otherwise returns NULL.
9370 static const Expr *getSizeOfExprArg(const Expr *E) {
9371   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9372     if (!SizeOf->isArgumentType())
9373       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9374   return nullptr;
9375 }
9376 
9377 /// If E is a sizeof expression, returns its argument type.
9378 static QualType getSizeOfArgType(const Expr *E) {
9379   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9380     return SizeOf->getTypeOfArgument();
9381   return QualType();
9382 }
9383 
9384 namespace {
9385 
9386 struct SearchNonTrivialToInitializeField
9387     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9388   using Super =
9389       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9390 
9391   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9392 
9393   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9394                      SourceLocation SL) {
9395     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9396       asDerived().visitArray(PDIK, AT, SL);
9397       return;
9398     }
9399 
9400     Super::visitWithKind(PDIK, FT, SL);
9401   }
9402 
9403   void visitARCStrong(QualType FT, SourceLocation SL) {
9404     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9405   }
9406   void visitARCWeak(QualType FT, SourceLocation SL) {
9407     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9408   }
9409   void visitStruct(QualType FT, SourceLocation SL) {
9410     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9411       visit(FD->getType(), FD->getLocation());
9412   }
9413   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9414                   const ArrayType *AT, SourceLocation SL) {
9415     visit(getContext().getBaseElementType(AT), SL);
9416   }
9417   void visitTrivial(QualType FT, SourceLocation SL) {}
9418 
9419   static void diag(QualType RT, const Expr *E, Sema &S) {
9420     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9421   }
9422 
9423   ASTContext &getContext() { return S.getASTContext(); }
9424 
9425   const Expr *E;
9426   Sema &S;
9427 };
9428 
9429 struct SearchNonTrivialToCopyField
9430     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9431   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9432 
9433   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9434 
9435   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9436                      SourceLocation SL) {
9437     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9438       asDerived().visitArray(PCK, AT, SL);
9439       return;
9440     }
9441 
9442     Super::visitWithKind(PCK, FT, SL);
9443   }
9444 
9445   void visitARCStrong(QualType FT, SourceLocation SL) {
9446     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9447   }
9448   void visitARCWeak(QualType FT, SourceLocation SL) {
9449     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9450   }
9451   void visitStruct(QualType FT, SourceLocation SL) {
9452     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9453       visit(FD->getType(), FD->getLocation());
9454   }
9455   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9456                   SourceLocation SL) {
9457     visit(getContext().getBaseElementType(AT), SL);
9458   }
9459   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9460                 SourceLocation SL) {}
9461   void visitTrivial(QualType FT, SourceLocation SL) {}
9462   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9463 
9464   static void diag(QualType RT, const Expr *E, Sema &S) {
9465     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9466   }
9467 
9468   ASTContext &getContext() { return S.getASTContext(); }
9469 
9470   const Expr *E;
9471   Sema &S;
9472 };
9473 
9474 }
9475 
9476 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9477 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9478   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9479 
9480   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9481     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9482       return false;
9483 
9484     return doesExprLikelyComputeSize(BO->getLHS()) ||
9485            doesExprLikelyComputeSize(BO->getRHS());
9486   }
9487 
9488   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9489 }
9490 
9491 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9492 ///
9493 /// \code
9494 ///   #define MACRO 0
9495 ///   foo(MACRO);
9496 ///   foo(0);
9497 /// \endcode
9498 ///
9499 /// This should return true for the first call to foo, but not for the second
9500 /// (regardless of whether foo is a macro or function).
9501 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9502                                         SourceLocation CallLoc,
9503                                         SourceLocation ArgLoc) {
9504   if (!CallLoc.isMacroID())
9505     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9506 
9507   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9508          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9509 }
9510 
9511 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9512 /// last two arguments transposed.
9513 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9514   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9515     return;
9516 
9517   const Expr *SizeArg =
9518     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9519 
9520   auto isLiteralZero = [](const Expr *E) {
9521     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9522   };
9523 
9524   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9525   SourceLocation CallLoc = Call->getRParenLoc();
9526   SourceManager &SM = S.getSourceManager();
9527   if (isLiteralZero(SizeArg) &&
9528       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9529 
9530     SourceLocation DiagLoc = SizeArg->getExprLoc();
9531 
9532     // Some platforms #define bzero to __builtin_memset. See if this is the
9533     // case, and if so, emit a better diagnostic.
9534     if (BId == Builtin::BIbzero ||
9535         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9536                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9537       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9538       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9539     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9540       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9541       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9542     }
9543     return;
9544   }
9545 
9546   // If the second argument to a memset is a sizeof expression and the third
9547   // isn't, this is also likely an error. This should catch
9548   // 'memset(buf, sizeof(buf), 0xff)'.
9549   if (BId == Builtin::BImemset &&
9550       doesExprLikelyComputeSize(Call->getArg(1)) &&
9551       !doesExprLikelyComputeSize(Call->getArg(2))) {
9552     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9553     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9554     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9555     return;
9556   }
9557 }
9558 
9559 /// Check for dangerous or invalid arguments to memset().
9560 ///
9561 /// This issues warnings on known problematic, dangerous or unspecified
9562 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9563 /// function calls.
9564 ///
9565 /// \param Call The call expression to diagnose.
9566 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9567                                    unsigned BId,
9568                                    IdentifierInfo *FnName) {
9569   assert(BId != 0);
9570 
9571   // It is possible to have a non-standard definition of memset.  Validate
9572   // we have enough arguments, and if not, abort further checking.
9573   unsigned ExpectedNumArgs =
9574       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9575   if (Call->getNumArgs() < ExpectedNumArgs)
9576     return;
9577 
9578   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9579                       BId == Builtin::BIstrndup ? 1 : 2);
9580   unsigned LenArg =
9581       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9582   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9583 
9584   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9585                                      Call->getBeginLoc(), Call->getRParenLoc()))
9586     return;
9587 
9588   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9589   CheckMemaccessSize(*this, BId, Call);
9590 
9591   // We have special checking when the length is a sizeof expression.
9592   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9593   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9594   llvm::FoldingSetNodeID SizeOfArgID;
9595 
9596   // Although widely used, 'bzero' is not a standard function. Be more strict
9597   // with the argument types before allowing diagnostics and only allow the
9598   // form bzero(ptr, sizeof(...)).
9599   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9600   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9601     return;
9602 
9603   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9604     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9605     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9606 
9607     QualType DestTy = Dest->getType();
9608     QualType PointeeTy;
9609     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9610       PointeeTy = DestPtrTy->getPointeeType();
9611 
9612       // Never warn about void type pointers. This can be used to suppress
9613       // false positives.
9614       if (PointeeTy->isVoidType())
9615         continue;
9616 
9617       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9618       // actually comparing the expressions for equality. Because computing the
9619       // expression IDs can be expensive, we only do this if the diagnostic is
9620       // enabled.
9621       if (SizeOfArg &&
9622           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9623                            SizeOfArg->getExprLoc())) {
9624         // We only compute IDs for expressions if the warning is enabled, and
9625         // cache the sizeof arg's ID.
9626         if (SizeOfArgID == llvm::FoldingSetNodeID())
9627           SizeOfArg->Profile(SizeOfArgID, Context, true);
9628         llvm::FoldingSetNodeID DestID;
9629         Dest->Profile(DestID, Context, true);
9630         if (DestID == SizeOfArgID) {
9631           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9632           //       over sizeof(src) as well.
9633           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9634           StringRef ReadableName = FnName->getName();
9635 
9636           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9637             if (UnaryOp->getOpcode() == UO_AddrOf)
9638               ActionIdx = 1; // If its an address-of operator, just remove it.
9639           if (!PointeeTy->isIncompleteType() &&
9640               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9641             ActionIdx = 2; // If the pointee's size is sizeof(char),
9642                            // suggest an explicit length.
9643 
9644           // If the function is defined as a builtin macro, do not show macro
9645           // expansion.
9646           SourceLocation SL = SizeOfArg->getExprLoc();
9647           SourceRange DSR = Dest->getSourceRange();
9648           SourceRange SSR = SizeOfArg->getSourceRange();
9649           SourceManager &SM = getSourceManager();
9650 
9651           if (SM.isMacroArgExpansion(SL)) {
9652             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9653             SL = SM.getSpellingLoc(SL);
9654             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9655                              SM.getSpellingLoc(DSR.getEnd()));
9656             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9657                              SM.getSpellingLoc(SSR.getEnd()));
9658           }
9659 
9660           DiagRuntimeBehavior(SL, SizeOfArg,
9661                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9662                                 << ReadableName
9663                                 << PointeeTy
9664                                 << DestTy
9665                                 << DSR
9666                                 << SSR);
9667           DiagRuntimeBehavior(SL, SizeOfArg,
9668                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9669                                 << ActionIdx
9670                                 << SSR);
9671 
9672           break;
9673         }
9674       }
9675 
9676       // Also check for cases where the sizeof argument is the exact same
9677       // type as the memory argument, and where it points to a user-defined
9678       // record type.
9679       if (SizeOfArgTy != QualType()) {
9680         if (PointeeTy->isRecordType() &&
9681             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9682           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9683                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9684                                 << FnName << SizeOfArgTy << ArgIdx
9685                                 << PointeeTy << Dest->getSourceRange()
9686                                 << LenExpr->getSourceRange());
9687           break;
9688         }
9689       }
9690     } else if (DestTy->isArrayType()) {
9691       PointeeTy = DestTy;
9692     }
9693 
9694     if (PointeeTy == QualType())
9695       continue;
9696 
9697     // Always complain about dynamic classes.
9698     bool IsContained;
9699     if (const CXXRecordDecl *ContainedRD =
9700             getContainedDynamicClass(PointeeTy, IsContained)) {
9701 
9702       unsigned OperationType = 0;
9703       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9704       // "overwritten" if we're warning about the destination for any call
9705       // but memcmp; otherwise a verb appropriate to the call.
9706       if (ArgIdx != 0 || IsCmp) {
9707         if (BId == Builtin::BImemcpy)
9708           OperationType = 1;
9709         else if(BId == Builtin::BImemmove)
9710           OperationType = 2;
9711         else if (IsCmp)
9712           OperationType = 3;
9713       }
9714 
9715       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9716                           PDiag(diag::warn_dyn_class_memaccess)
9717                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9718                               << IsContained << ContainedRD << OperationType
9719                               << Call->getCallee()->getSourceRange());
9720     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9721              BId != Builtin::BImemset)
9722       DiagRuntimeBehavior(
9723         Dest->getExprLoc(), Dest,
9724         PDiag(diag::warn_arc_object_memaccess)
9725           << ArgIdx << FnName << PointeeTy
9726           << Call->getCallee()->getSourceRange());
9727     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9728       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9729           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9730         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9731                             PDiag(diag::warn_cstruct_memaccess)
9732                                 << ArgIdx << FnName << PointeeTy << 0);
9733         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9734       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9735                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9736         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9737                             PDiag(diag::warn_cstruct_memaccess)
9738                                 << ArgIdx << FnName << PointeeTy << 1);
9739         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9740       } else {
9741         continue;
9742       }
9743     } else
9744       continue;
9745 
9746     DiagRuntimeBehavior(
9747       Dest->getExprLoc(), Dest,
9748       PDiag(diag::note_bad_memaccess_silence)
9749         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9750     break;
9751   }
9752 }
9753 
9754 // A little helper routine: ignore addition and subtraction of integer literals.
9755 // This intentionally does not ignore all integer constant expressions because
9756 // we don't want to remove sizeof().
9757 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9758   Ex = Ex->IgnoreParenCasts();
9759 
9760   while (true) {
9761     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9762     if (!BO || !BO->isAdditiveOp())
9763       break;
9764 
9765     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9766     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9767 
9768     if (isa<IntegerLiteral>(RHS))
9769       Ex = LHS;
9770     else if (isa<IntegerLiteral>(LHS))
9771       Ex = RHS;
9772     else
9773       break;
9774   }
9775 
9776   return Ex;
9777 }
9778 
9779 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9780                                                       ASTContext &Context) {
9781   // Only handle constant-sized or VLAs, but not flexible members.
9782   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9783     // Only issue the FIXIT for arrays of size > 1.
9784     if (CAT->getSize().getSExtValue() <= 1)
9785       return false;
9786   } else if (!Ty->isVariableArrayType()) {
9787     return false;
9788   }
9789   return true;
9790 }
9791 
9792 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9793 // be the size of the source, instead of the destination.
9794 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9795                                     IdentifierInfo *FnName) {
9796 
9797   // Don't crash if the user has the wrong number of arguments
9798   unsigned NumArgs = Call->getNumArgs();
9799   if ((NumArgs != 3) && (NumArgs != 4))
9800     return;
9801 
9802   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9803   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9804   const Expr *CompareWithSrc = nullptr;
9805 
9806   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9807                                      Call->getBeginLoc(), Call->getRParenLoc()))
9808     return;
9809 
9810   // Look for 'strlcpy(dst, x, sizeof(x))'
9811   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9812     CompareWithSrc = Ex;
9813   else {
9814     // Look for 'strlcpy(dst, x, strlen(x))'
9815     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9816       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9817           SizeCall->getNumArgs() == 1)
9818         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9819     }
9820   }
9821 
9822   if (!CompareWithSrc)
9823     return;
9824 
9825   // Determine if the argument to sizeof/strlen is equal to the source
9826   // argument.  In principle there's all kinds of things you could do
9827   // here, for instance creating an == expression and evaluating it with
9828   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9829   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9830   if (!SrcArgDRE)
9831     return;
9832 
9833   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9834   if (!CompareWithSrcDRE ||
9835       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9836     return;
9837 
9838   const Expr *OriginalSizeArg = Call->getArg(2);
9839   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9840       << OriginalSizeArg->getSourceRange() << FnName;
9841 
9842   // Output a FIXIT hint if the destination is an array (rather than a
9843   // pointer to an array).  This could be enhanced to handle some
9844   // pointers if we know the actual size, like if DstArg is 'array+2'
9845   // we could say 'sizeof(array)-2'.
9846   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9847   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9848     return;
9849 
9850   SmallString<128> sizeString;
9851   llvm::raw_svector_ostream OS(sizeString);
9852   OS << "sizeof(";
9853   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9854   OS << ")";
9855 
9856   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9857       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9858                                       OS.str());
9859 }
9860 
9861 /// Check if two expressions refer to the same declaration.
9862 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9863   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9864     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9865       return D1->getDecl() == D2->getDecl();
9866   return false;
9867 }
9868 
9869 static const Expr *getStrlenExprArg(const Expr *E) {
9870   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9871     const FunctionDecl *FD = CE->getDirectCallee();
9872     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9873       return nullptr;
9874     return CE->getArg(0)->IgnoreParenCasts();
9875   }
9876   return nullptr;
9877 }
9878 
9879 // Warn on anti-patterns as the 'size' argument to strncat.
9880 // The correct size argument should look like following:
9881 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9882 void Sema::CheckStrncatArguments(const CallExpr *CE,
9883                                  IdentifierInfo *FnName) {
9884   // Don't crash if the user has the wrong number of arguments.
9885   if (CE->getNumArgs() < 3)
9886     return;
9887   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9888   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9889   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9890 
9891   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9892                                      CE->getRParenLoc()))
9893     return;
9894 
9895   // Identify common expressions, which are wrongly used as the size argument
9896   // to strncat and may lead to buffer overflows.
9897   unsigned PatternType = 0;
9898   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9899     // - sizeof(dst)
9900     if (referToTheSameDecl(SizeOfArg, DstArg))
9901       PatternType = 1;
9902     // - sizeof(src)
9903     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9904       PatternType = 2;
9905   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9906     if (BE->getOpcode() == BO_Sub) {
9907       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9908       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9909       // - sizeof(dst) - strlen(dst)
9910       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9911           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9912         PatternType = 1;
9913       // - sizeof(src) - (anything)
9914       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9915         PatternType = 2;
9916     }
9917   }
9918 
9919   if (PatternType == 0)
9920     return;
9921 
9922   // Generate the diagnostic.
9923   SourceLocation SL = LenArg->getBeginLoc();
9924   SourceRange SR = LenArg->getSourceRange();
9925   SourceManager &SM = getSourceManager();
9926 
9927   // If the function is defined as a builtin macro, do not show macro expansion.
9928   if (SM.isMacroArgExpansion(SL)) {
9929     SL = SM.getSpellingLoc(SL);
9930     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9931                      SM.getSpellingLoc(SR.getEnd()));
9932   }
9933 
9934   // Check if the destination is an array (rather than a pointer to an array).
9935   QualType DstTy = DstArg->getType();
9936   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9937                                                                     Context);
9938   if (!isKnownSizeArray) {
9939     if (PatternType == 1)
9940       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9941     else
9942       Diag(SL, diag::warn_strncat_src_size) << SR;
9943     return;
9944   }
9945 
9946   if (PatternType == 1)
9947     Diag(SL, diag::warn_strncat_large_size) << SR;
9948   else
9949     Diag(SL, diag::warn_strncat_src_size) << SR;
9950 
9951   SmallString<128> sizeString;
9952   llvm::raw_svector_ostream OS(sizeString);
9953   OS << "sizeof(";
9954   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9955   OS << ") - ";
9956   OS << "strlen(";
9957   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9958   OS << ") - 1";
9959 
9960   Diag(SL, diag::note_strncat_wrong_size)
9961     << FixItHint::CreateReplacement(SR, OS.str());
9962 }
9963 
9964 void
9965 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9966                          SourceLocation ReturnLoc,
9967                          bool isObjCMethod,
9968                          const AttrVec *Attrs,
9969                          const FunctionDecl *FD) {
9970   // Check if the return value is null but should not be.
9971   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9972        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9973       CheckNonNullExpr(*this, RetValExp))
9974     Diag(ReturnLoc, diag::warn_null_ret)
9975       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9976 
9977   // C++11 [basic.stc.dynamic.allocation]p4:
9978   //   If an allocation function declared with a non-throwing
9979   //   exception-specification fails to allocate storage, it shall return
9980   //   a null pointer. Any other allocation function that fails to allocate
9981   //   storage shall indicate failure only by throwing an exception [...]
9982   if (FD) {
9983     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9984     if (Op == OO_New || Op == OO_Array_New) {
9985       const FunctionProtoType *Proto
9986         = FD->getType()->castAs<FunctionProtoType>();
9987       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9988           CheckNonNullExpr(*this, RetValExp))
9989         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9990           << FD << getLangOpts().CPlusPlus11;
9991     }
9992   }
9993 }
9994 
9995 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9996 
9997 /// Check for comparisons of floating point operands using != and ==.
9998 /// Issue a warning if these are no self-comparisons, as they are not likely
9999 /// to do what the programmer intended.
10000 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10001   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10002   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10003 
10004   // Special case: check for x == x (which is OK).
10005   // Do not emit warnings for such cases.
10006   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10007     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10008       if (DRL->getDecl() == DRR->getDecl())
10009         return;
10010 
10011   // Special case: check for comparisons against literals that can be exactly
10012   //  represented by APFloat.  In such cases, do not emit a warning.  This
10013   //  is a heuristic: often comparison against such literals are used to
10014   //  detect if a value in a variable has not changed.  This clearly can
10015   //  lead to false negatives.
10016   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10017     if (FLL->isExact())
10018       return;
10019   } else
10020     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10021       if (FLR->isExact())
10022         return;
10023 
10024   // Check for comparisons with builtin types.
10025   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10026     if (CL->getBuiltinCallee())
10027       return;
10028 
10029   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10030     if (CR->getBuiltinCallee())
10031       return;
10032 
10033   // Emit the diagnostic.
10034   Diag(Loc, diag::warn_floatingpoint_eq)
10035     << LHS->getSourceRange() << RHS->getSourceRange();
10036 }
10037 
10038 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10039 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10040 
10041 namespace {
10042 
10043 /// Structure recording the 'active' range of an integer-valued
10044 /// expression.
10045 struct IntRange {
10046   /// The number of bits active in the int.
10047   unsigned Width;
10048 
10049   /// True if the int is known not to have negative values.
10050   bool NonNegative;
10051 
10052   IntRange(unsigned Width, bool NonNegative)
10053       : Width(Width), NonNegative(NonNegative) {}
10054 
10055   /// Returns the range of the bool type.
10056   static IntRange forBoolType() {
10057     return IntRange(1, true);
10058   }
10059 
10060   /// Returns the range of an opaque value of the given integral type.
10061   static IntRange forValueOfType(ASTContext &C, QualType T) {
10062     return forValueOfCanonicalType(C,
10063                           T->getCanonicalTypeInternal().getTypePtr());
10064   }
10065 
10066   /// Returns the range of an opaque value of a canonical integral type.
10067   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10068     assert(T->isCanonicalUnqualified());
10069 
10070     if (const VectorType *VT = dyn_cast<VectorType>(T))
10071       T = VT->getElementType().getTypePtr();
10072     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10073       T = CT->getElementType().getTypePtr();
10074     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10075       T = AT->getValueType().getTypePtr();
10076 
10077     if (!C.getLangOpts().CPlusPlus) {
10078       // For enum types in C code, use the underlying datatype.
10079       if (const EnumType *ET = dyn_cast<EnumType>(T))
10080         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10081     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10082       // For enum types in C++, use the known bit width of the enumerators.
10083       EnumDecl *Enum = ET->getDecl();
10084       // In C++11, enums can have a fixed underlying type. Use this type to
10085       // compute the range.
10086       if (Enum->isFixed()) {
10087         return IntRange(C.getIntWidth(QualType(T, 0)),
10088                         !ET->isSignedIntegerOrEnumerationType());
10089       }
10090 
10091       unsigned NumPositive = Enum->getNumPositiveBits();
10092       unsigned NumNegative = Enum->getNumNegativeBits();
10093 
10094       if (NumNegative == 0)
10095         return IntRange(NumPositive, true/*NonNegative*/);
10096       else
10097         return IntRange(std::max(NumPositive + 1, NumNegative),
10098                         false/*NonNegative*/);
10099     }
10100 
10101     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10102       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10103 
10104     const BuiltinType *BT = cast<BuiltinType>(T);
10105     assert(BT->isInteger());
10106 
10107     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10108   }
10109 
10110   /// Returns the "target" range of a canonical integral type, i.e.
10111   /// the range of values expressible in the type.
10112   ///
10113   /// This matches forValueOfCanonicalType except that enums have the
10114   /// full range of their type, not the range of their enumerators.
10115   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10116     assert(T->isCanonicalUnqualified());
10117 
10118     if (const VectorType *VT = dyn_cast<VectorType>(T))
10119       T = VT->getElementType().getTypePtr();
10120     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10121       T = CT->getElementType().getTypePtr();
10122     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10123       T = AT->getValueType().getTypePtr();
10124     if (const EnumType *ET = dyn_cast<EnumType>(T))
10125       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10126 
10127     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10128       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10129 
10130     const BuiltinType *BT = cast<BuiltinType>(T);
10131     assert(BT->isInteger());
10132 
10133     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10134   }
10135 
10136   /// Returns the supremum of two ranges: i.e. their conservative merge.
10137   static IntRange join(IntRange L, IntRange R) {
10138     return IntRange(std::max(L.Width, R.Width),
10139                     L.NonNegative && R.NonNegative);
10140   }
10141 
10142   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10143   static IntRange meet(IntRange L, IntRange R) {
10144     return IntRange(std::min(L.Width, R.Width),
10145                     L.NonNegative || R.NonNegative);
10146   }
10147 };
10148 
10149 } // namespace
10150 
10151 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10152                               unsigned MaxWidth) {
10153   if (value.isSigned() && value.isNegative())
10154     return IntRange(value.getMinSignedBits(), false);
10155 
10156   if (value.getBitWidth() > MaxWidth)
10157     value = value.trunc(MaxWidth);
10158 
10159   // isNonNegative() just checks the sign bit without considering
10160   // signedness.
10161   return IntRange(value.getActiveBits(), true);
10162 }
10163 
10164 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10165                               unsigned MaxWidth) {
10166   if (result.isInt())
10167     return GetValueRange(C, result.getInt(), MaxWidth);
10168 
10169   if (result.isVector()) {
10170     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10171     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10172       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10173       R = IntRange::join(R, El);
10174     }
10175     return R;
10176   }
10177 
10178   if (result.isComplexInt()) {
10179     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10180     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10181     return IntRange::join(R, I);
10182   }
10183 
10184   // This can happen with lossless casts to intptr_t of "based" lvalues.
10185   // Assume it might use arbitrary bits.
10186   // FIXME: The only reason we need to pass the type in here is to get
10187   // the sign right on this one case.  It would be nice if APValue
10188   // preserved this.
10189   assert(result.isLValue() || result.isAddrLabelDiff());
10190   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10191 }
10192 
10193 static QualType GetExprType(const Expr *E) {
10194   QualType Ty = E->getType();
10195   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10196     Ty = AtomicRHS->getValueType();
10197   return Ty;
10198 }
10199 
10200 /// Pseudo-evaluate the given integer expression, estimating the
10201 /// range of values it might take.
10202 ///
10203 /// \param MaxWidth - the width to which the value will be truncated
10204 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10205                              bool InConstantContext) {
10206   E = E->IgnoreParens();
10207 
10208   // Try a full evaluation first.
10209   Expr::EvalResult result;
10210   if (E->EvaluateAsRValue(result, C, InConstantContext))
10211     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10212 
10213   // I think we only want to look through implicit casts here; if the
10214   // user has an explicit widening cast, we should treat the value as
10215   // being of the new, wider type.
10216   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10217     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10218       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10219 
10220     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10221 
10222     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10223                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10224 
10225     // Assume that non-integer casts can span the full range of the type.
10226     if (!isIntegerCast)
10227       return OutputTypeRange;
10228 
10229     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10230                                      std::min(MaxWidth, OutputTypeRange.Width),
10231                                      InConstantContext);
10232 
10233     // Bail out if the subexpr's range is as wide as the cast type.
10234     if (SubRange.Width >= OutputTypeRange.Width)
10235       return OutputTypeRange;
10236 
10237     // Otherwise, we take the smaller width, and we're non-negative if
10238     // either the output type or the subexpr is.
10239     return IntRange(SubRange.Width,
10240                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10241   }
10242 
10243   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10244     // If we can fold the condition, just take that operand.
10245     bool CondResult;
10246     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10247       return GetExprRange(C,
10248                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10249                           MaxWidth, InConstantContext);
10250 
10251     // Otherwise, conservatively merge.
10252     IntRange L =
10253         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10254     IntRange R =
10255         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10256     return IntRange::join(L, R);
10257   }
10258 
10259   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10260     switch (BO->getOpcode()) {
10261     case BO_Cmp:
10262       llvm_unreachable("builtin <=> should have class type");
10263 
10264     // Boolean-valued operations are single-bit and positive.
10265     case BO_LAnd:
10266     case BO_LOr:
10267     case BO_LT:
10268     case BO_GT:
10269     case BO_LE:
10270     case BO_GE:
10271     case BO_EQ:
10272     case BO_NE:
10273       return IntRange::forBoolType();
10274 
10275     // The type of the assignments is the type of the LHS, so the RHS
10276     // is not necessarily the same type.
10277     case BO_MulAssign:
10278     case BO_DivAssign:
10279     case BO_RemAssign:
10280     case BO_AddAssign:
10281     case BO_SubAssign:
10282     case BO_XorAssign:
10283     case BO_OrAssign:
10284       // TODO: bitfields?
10285       return IntRange::forValueOfType(C, GetExprType(E));
10286 
10287     // Simple assignments just pass through the RHS, which will have
10288     // been coerced to the LHS type.
10289     case BO_Assign:
10290       // TODO: bitfields?
10291       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10292 
10293     // Operations with opaque sources are black-listed.
10294     case BO_PtrMemD:
10295     case BO_PtrMemI:
10296       return IntRange::forValueOfType(C, GetExprType(E));
10297 
10298     // Bitwise-and uses the *infinum* of the two source ranges.
10299     case BO_And:
10300     case BO_AndAssign:
10301       return IntRange::meet(
10302           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10303           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10304 
10305     // Left shift gets black-listed based on a judgement call.
10306     case BO_Shl:
10307       // ...except that we want to treat '1 << (blah)' as logically
10308       // positive.  It's an important idiom.
10309       if (IntegerLiteral *I
10310             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10311         if (I->getValue() == 1) {
10312           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10313           return IntRange(R.Width, /*NonNegative*/ true);
10314         }
10315       }
10316       LLVM_FALLTHROUGH;
10317 
10318     case BO_ShlAssign:
10319       return IntRange::forValueOfType(C, GetExprType(E));
10320 
10321     // Right shift by a constant can narrow its left argument.
10322     case BO_Shr:
10323     case BO_ShrAssign: {
10324       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10325 
10326       // If the shift amount is a positive constant, drop the width by
10327       // that much.
10328       if (Optional<llvm::APSInt> shift =
10329               BO->getRHS()->getIntegerConstantExpr(C)) {
10330         if (shift->isNonNegative()) {
10331           unsigned zext = shift->getZExtValue();
10332           if (zext >= L.Width)
10333             L.Width = (L.NonNegative ? 0 : 1);
10334           else
10335             L.Width -= zext;
10336         }
10337       }
10338 
10339       return L;
10340     }
10341 
10342     // Comma acts as its right operand.
10343     case BO_Comma:
10344       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10345 
10346     // Black-list pointer subtractions.
10347     case BO_Sub:
10348       if (BO->getLHS()->getType()->isPointerType())
10349         return IntRange::forValueOfType(C, GetExprType(E));
10350       break;
10351 
10352     // The width of a division result is mostly determined by the size
10353     // of the LHS.
10354     case BO_Div: {
10355       // Don't 'pre-truncate' the operands.
10356       unsigned opWidth = C.getIntWidth(GetExprType(E));
10357       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10358 
10359       // If the divisor is constant, use that.
10360       if (Optional<llvm::APSInt> divisor =
10361               BO->getRHS()->getIntegerConstantExpr(C)) {
10362         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10363         if (log2 >= L.Width)
10364           L.Width = (L.NonNegative ? 0 : 1);
10365         else
10366           L.Width = std::min(L.Width - log2, MaxWidth);
10367         return L;
10368       }
10369 
10370       // Otherwise, just use the LHS's width.
10371       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10372       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10373     }
10374 
10375     // The result of a remainder can't be larger than the result of
10376     // either side.
10377     case BO_Rem: {
10378       // Don't 'pre-truncate' the operands.
10379       unsigned opWidth = C.getIntWidth(GetExprType(E));
10380       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10381       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10382 
10383       IntRange meet = IntRange::meet(L, R);
10384       meet.Width = std::min(meet.Width, MaxWidth);
10385       return meet;
10386     }
10387 
10388     // The default behavior is okay for these.
10389     case BO_Mul:
10390     case BO_Add:
10391     case BO_Xor:
10392     case BO_Or:
10393       break;
10394     }
10395 
10396     // The default case is to treat the operation as if it were closed
10397     // on the narrowest type that encompasses both operands.
10398     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10399     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10400     return IntRange::join(L, R);
10401   }
10402 
10403   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10404     switch (UO->getOpcode()) {
10405     // Boolean-valued operations are white-listed.
10406     case UO_LNot:
10407       return IntRange::forBoolType();
10408 
10409     // Operations with opaque sources are black-listed.
10410     case UO_Deref:
10411     case UO_AddrOf: // should be impossible
10412       return IntRange::forValueOfType(C, GetExprType(E));
10413 
10414     default:
10415       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10416     }
10417   }
10418 
10419   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10420     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10421 
10422   if (const auto *BitField = E->getSourceBitField())
10423     return IntRange(BitField->getBitWidthValue(C),
10424                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10425 
10426   return IntRange::forValueOfType(C, GetExprType(E));
10427 }
10428 
10429 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10430                              bool InConstantContext) {
10431   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10432 }
10433 
10434 /// Checks whether the given value, which currently has the given
10435 /// source semantics, has the same value when coerced through the
10436 /// target semantics.
10437 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10438                                  const llvm::fltSemantics &Src,
10439                                  const llvm::fltSemantics &Tgt) {
10440   llvm::APFloat truncated = value;
10441 
10442   bool ignored;
10443   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10444   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10445 
10446   return truncated.bitwiseIsEqual(value);
10447 }
10448 
10449 /// Checks whether the given value, which currently has the given
10450 /// source semantics, has the same value when coerced through the
10451 /// target semantics.
10452 ///
10453 /// The value might be a vector of floats (or a complex number).
10454 static bool IsSameFloatAfterCast(const APValue &value,
10455                                  const llvm::fltSemantics &Src,
10456                                  const llvm::fltSemantics &Tgt) {
10457   if (value.isFloat())
10458     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10459 
10460   if (value.isVector()) {
10461     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10462       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10463         return false;
10464     return true;
10465   }
10466 
10467   assert(value.isComplexFloat());
10468   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10469           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10470 }
10471 
10472 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10473                                        bool IsListInit = false);
10474 
10475 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10476   // Suppress cases where we are comparing against an enum constant.
10477   if (const DeclRefExpr *DR =
10478       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10479     if (isa<EnumConstantDecl>(DR->getDecl()))
10480       return true;
10481 
10482   // Suppress cases where the value is expanded from a macro, unless that macro
10483   // is how a language represents a boolean literal. This is the case in both C
10484   // and Objective-C.
10485   SourceLocation BeginLoc = E->getBeginLoc();
10486   if (BeginLoc.isMacroID()) {
10487     StringRef MacroName = Lexer::getImmediateMacroName(
10488         BeginLoc, S.getSourceManager(), S.getLangOpts());
10489     return MacroName != "YES" && MacroName != "NO" &&
10490            MacroName != "true" && MacroName != "false";
10491   }
10492 
10493   return false;
10494 }
10495 
10496 static bool isKnownToHaveUnsignedValue(Expr *E) {
10497   return E->getType()->isIntegerType() &&
10498          (!E->getType()->isSignedIntegerType() ||
10499           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10500 }
10501 
10502 namespace {
10503 /// The promoted range of values of a type. In general this has the
10504 /// following structure:
10505 ///
10506 ///     |-----------| . . . |-----------|
10507 ///     ^           ^       ^           ^
10508 ///    Min       HoleMin  HoleMax      Max
10509 ///
10510 /// ... where there is only a hole if a signed type is promoted to unsigned
10511 /// (in which case Min and Max are the smallest and largest representable
10512 /// values).
10513 struct PromotedRange {
10514   // Min, or HoleMax if there is a hole.
10515   llvm::APSInt PromotedMin;
10516   // Max, or HoleMin if there is a hole.
10517   llvm::APSInt PromotedMax;
10518 
10519   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10520     if (R.Width == 0)
10521       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10522     else if (R.Width >= BitWidth && !Unsigned) {
10523       // Promotion made the type *narrower*. This happens when promoting
10524       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10525       // Treat all values of 'signed int' as being in range for now.
10526       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10527       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10528     } else {
10529       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10530                         .extOrTrunc(BitWidth);
10531       PromotedMin.setIsUnsigned(Unsigned);
10532 
10533       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10534                         .extOrTrunc(BitWidth);
10535       PromotedMax.setIsUnsigned(Unsigned);
10536     }
10537   }
10538 
10539   // Determine whether this range is contiguous (has no hole).
10540   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10541 
10542   // Where a constant value is within the range.
10543   enum ComparisonResult {
10544     LT = 0x1,
10545     LE = 0x2,
10546     GT = 0x4,
10547     GE = 0x8,
10548     EQ = 0x10,
10549     NE = 0x20,
10550     InRangeFlag = 0x40,
10551 
10552     Less = LE | LT | NE,
10553     Min = LE | InRangeFlag,
10554     InRange = InRangeFlag,
10555     Max = GE | InRangeFlag,
10556     Greater = GE | GT | NE,
10557 
10558     OnlyValue = LE | GE | EQ | InRangeFlag,
10559     InHole = NE
10560   };
10561 
10562   ComparisonResult compare(const llvm::APSInt &Value) const {
10563     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10564            Value.isUnsigned() == PromotedMin.isUnsigned());
10565     if (!isContiguous()) {
10566       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10567       if (Value.isMinValue()) return Min;
10568       if (Value.isMaxValue()) return Max;
10569       if (Value >= PromotedMin) return InRange;
10570       if (Value <= PromotedMax) return InRange;
10571       return InHole;
10572     }
10573 
10574     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10575     case -1: return Less;
10576     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10577     case 1:
10578       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10579       case -1: return InRange;
10580       case 0: return Max;
10581       case 1: return Greater;
10582       }
10583     }
10584 
10585     llvm_unreachable("impossible compare result");
10586   }
10587 
10588   static llvm::Optional<StringRef>
10589   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10590     if (Op == BO_Cmp) {
10591       ComparisonResult LTFlag = LT, GTFlag = GT;
10592       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10593 
10594       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10595       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10596       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10597       return llvm::None;
10598     }
10599 
10600     ComparisonResult TrueFlag, FalseFlag;
10601     if (Op == BO_EQ) {
10602       TrueFlag = EQ;
10603       FalseFlag = NE;
10604     } else if (Op == BO_NE) {
10605       TrueFlag = NE;
10606       FalseFlag = EQ;
10607     } else {
10608       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10609         TrueFlag = LT;
10610         FalseFlag = GE;
10611       } else {
10612         TrueFlag = GT;
10613         FalseFlag = LE;
10614       }
10615       if (Op == BO_GE || Op == BO_LE)
10616         std::swap(TrueFlag, FalseFlag);
10617     }
10618     if (R & TrueFlag)
10619       return StringRef("true");
10620     if (R & FalseFlag)
10621       return StringRef("false");
10622     return llvm::None;
10623   }
10624 };
10625 }
10626 
10627 static bool HasEnumType(Expr *E) {
10628   // Strip off implicit integral promotions.
10629   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10630     if (ICE->getCastKind() != CK_IntegralCast &&
10631         ICE->getCastKind() != CK_NoOp)
10632       break;
10633     E = ICE->getSubExpr();
10634   }
10635 
10636   return E->getType()->isEnumeralType();
10637 }
10638 
10639 static int classifyConstantValue(Expr *Constant) {
10640   // The values of this enumeration are used in the diagnostics
10641   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10642   enum ConstantValueKind {
10643     Miscellaneous = 0,
10644     LiteralTrue,
10645     LiteralFalse
10646   };
10647   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10648     return BL->getValue() ? ConstantValueKind::LiteralTrue
10649                           : ConstantValueKind::LiteralFalse;
10650   return ConstantValueKind::Miscellaneous;
10651 }
10652 
10653 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10654                                         Expr *Constant, Expr *Other,
10655                                         const llvm::APSInt &Value,
10656                                         bool RhsConstant) {
10657   if (S.inTemplateInstantiation())
10658     return false;
10659 
10660   Expr *OriginalOther = Other;
10661 
10662   Constant = Constant->IgnoreParenImpCasts();
10663   Other = Other->IgnoreParenImpCasts();
10664 
10665   // Suppress warnings on tautological comparisons between values of the same
10666   // enumeration type. There are only two ways we could warn on this:
10667   //  - If the constant is outside the range of representable values of
10668   //    the enumeration. In such a case, we should warn about the cast
10669   //    to enumeration type, not about the comparison.
10670   //  - If the constant is the maximum / minimum in-range value. For an
10671   //    enumeratin type, such comparisons can be meaningful and useful.
10672   if (Constant->getType()->isEnumeralType() &&
10673       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10674     return false;
10675 
10676   // TODO: Investigate using GetExprRange() to get tighter bounds
10677   // on the bit ranges.
10678   QualType OtherT = Other->getType();
10679   if (const auto *AT = OtherT->getAs<AtomicType>())
10680     OtherT = AT->getValueType();
10681   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10682 
10683   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10684   // (Namely, macOS).
10685   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10686                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10687                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10688 
10689   // Whether we're treating Other as being a bool because of the form of
10690   // expression despite it having another type (typically 'int' in C).
10691   bool OtherIsBooleanDespiteType =
10692       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10693   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10694     OtherRange = IntRange::forBoolType();
10695 
10696   // Determine the promoted range of the other type and see if a comparison of
10697   // the constant against that range is tautological.
10698   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10699                                    Value.isUnsigned());
10700   auto Cmp = OtherPromotedRange.compare(Value);
10701   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10702   if (!Result)
10703     return false;
10704 
10705   // Suppress the diagnostic for an in-range comparison if the constant comes
10706   // from a macro or enumerator. We don't want to diagnose
10707   //
10708   //   some_long_value <= INT_MAX
10709   //
10710   // when sizeof(int) == sizeof(long).
10711   bool InRange = Cmp & PromotedRange::InRangeFlag;
10712   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10713     return false;
10714 
10715   // If this is a comparison to an enum constant, include that
10716   // constant in the diagnostic.
10717   const EnumConstantDecl *ED = nullptr;
10718   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10719     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10720 
10721   // Should be enough for uint128 (39 decimal digits)
10722   SmallString<64> PrettySourceValue;
10723   llvm::raw_svector_ostream OS(PrettySourceValue);
10724   if (ED) {
10725     OS << '\'' << *ED << "' (" << Value << ")";
10726   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10727                Constant->IgnoreParenImpCasts())) {
10728     OS << (BL->getValue() ? "YES" : "NO");
10729   } else {
10730     OS << Value;
10731   }
10732 
10733   if (IsObjCSignedCharBool) {
10734     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10735                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10736                               << OS.str() << *Result);
10737     return true;
10738   }
10739 
10740   // FIXME: We use a somewhat different formatting for the in-range cases and
10741   // cases involving boolean values for historical reasons. We should pick a
10742   // consistent way of presenting these diagnostics.
10743   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10744 
10745     S.DiagRuntimeBehavior(
10746         E->getOperatorLoc(), E,
10747         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10748                          : diag::warn_tautological_bool_compare)
10749             << OS.str() << classifyConstantValue(Constant) << OtherT
10750             << OtherIsBooleanDespiteType << *Result
10751             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10752   } else {
10753     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10754                         ? (HasEnumType(OriginalOther)
10755                                ? diag::warn_unsigned_enum_always_true_comparison
10756                                : diag::warn_unsigned_always_true_comparison)
10757                         : diag::warn_tautological_constant_compare;
10758 
10759     S.Diag(E->getOperatorLoc(), Diag)
10760         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10761         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10762   }
10763 
10764   return true;
10765 }
10766 
10767 /// Analyze the operands of the given comparison.  Implements the
10768 /// fallback case from AnalyzeComparison.
10769 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10770   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10771   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10772 }
10773 
10774 /// Implements -Wsign-compare.
10775 ///
10776 /// \param E the binary operator to check for warnings
10777 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10778   // The type the comparison is being performed in.
10779   QualType T = E->getLHS()->getType();
10780 
10781   // Only analyze comparison operators where both sides have been converted to
10782   // the same type.
10783   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10784     return AnalyzeImpConvsInComparison(S, E);
10785 
10786   // Don't analyze value-dependent comparisons directly.
10787   if (E->isValueDependent())
10788     return AnalyzeImpConvsInComparison(S, E);
10789 
10790   Expr *LHS = E->getLHS();
10791   Expr *RHS = E->getRHS();
10792 
10793   if (T->isIntegralType(S.Context)) {
10794     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
10795     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
10796 
10797     // We don't care about expressions whose result is a constant.
10798     if (RHSValue && LHSValue)
10799       return AnalyzeImpConvsInComparison(S, E);
10800 
10801     // We only care about expressions where just one side is literal
10802     if ((bool)RHSValue ^ (bool)LHSValue) {
10803       // Is the constant on the RHS or LHS?
10804       const bool RhsConstant = (bool)RHSValue;
10805       Expr *Const = RhsConstant ? RHS : LHS;
10806       Expr *Other = RhsConstant ? LHS : RHS;
10807       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
10808 
10809       // Check whether an integer constant comparison results in a value
10810       // of 'true' or 'false'.
10811       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10812         return AnalyzeImpConvsInComparison(S, E);
10813     }
10814   }
10815 
10816   if (!T->hasUnsignedIntegerRepresentation()) {
10817     // We don't do anything special if this isn't an unsigned integral
10818     // comparison:  we're only interested in integral comparisons, and
10819     // signed comparisons only happen in cases we don't care to warn about.
10820     return AnalyzeImpConvsInComparison(S, E);
10821   }
10822 
10823   LHS = LHS->IgnoreParenImpCasts();
10824   RHS = RHS->IgnoreParenImpCasts();
10825 
10826   if (!S.getLangOpts().CPlusPlus) {
10827     // Avoid warning about comparison of integers with different signs when
10828     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10829     // the type of `E`.
10830     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10831       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10832     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10833       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10834   }
10835 
10836   // Check to see if one of the (unmodified) operands is of different
10837   // signedness.
10838   Expr *signedOperand, *unsignedOperand;
10839   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10840     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10841            "unsigned comparison between two signed integer expressions?");
10842     signedOperand = LHS;
10843     unsignedOperand = RHS;
10844   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10845     signedOperand = RHS;
10846     unsignedOperand = LHS;
10847   } else {
10848     return AnalyzeImpConvsInComparison(S, E);
10849   }
10850 
10851   // Otherwise, calculate the effective range of the signed operand.
10852   IntRange signedRange =
10853       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10854 
10855   // Go ahead and analyze implicit conversions in the operands.  Note
10856   // that we skip the implicit conversions on both sides.
10857   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10858   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10859 
10860   // If the signed range is non-negative, -Wsign-compare won't fire.
10861   if (signedRange.NonNegative)
10862     return;
10863 
10864   // For (in)equality comparisons, if the unsigned operand is a
10865   // constant which cannot collide with a overflowed signed operand,
10866   // then reinterpreting the signed operand as unsigned will not
10867   // change the result of the comparison.
10868   if (E->isEqualityOp()) {
10869     unsigned comparisonWidth = S.Context.getIntWidth(T);
10870     IntRange unsignedRange =
10871         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10872 
10873     // We should never be unable to prove that the unsigned operand is
10874     // non-negative.
10875     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10876 
10877     if (unsignedRange.Width < comparisonWidth)
10878       return;
10879   }
10880 
10881   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10882                         S.PDiag(diag::warn_mixed_sign_comparison)
10883                             << LHS->getType() << RHS->getType()
10884                             << LHS->getSourceRange() << RHS->getSourceRange());
10885 }
10886 
10887 /// Analyzes an attempt to assign the given value to a bitfield.
10888 ///
10889 /// Returns true if there was something fishy about the attempt.
10890 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10891                                       SourceLocation InitLoc) {
10892   assert(Bitfield->isBitField());
10893   if (Bitfield->isInvalidDecl())
10894     return false;
10895 
10896   // White-list bool bitfields.
10897   QualType BitfieldType = Bitfield->getType();
10898   if (BitfieldType->isBooleanType())
10899      return false;
10900 
10901   if (BitfieldType->isEnumeralType()) {
10902     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10903     // If the underlying enum type was not explicitly specified as an unsigned
10904     // type and the enum contain only positive values, MSVC++ will cause an
10905     // inconsistency by storing this as a signed type.
10906     if (S.getLangOpts().CPlusPlus11 &&
10907         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10908         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10909         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10910       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10911         << BitfieldEnumDecl->getNameAsString();
10912     }
10913   }
10914 
10915   if (Bitfield->getType()->isBooleanType())
10916     return false;
10917 
10918   // Ignore value- or type-dependent expressions.
10919   if (Bitfield->getBitWidth()->isValueDependent() ||
10920       Bitfield->getBitWidth()->isTypeDependent() ||
10921       Init->isValueDependent() ||
10922       Init->isTypeDependent())
10923     return false;
10924 
10925   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10926   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10927 
10928   Expr::EvalResult Result;
10929   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10930                                    Expr::SE_AllowSideEffects)) {
10931     // The RHS is not constant.  If the RHS has an enum type, make sure the
10932     // bitfield is wide enough to hold all the values of the enum without
10933     // truncation.
10934     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10935       EnumDecl *ED = EnumTy->getDecl();
10936       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10937 
10938       // Enum types are implicitly signed on Windows, so check if there are any
10939       // negative enumerators to see if the enum was intended to be signed or
10940       // not.
10941       bool SignedEnum = ED->getNumNegativeBits() > 0;
10942 
10943       // Check for surprising sign changes when assigning enum values to a
10944       // bitfield of different signedness.  If the bitfield is signed and we
10945       // have exactly the right number of bits to store this unsigned enum,
10946       // suggest changing the enum to an unsigned type. This typically happens
10947       // on Windows where unfixed enums always use an underlying type of 'int'.
10948       unsigned DiagID = 0;
10949       if (SignedEnum && !SignedBitfield) {
10950         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10951       } else if (SignedBitfield && !SignedEnum &&
10952                  ED->getNumPositiveBits() == FieldWidth) {
10953         DiagID = diag::warn_signed_bitfield_enum_conversion;
10954       }
10955 
10956       if (DiagID) {
10957         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10958         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10959         SourceRange TypeRange =
10960             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10961         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10962             << SignedEnum << TypeRange;
10963       }
10964 
10965       // Compute the required bitwidth. If the enum has negative values, we need
10966       // one more bit than the normal number of positive bits to represent the
10967       // sign bit.
10968       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10969                                                   ED->getNumNegativeBits())
10970                                        : ED->getNumPositiveBits();
10971 
10972       // Check the bitwidth.
10973       if (BitsNeeded > FieldWidth) {
10974         Expr *WidthExpr = Bitfield->getBitWidth();
10975         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10976             << Bitfield << ED;
10977         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10978             << BitsNeeded << ED << WidthExpr->getSourceRange();
10979       }
10980     }
10981 
10982     return false;
10983   }
10984 
10985   llvm::APSInt Value = Result.Val.getInt();
10986 
10987   unsigned OriginalWidth = Value.getBitWidth();
10988 
10989   if (!Value.isSigned() || Value.isNegative())
10990     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10991       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10992         OriginalWidth = Value.getMinSignedBits();
10993 
10994   if (OriginalWidth <= FieldWidth)
10995     return false;
10996 
10997   // Compute the value which the bitfield will contain.
10998   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10999   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11000 
11001   // Check whether the stored value is equal to the original value.
11002   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11003   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11004     return false;
11005 
11006   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11007   // therefore don't strictly fit into a signed bitfield of width 1.
11008   if (FieldWidth == 1 && Value == 1)
11009     return false;
11010 
11011   std::string PrettyValue = Value.toString(10);
11012   std::string PrettyTrunc = TruncatedValue.toString(10);
11013 
11014   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11015     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11016     << Init->getSourceRange();
11017 
11018   return true;
11019 }
11020 
11021 /// Analyze the given simple or compound assignment for warning-worthy
11022 /// operations.
11023 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11024   // Just recurse on the LHS.
11025   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11026 
11027   // We want to recurse on the RHS as normal unless we're assigning to
11028   // a bitfield.
11029   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11030     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11031                                   E->getOperatorLoc())) {
11032       // Recurse, ignoring any implicit conversions on the RHS.
11033       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11034                                         E->getOperatorLoc());
11035     }
11036   }
11037 
11038   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11039 
11040   // Diagnose implicitly sequentially-consistent atomic assignment.
11041   if (E->getLHS()->getType()->isAtomicType())
11042     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11043 }
11044 
11045 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11046 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11047                             SourceLocation CContext, unsigned diag,
11048                             bool pruneControlFlow = false) {
11049   if (pruneControlFlow) {
11050     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11051                           S.PDiag(diag)
11052                               << SourceType << T << E->getSourceRange()
11053                               << SourceRange(CContext));
11054     return;
11055   }
11056   S.Diag(E->getExprLoc(), diag)
11057     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11058 }
11059 
11060 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11061 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11062                             SourceLocation CContext,
11063                             unsigned diag, bool pruneControlFlow = false) {
11064   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11065 }
11066 
11067 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11068   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11069       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11070 }
11071 
11072 static void adornObjCBoolConversionDiagWithTernaryFixit(
11073     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11074   Expr *Ignored = SourceExpr->IgnoreImplicit();
11075   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11076     Ignored = OVE->getSourceExpr();
11077   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11078                      isa<BinaryOperator>(Ignored) ||
11079                      isa<CXXOperatorCallExpr>(Ignored);
11080   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11081   if (NeedsParens)
11082     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11083             << FixItHint::CreateInsertion(EndLoc, ")");
11084   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11085 }
11086 
11087 /// Diagnose an implicit cast from a floating point value to an integer value.
11088 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11089                                     SourceLocation CContext) {
11090   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11091   const bool PruneWarnings = S.inTemplateInstantiation();
11092 
11093   Expr *InnerE = E->IgnoreParenImpCasts();
11094   // We also want to warn on, e.g., "int i = -1.234"
11095   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11096     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11097       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11098 
11099   const bool IsLiteral =
11100       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11101 
11102   llvm::APFloat Value(0.0);
11103   bool IsConstant =
11104     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11105   if (!IsConstant) {
11106     if (isObjCSignedCharBool(S, T)) {
11107       return adornObjCBoolConversionDiagWithTernaryFixit(
11108           S, E,
11109           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11110               << E->getType());
11111     }
11112 
11113     return DiagnoseImpCast(S, E, T, CContext,
11114                            diag::warn_impcast_float_integer, PruneWarnings);
11115   }
11116 
11117   bool isExact = false;
11118 
11119   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11120                             T->hasUnsignedIntegerRepresentation());
11121   llvm::APFloat::opStatus Result = Value.convertToInteger(
11122       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11123 
11124   // FIXME: Force the precision of the source value down so we don't print
11125   // digits which are usually useless (we don't really care here if we
11126   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11127   // would automatically print the shortest representation, but it's a bit
11128   // tricky to implement.
11129   SmallString<16> PrettySourceValue;
11130   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11131   precision = (precision * 59 + 195) / 196;
11132   Value.toString(PrettySourceValue, precision);
11133 
11134   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11135     return adornObjCBoolConversionDiagWithTernaryFixit(
11136         S, E,
11137         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11138             << PrettySourceValue);
11139   }
11140 
11141   if (Result == llvm::APFloat::opOK && isExact) {
11142     if (IsLiteral) return;
11143     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11144                            PruneWarnings);
11145   }
11146 
11147   // Conversion of a floating-point value to a non-bool integer where the
11148   // integral part cannot be represented by the integer type is undefined.
11149   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11150     return DiagnoseImpCast(
11151         S, E, T, CContext,
11152         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11153                   : diag::warn_impcast_float_to_integer_out_of_range,
11154         PruneWarnings);
11155 
11156   unsigned DiagID = 0;
11157   if (IsLiteral) {
11158     // Warn on floating point literal to integer.
11159     DiagID = diag::warn_impcast_literal_float_to_integer;
11160   } else if (IntegerValue == 0) {
11161     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11162       return DiagnoseImpCast(S, E, T, CContext,
11163                              diag::warn_impcast_float_integer, PruneWarnings);
11164     }
11165     // Warn on non-zero to zero conversion.
11166     DiagID = diag::warn_impcast_float_to_integer_zero;
11167   } else {
11168     if (IntegerValue.isUnsigned()) {
11169       if (!IntegerValue.isMaxValue()) {
11170         return DiagnoseImpCast(S, E, T, CContext,
11171                                diag::warn_impcast_float_integer, PruneWarnings);
11172       }
11173     } else {  // IntegerValue.isSigned()
11174       if (!IntegerValue.isMaxSignedValue() &&
11175           !IntegerValue.isMinSignedValue()) {
11176         return DiagnoseImpCast(S, E, T, CContext,
11177                                diag::warn_impcast_float_integer, PruneWarnings);
11178       }
11179     }
11180     // Warn on evaluatable floating point expression to integer conversion.
11181     DiagID = diag::warn_impcast_float_to_integer;
11182   }
11183 
11184   SmallString<16> PrettyTargetValue;
11185   if (IsBool)
11186     PrettyTargetValue = Value.isZero() ? "false" : "true";
11187   else
11188     IntegerValue.toString(PrettyTargetValue);
11189 
11190   if (PruneWarnings) {
11191     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11192                           S.PDiag(DiagID)
11193                               << E->getType() << T.getUnqualifiedType()
11194                               << PrettySourceValue << PrettyTargetValue
11195                               << E->getSourceRange() << SourceRange(CContext));
11196   } else {
11197     S.Diag(E->getExprLoc(), DiagID)
11198         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11199         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11200   }
11201 }
11202 
11203 /// Analyze the given compound assignment for the possible losing of
11204 /// floating-point precision.
11205 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11206   assert(isa<CompoundAssignOperator>(E) &&
11207          "Must be compound assignment operation");
11208   // Recurse on the LHS and RHS in here
11209   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11210   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11211 
11212   if (E->getLHS()->getType()->isAtomicType())
11213     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11214 
11215   // Now check the outermost expression
11216   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11217   const auto *RBT = cast<CompoundAssignOperator>(E)
11218                         ->getComputationResultType()
11219                         ->getAs<BuiltinType>();
11220 
11221   // The below checks assume source is floating point.
11222   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11223 
11224   // If source is floating point but target is an integer.
11225   if (ResultBT->isInteger())
11226     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11227                            E->getExprLoc(), diag::warn_impcast_float_integer);
11228 
11229   if (!ResultBT->isFloatingPoint())
11230     return;
11231 
11232   // If both source and target are floating points, warn about losing precision.
11233   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11234       QualType(ResultBT, 0), QualType(RBT, 0));
11235   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11236     // warn about dropping FP rank.
11237     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11238                     diag::warn_impcast_float_result_precision);
11239 }
11240 
11241 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11242                                       IntRange Range) {
11243   if (!Range.Width) return "0";
11244 
11245   llvm::APSInt ValueInRange = Value;
11246   ValueInRange.setIsSigned(!Range.NonNegative);
11247   ValueInRange = ValueInRange.trunc(Range.Width);
11248   return ValueInRange.toString(10);
11249 }
11250 
11251 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11252   if (!isa<ImplicitCastExpr>(Ex))
11253     return false;
11254 
11255   Expr *InnerE = Ex->IgnoreParenImpCasts();
11256   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11257   const Type *Source =
11258     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11259   if (Target->isDependentType())
11260     return false;
11261 
11262   const BuiltinType *FloatCandidateBT =
11263     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11264   const Type *BoolCandidateType = ToBool ? Target : Source;
11265 
11266   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11267           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11268 }
11269 
11270 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11271                                              SourceLocation CC) {
11272   unsigned NumArgs = TheCall->getNumArgs();
11273   for (unsigned i = 0; i < NumArgs; ++i) {
11274     Expr *CurrA = TheCall->getArg(i);
11275     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11276       continue;
11277 
11278     bool IsSwapped = ((i > 0) &&
11279         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11280     IsSwapped |= ((i < (NumArgs - 1)) &&
11281         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11282     if (IsSwapped) {
11283       // Warn on this floating-point to bool conversion.
11284       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11285                       CurrA->getType(), CC,
11286                       diag::warn_impcast_floating_point_to_bool);
11287     }
11288   }
11289 }
11290 
11291 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11292                                    SourceLocation CC) {
11293   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11294                         E->getExprLoc()))
11295     return;
11296 
11297   // Don't warn on functions which have return type nullptr_t.
11298   if (isa<CallExpr>(E))
11299     return;
11300 
11301   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11302   const Expr::NullPointerConstantKind NullKind =
11303       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11304   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11305     return;
11306 
11307   // Return if target type is a safe conversion.
11308   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11309       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11310     return;
11311 
11312   SourceLocation Loc = E->getSourceRange().getBegin();
11313 
11314   // Venture through the macro stacks to get to the source of macro arguments.
11315   // The new location is a better location than the complete location that was
11316   // passed in.
11317   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11318   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11319 
11320   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11321   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11322     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11323         Loc, S.SourceMgr, S.getLangOpts());
11324     if (MacroName == "NULL")
11325       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11326   }
11327 
11328   // Only warn if the null and context location are in the same macro expansion.
11329   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11330     return;
11331 
11332   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11333       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11334       << FixItHint::CreateReplacement(Loc,
11335                                       S.getFixItZeroLiteralForType(T, Loc));
11336 }
11337 
11338 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11339                                   ObjCArrayLiteral *ArrayLiteral);
11340 
11341 static void
11342 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11343                            ObjCDictionaryLiteral *DictionaryLiteral);
11344 
11345 /// Check a single element within a collection literal against the
11346 /// target element type.
11347 static void checkObjCCollectionLiteralElement(Sema &S,
11348                                               QualType TargetElementType,
11349                                               Expr *Element,
11350                                               unsigned ElementKind) {
11351   // Skip a bitcast to 'id' or qualified 'id'.
11352   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11353     if (ICE->getCastKind() == CK_BitCast &&
11354         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11355       Element = ICE->getSubExpr();
11356   }
11357 
11358   QualType ElementType = Element->getType();
11359   ExprResult ElementResult(Element);
11360   if (ElementType->getAs<ObjCObjectPointerType>() &&
11361       S.CheckSingleAssignmentConstraints(TargetElementType,
11362                                          ElementResult,
11363                                          false, false)
11364         != Sema::Compatible) {
11365     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11366         << ElementType << ElementKind << TargetElementType
11367         << Element->getSourceRange();
11368   }
11369 
11370   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11371     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11372   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11373     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11374 }
11375 
11376 /// Check an Objective-C array literal being converted to the given
11377 /// target type.
11378 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11379                                   ObjCArrayLiteral *ArrayLiteral) {
11380   if (!S.NSArrayDecl)
11381     return;
11382 
11383   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11384   if (!TargetObjCPtr)
11385     return;
11386 
11387   if (TargetObjCPtr->isUnspecialized() ||
11388       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11389         != S.NSArrayDecl->getCanonicalDecl())
11390     return;
11391 
11392   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11393   if (TypeArgs.size() != 1)
11394     return;
11395 
11396   QualType TargetElementType = TypeArgs[0];
11397   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11398     checkObjCCollectionLiteralElement(S, TargetElementType,
11399                                       ArrayLiteral->getElement(I),
11400                                       0);
11401   }
11402 }
11403 
11404 /// Check an Objective-C dictionary literal being converted to the given
11405 /// target type.
11406 static void
11407 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11408                            ObjCDictionaryLiteral *DictionaryLiteral) {
11409   if (!S.NSDictionaryDecl)
11410     return;
11411 
11412   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11413   if (!TargetObjCPtr)
11414     return;
11415 
11416   if (TargetObjCPtr->isUnspecialized() ||
11417       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11418         != S.NSDictionaryDecl->getCanonicalDecl())
11419     return;
11420 
11421   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11422   if (TypeArgs.size() != 2)
11423     return;
11424 
11425   QualType TargetKeyType = TypeArgs[0];
11426   QualType TargetObjectType = TypeArgs[1];
11427   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11428     auto Element = DictionaryLiteral->getKeyValueElement(I);
11429     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11430     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11431   }
11432 }
11433 
11434 // Helper function to filter out cases for constant width constant conversion.
11435 // Don't warn on char array initialization or for non-decimal values.
11436 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11437                                           SourceLocation CC) {
11438   // If initializing from a constant, and the constant starts with '0',
11439   // then it is a binary, octal, or hexadecimal.  Allow these constants
11440   // to fill all the bits, even if there is a sign change.
11441   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11442     const char FirstLiteralCharacter =
11443         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11444     if (FirstLiteralCharacter == '0')
11445       return false;
11446   }
11447 
11448   // If the CC location points to a '{', and the type is char, then assume
11449   // assume it is an array initialization.
11450   if (CC.isValid() && T->isCharType()) {
11451     const char FirstContextCharacter =
11452         S.getSourceManager().getCharacterData(CC)[0];
11453     if (FirstContextCharacter == '{')
11454       return false;
11455   }
11456 
11457   return true;
11458 }
11459 
11460 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11461   const auto *IL = dyn_cast<IntegerLiteral>(E);
11462   if (!IL) {
11463     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11464       if (UO->getOpcode() == UO_Minus)
11465         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11466     }
11467   }
11468 
11469   return IL;
11470 }
11471 
11472 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11473   E = E->IgnoreParenImpCasts();
11474   SourceLocation ExprLoc = E->getExprLoc();
11475 
11476   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11477     BinaryOperator::Opcode Opc = BO->getOpcode();
11478     Expr::EvalResult Result;
11479     // Do not diagnose unsigned shifts.
11480     if (Opc == BO_Shl) {
11481       const auto *LHS = getIntegerLiteral(BO->getLHS());
11482       const auto *RHS = getIntegerLiteral(BO->getRHS());
11483       if (LHS && LHS->getValue() == 0)
11484         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11485       else if (!E->isValueDependent() && LHS && RHS &&
11486                RHS->getValue().isNonNegative() &&
11487                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11488         S.Diag(ExprLoc, diag::warn_left_shift_always)
11489             << (Result.Val.getInt() != 0);
11490       else if (E->getType()->isSignedIntegerType())
11491         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11492     }
11493   }
11494 
11495   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11496     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11497     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11498     if (!LHS || !RHS)
11499       return;
11500     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11501         (RHS->getValue() == 0 || RHS->getValue() == 1))
11502       // Do not diagnose common idioms.
11503       return;
11504     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11505       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11506   }
11507 }
11508 
11509 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11510                                     SourceLocation CC,
11511                                     bool *ICContext = nullptr,
11512                                     bool IsListInit = false) {
11513   if (E->isTypeDependent() || E->isValueDependent()) return;
11514 
11515   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11516   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11517   if (Source == Target) return;
11518   if (Target->isDependentType()) return;
11519 
11520   // If the conversion context location is invalid don't complain. We also
11521   // don't want to emit a warning if the issue occurs from the expansion of
11522   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11523   // delay this check as long as possible. Once we detect we are in that
11524   // scenario, we just return.
11525   if (CC.isInvalid())
11526     return;
11527 
11528   if (Source->isAtomicType())
11529     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11530 
11531   // Diagnose implicit casts to bool.
11532   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11533     if (isa<StringLiteral>(E))
11534       // Warn on string literal to bool.  Checks for string literals in logical
11535       // and expressions, for instance, assert(0 && "error here"), are
11536       // prevented by a check in AnalyzeImplicitConversions().
11537       return DiagnoseImpCast(S, E, T, CC,
11538                              diag::warn_impcast_string_literal_to_bool);
11539     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11540         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11541       // This covers the literal expressions that evaluate to Objective-C
11542       // objects.
11543       return DiagnoseImpCast(S, E, T, CC,
11544                              diag::warn_impcast_objective_c_literal_to_bool);
11545     }
11546     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11547       // Warn on pointer to bool conversion that is always true.
11548       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11549                                      SourceRange(CC));
11550     }
11551   }
11552 
11553   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11554   // is a typedef for signed char (macOS), then that constant value has to be 1
11555   // or 0.
11556   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11557     Expr::EvalResult Result;
11558     if (E->EvaluateAsInt(Result, S.getASTContext(),
11559                          Expr::SE_AllowSideEffects)) {
11560       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11561         adornObjCBoolConversionDiagWithTernaryFixit(
11562             S, E,
11563             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11564                 << Result.Val.getInt().toString(10));
11565       }
11566       return;
11567     }
11568   }
11569 
11570   // Check implicit casts from Objective-C collection literals to specialized
11571   // collection types, e.g., NSArray<NSString *> *.
11572   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11573     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11574   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11575     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11576 
11577   // Strip vector types.
11578   if (isa<VectorType>(Source)) {
11579     if (!isa<VectorType>(Target)) {
11580       if (S.SourceMgr.isInSystemMacro(CC))
11581         return;
11582       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11583     }
11584 
11585     // If the vector cast is cast between two vectors of the same size, it is
11586     // a bitcast, not a conversion.
11587     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11588       return;
11589 
11590     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11591     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11592   }
11593   if (auto VecTy = dyn_cast<VectorType>(Target))
11594     Target = VecTy->getElementType().getTypePtr();
11595 
11596   // Strip complex types.
11597   if (isa<ComplexType>(Source)) {
11598     if (!isa<ComplexType>(Target)) {
11599       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11600         return;
11601 
11602       return DiagnoseImpCast(S, E, T, CC,
11603                              S.getLangOpts().CPlusPlus
11604                                  ? diag::err_impcast_complex_scalar
11605                                  : diag::warn_impcast_complex_scalar);
11606     }
11607 
11608     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11609     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11610   }
11611 
11612   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11613   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11614 
11615   // If the source is floating point...
11616   if (SourceBT && SourceBT->isFloatingPoint()) {
11617     // ...and the target is floating point...
11618     if (TargetBT && TargetBT->isFloatingPoint()) {
11619       // ...then warn if we're dropping FP rank.
11620 
11621       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11622           QualType(SourceBT, 0), QualType(TargetBT, 0));
11623       if (Order > 0) {
11624         // Don't warn about float constants that are precisely
11625         // representable in the target type.
11626         Expr::EvalResult result;
11627         if (E->EvaluateAsRValue(result, S.Context)) {
11628           // Value might be a float, a float vector, or a float complex.
11629           if (IsSameFloatAfterCast(result.Val,
11630                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11631                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11632             return;
11633         }
11634 
11635         if (S.SourceMgr.isInSystemMacro(CC))
11636           return;
11637 
11638         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11639       }
11640       // ... or possibly if we're increasing rank, too
11641       else if (Order < 0) {
11642         if (S.SourceMgr.isInSystemMacro(CC))
11643           return;
11644 
11645         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11646       }
11647       return;
11648     }
11649 
11650     // If the target is integral, always warn.
11651     if (TargetBT && TargetBT->isInteger()) {
11652       if (S.SourceMgr.isInSystemMacro(CC))
11653         return;
11654 
11655       DiagnoseFloatingImpCast(S, E, T, CC);
11656     }
11657 
11658     // Detect the case where a call result is converted from floating-point to
11659     // to bool, and the final argument to the call is converted from bool, to
11660     // discover this typo:
11661     //
11662     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11663     //
11664     // FIXME: This is an incredibly special case; is there some more general
11665     // way to detect this class of misplaced-parentheses bug?
11666     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11667       // Check last argument of function call to see if it is an
11668       // implicit cast from a type matching the type the result
11669       // is being cast to.
11670       CallExpr *CEx = cast<CallExpr>(E);
11671       if (unsigned NumArgs = CEx->getNumArgs()) {
11672         Expr *LastA = CEx->getArg(NumArgs - 1);
11673         Expr *InnerE = LastA->IgnoreParenImpCasts();
11674         if (isa<ImplicitCastExpr>(LastA) &&
11675             InnerE->getType()->isBooleanType()) {
11676           // Warn on this floating-point to bool conversion
11677           DiagnoseImpCast(S, E, T, CC,
11678                           diag::warn_impcast_floating_point_to_bool);
11679         }
11680       }
11681     }
11682     return;
11683   }
11684 
11685   // Valid casts involving fixed point types should be accounted for here.
11686   if (Source->isFixedPointType()) {
11687     if (Target->isUnsaturatedFixedPointType()) {
11688       Expr::EvalResult Result;
11689       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11690                                   S.isConstantEvaluated())) {
11691         APFixedPoint Value = Result.Val.getFixedPoint();
11692         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11693         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11694         if (Value > MaxVal || Value < MinVal) {
11695           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11696                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11697                                     << Value.toString() << T
11698                                     << E->getSourceRange()
11699                                     << clang::SourceRange(CC));
11700           return;
11701         }
11702       }
11703     } else if (Target->isIntegerType()) {
11704       Expr::EvalResult Result;
11705       if (!S.isConstantEvaluated() &&
11706           E->EvaluateAsFixedPoint(Result, S.Context,
11707                                   Expr::SE_AllowSideEffects)) {
11708         APFixedPoint FXResult = Result.Val.getFixedPoint();
11709 
11710         bool Overflowed;
11711         llvm::APSInt IntResult = FXResult.convertToInt(
11712             S.Context.getIntWidth(T),
11713             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11714 
11715         if (Overflowed) {
11716           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11717                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11718                                     << FXResult.toString() << T
11719                                     << E->getSourceRange()
11720                                     << clang::SourceRange(CC));
11721           return;
11722         }
11723       }
11724     }
11725   } else if (Target->isUnsaturatedFixedPointType()) {
11726     if (Source->isIntegerType()) {
11727       Expr::EvalResult Result;
11728       if (!S.isConstantEvaluated() &&
11729           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11730         llvm::APSInt Value = Result.Val.getInt();
11731 
11732         bool Overflowed;
11733         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11734             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11735 
11736         if (Overflowed) {
11737           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11738                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11739                                     << Value.toString(/*Radix=*/10) << T
11740                                     << E->getSourceRange()
11741                                     << clang::SourceRange(CC));
11742           return;
11743         }
11744       }
11745     }
11746   }
11747 
11748   // If we are casting an integer type to a floating point type without
11749   // initialization-list syntax, we might lose accuracy if the floating
11750   // point type has a narrower significand than the integer type.
11751   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11752       TargetBT->isFloatingType() && !IsListInit) {
11753     // Determine the number of precision bits in the source integer type.
11754     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11755     unsigned int SourcePrecision = SourceRange.Width;
11756 
11757     // Determine the number of precision bits in the
11758     // target floating point type.
11759     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11760         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11761 
11762     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11763         SourcePrecision > TargetPrecision) {
11764 
11765       if (Optional<llvm::APSInt> SourceInt =
11766               E->getIntegerConstantExpr(S.Context)) {
11767         // If the source integer is a constant, convert it to the target
11768         // floating point type. Issue a warning if the value changes
11769         // during the whole conversion.
11770         llvm::APFloat TargetFloatValue(
11771             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11772         llvm::APFloat::opStatus ConversionStatus =
11773             TargetFloatValue.convertFromAPInt(
11774                 *SourceInt, SourceBT->isSignedInteger(),
11775                 llvm::APFloat::rmNearestTiesToEven);
11776 
11777         if (ConversionStatus != llvm::APFloat::opOK) {
11778           std::string PrettySourceValue = SourceInt->toString(10);
11779           SmallString<32> PrettyTargetValue;
11780           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11781 
11782           S.DiagRuntimeBehavior(
11783               E->getExprLoc(), E,
11784               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11785                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11786                   << E->getSourceRange() << clang::SourceRange(CC));
11787         }
11788       } else {
11789         // Otherwise, the implicit conversion may lose precision.
11790         DiagnoseImpCast(S, E, T, CC,
11791                         diag::warn_impcast_integer_float_precision);
11792       }
11793     }
11794   }
11795 
11796   DiagnoseNullConversion(S, E, T, CC);
11797 
11798   S.DiscardMisalignedMemberAddress(Target, E);
11799 
11800   if (Target->isBooleanType())
11801     DiagnoseIntInBoolContext(S, E);
11802 
11803   if (!Source->isIntegerType() || !Target->isIntegerType())
11804     return;
11805 
11806   // TODO: remove this early return once the false positives for constant->bool
11807   // in templates, macros, etc, are reduced or removed.
11808   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11809     return;
11810 
11811   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11812       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11813     return adornObjCBoolConversionDiagWithTernaryFixit(
11814         S, E,
11815         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11816             << E->getType());
11817   }
11818 
11819   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11820   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11821 
11822   if (SourceRange.Width > TargetRange.Width) {
11823     // If the source is a constant, use a default-on diagnostic.
11824     // TODO: this should happen for bitfield stores, too.
11825     Expr::EvalResult Result;
11826     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11827                          S.isConstantEvaluated())) {
11828       llvm::APSInt Value(32);
11829       Value = Result.Val.getInt();
11830 
11831       if (S.SourceMgr.isInSystemMacro(CC))
11832         return;
11833 
11834       std::string PrettySourceValue = Value.toString(10);
11835       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11836 
11837       S.DiagRuntimeBehavior(
11838           E->getExprLoc(), E,
11839           S.PDiag(diag::warn_impcast_integer_precision_constant)
11840               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11841               << E->getSourceRange() << clang::SourceRange(CC));
11842       return;
11843     }
11844 
11845     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11846     if (S.SourceMgr.isInSystemMacro(CC))
11847       return;
11848 
11849     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11850       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11851                              /* pruneControlFlow */ true);
11852     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11853   }
11854 
11855   if (TargetRange.Width > SourceRange.Width) {
11856     if (auto *UO = dyn_cast<UnaryOperator>(E))
11857       if (UO->getOpcode() == UO_Minus)
11858         if (Source->isUnsignedIntegerType()) {
11859           if (Target->isUnsignedIntegerType())
11860             return DiagnoseImpCast(S, E, T, CC,
11861                                    diag::warn_impcast_high_order_zero_bits);
11862           if (Target->isSignedIntegerType())
11863             return DiagnoseImpCast(S, E, T, CC,
11864                                    diag::warn_impcast_nonnegative_result);
11865         }
11866   }
11867 
11868   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11869       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11870     // Warn when doing a signed to signed conversion, warn if the positive
11871     // source value is exactly the width of the target type, which will
11872     // cause a negative value to be stored.
11873 
11874     Expr::EvalResult Result;
11875     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11876         !S.SourceMgr.isInSystemMacro(CC)) {
11877       llvm::APSInt Value = Result.Val.getInt();
11878       if (isSameWidthConstantConversion(S, E, T, CC)) {
11879         std::string PrettySourceValue = Value.toString(10);
11880         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11881 
11882         S.DiagRuntimeBehavior(
11883             E->getExprLoc(), E,
11884             S.PDiag(diag::warn_impcast_integer_precision_constant)
11885                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11886                 << E->getSourceRange() << clang::SourceRange(CC));
11887         return;
11888       }
11889     }
11890 
11891     // Fall through for non-constants to give a sign conversion warning.
11892   }
11893 
11894   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11895       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11896        SourceRange.Width == TargetRange.Width)) {
11897     if (S.SourceMgr.isInSystemMacro(CC))
11898       return;
11899 
11900     unsigned DiagID = diag::warn_impcast_integer_sign;
11901 
11902     // Traditionally, gcc has warned about this under -Wsign-compare.
11903     // We also want to warn about it in -Wconversion.
11904     // So if -Wconversion is off, use a completely identical diagnostic
11905     // in the sign-compare group.
11906     // The conditional-checking code will
11907     if (ICContext) {
11908       DiagID = diag::warn_impcast_integer_sign_conditional;
11909       *ICContext = true;
11910     }
11911 
11912     return DiagnoseImpCast(S, E, T, CC, DiagID);
11913   }
11914 
11915   // Diagnose conversions between different enumeration types.
11916   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11917   // type, to give us better diagnostics.
11918   QualType SourceType = E->getType();
11919   if (!S.getLangOpts().CPlusPlus) {
11920     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11921       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11922         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11923         SourceType = S.Context.getTypeDeclType(Enum);
11924         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11925       }
11926   }
11927 
11928   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11929     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11930       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11931           TargetEnum->getDecl()->hasNameForLinkage() &&
11932           SourceEnum != TargetEnum) {
11933         if (S.SourceMgr.isInSystemMacro(CC))
11934           return;
11935 
11936         return DiagnoseImpCast(S, E, SourceType, T, CC,
11937                                diag::warn_impcast_different_enum_types);
11938       }
11939 }
11940 
11941 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
11942                                      SourceLocation CC, QualType T);
11943 
11944 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11945                                     SourceLocation CC, bool &ICContext) {
11946   E = E->IgnoreParenImpCasts();
11947 
11948   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
11949     return CheckConditionalOperator(S, CO, CC, T);
11950 
11951   AnalyzeImplicitConversions(S, E, CC);
11952   if (E->getType() != T)
11953     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11954 }
11955 
11956 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
11957                                      SourceLocation CC, QualType T) {
11958   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11959 
11960   Expr *TrueExpr = E->getTrueExpr();
11961   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
11962     TrueExpr = BCO->getCommon();
11963 
11964   bool Suspicious = false;
11965   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
11966   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11967 
11968   if (T->isBooleanType())
11969     DiagnoseIntInBoolContext(S, E);
11970 
11971   // If -Wconversion would have warned about either of the candidates
11972   // for a signedness conversion to the context type...
11973   if (!Suspicious) return;
11974 
11975   // ...but it's currently ignored...
11976   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11977     return;
11978 
11979   // ...then check whether it would have warned about either of the
11980   // candidates for a signedness conversion to the condition type.
11981   if (E->getType() == T) return;
11982 
11983   Suspicious = false;
11984   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
11985                           E->getType(), CC, &Suspicious);
11986   if (!Suspicious)
11987     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11988                             E->getType(), CC, &Suspicious);
11989 }
11990 
11991 /// Check conversion of given expression to boolean.
11992 /// Input argument E is a logical expression.
11993 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11994   if (S.getLangOpts().Bool)
11995     return;
11996   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11997     return;
11998   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11999 }
12000 
12001 namespace {
12002 struct AnalyzeImplicitConversionsWorkItem {
12003   Expr *E;
12004   SourceLocation CC;
12005   bool IsListInit;
12006 };
12007 }
12008 
12009 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12010 /// that should be visited are added to WorkList.
12011 static void AnalyzeImplicitConversions(
12012     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12013     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12014   Expr *OrigE = Item.E;
12015   SourceLocation CC = Item.CC;
12016 
12017   QualType T = OrigE->getType();
12018   Expr *E = OrigE->IgnoreParenImpCasts();
12019 
12020   // Propagate whether we are in a C++ list initialization expression.
12021   // If so, we do not issue warnings for implicit int-float conversion
12022   // precision loss, because C++11 narrowing already handles it.
12023   bool IsListInit = Item.IsListInit ||
12024                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12025 
12026   if (E->isTypeDependent() || E->isValueDependent())
12027     return;
12028 
12029   Expr *SourceExpr = E;
12030   // Examine, but don't traverse into the source expression of an
12031   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12032   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12033   // evaluate it in the context of checking the specific conversion to T though.
12034   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12035     if (auto *Src = OVE->getSourceExpr())
12036       SourceExpr = Src;
12037 
12038   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12039     if (UO->getOpcode() == UO_Not &&
12040         UO->getSubExpr()->isKnownToHaveBooleanValue())
12041       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12042           << OrigE->getSourceRange() << T->isBooleanType()
12043           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12044 
12045   // For conditional operators, we analyze the arguments as if they
12046   // were being fed directly into the output.
12047   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12048     CheckConditionalOperator(S, CO, CC, T);
12049     return;
12050   }
12051 
12052   // Check implicit argument conversions for function calls.
12053   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12054     CheckImplicitArgumentConversions(S, Call, CC);
12055 
12056   // Go ahead and check any implicit conversions we might have skipped.
12057   // The non-canonical typecheck is just an optimization;
12058   // CheckImplicitConversion will filter out dead implicit conversions.
12059   if (SourceExpr->getType() != T)
12060     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12061 
12062   // Now continue drilling into this expression.
12063 
12064   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12065     // The bound subexpressions in a PseudoObjectExpr are not reachable
12066     // as transitive children.
12067     // FIXME: Use a more uniform representation for this.
12068     for (auto *SE : POE->semantics())
12069       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12070         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12071   }
12072 
12073   // Skip past explicit casts.
12074   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12075     E = CE->getSubExpr()->IgnoreParenImpCasts();
12076     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12077       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12078     WorkList.push_back({E, CC, IsListInit});
12079     return;
12080   }
12081 
12082   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12083     // Do a somewhat different check with comparison operators.
12084     if (BO->isComparisonOp())
12085       return AnalyzeComparison(S, BO);
12086 
12087     // And with simple assignments.
12088     if (BO->getOpcode() == BO_Assign)
12089       return AnalyzeAssignment(S, BO);
12090     // And with compound assignments.
12091     if (BO->isAssignmentOp())
12092       return AnalyzeCompoundAssignment(S, BO);
12093   }
12094 
12095   // These break the otherwise-useful invariant below.  Fortunately,
12096   // we don't really need to recurse into them, because any internal
12097   // expressions should have been analyzed already when they were
12098   // built into statements.
12099   if (isa<StmtExpr>(E)) return;
12100 
12101   // Don't descend into unevaluated contexts.
12102   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12103 
12104   // Now just recurse over the expression's children.
12105   CC = E->getExprLoc();
12106   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12107   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12108   for (Stmt *SubStmt : E->children()) {
12109     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12110     if (!ChildExpr)
12111       continue;
12112 
12113     if (IsLogicalAndOperator &&
12114         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12115       // Ignore checking string literals that are in logical and operators.
12116       // This is a common pattern for asserts.
12117       continue;
12118     WorkList.push_back({ChildExpr, CC, IsListInit});
12119   }
12120 
12121   if (BO && BO->isLogicalOp()) {
12122     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12123     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12124       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12125 
12126     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12127     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12128       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12129   }
12130 
12131   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12132     if (U->getOpcode() == UO_LNot) {
12133       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12134     } else if (U->getOpcode() != UO_AddrOf) {
12135       if (U->getSubExpr()->getType()->isAtomicType())
12136         S.Diag(U->getSubExpr()->getBeginLoc(),
12137                diag::warn_atomic_implicit_seq_cst);
12138     }
12139   }
12140 }
12141 
12142 /// AnalyzeImplicitConversions - Find and report any interesting
12143 /// implicit conversions in the given expression.  There are a couple
12144 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12145 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12146                                        bool IsListInit/*= false*/) {
12147   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12148   WorkList.push_back({OrigE, CC, IsListInit});
12149   while (!WorkList.empty())
12150     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12151 }
12152 
12153 /// Diagnose integer type and any valid implicit conversion to it.
12154 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12155   // Taking into account implicit conversions,
12156   // allow any integer.
12157   if (!E->getType()->isIntegerType()) {
12158     S.Diag(E->getBeginLoc(),
12159            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12160     return true;
12161   }
12162   // Potentially emit standard warnings for implicit conversions if enabled
12163   // using -Wconversion.
12164   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12165   return false;
12166 }
12167 
12168 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12169 // Returns true when emitting a warning about taking the address of a reference.
12170 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12171                               const PartialDiagnostic &PD) {
12172   E = E->IgnoreParenImpCasts();
12173 
12174   const FunctionDecl *FD = nullptr;
12175 
12176   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12177     if (!DRE->getDecl()->getType()->isReferenceType())
12178       return false;
12179   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12180     if (!M->getMemberDecl()->getType()->isReferenceType())
12181       return false;
12182   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12183     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12184       return false;
12185     FD = Call->getDirectCallee();
12186   } else {
12187     return false;
12188   }
12189 
12190   SemaRef.Diag(E->getExprLoc(), PD);
12191 
12192   // If possible, point to location of function.
12193   if (FD) {
12194     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12195   }
12196 
12197   return true;
12198 }
12199 
12200 // Returns true if the SourceLocation is expanded from any macro body.
12201 // Returns false if the SourceLocation is invalid, is from not in a macro
12202 // expansion, or is from expanded from a top-level macro argument.
12203 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12204   if (Loc.isInvalid())
12205     return false;
12206 
12207   while (Loc.isMacroID()) {
12208     if (SM.isMacroBodyExpansion(Loc))
12209       return true;
12210     Loc = SM.getImmediateMacroCallerLoc(Loc);
12211   }
12212 
12213   return false;
12214 }
12215 
12216 /// Diagnose pointers that are always non-null.
12217 /// \param E the expression containing the pointer
12218 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12219 /// compared to a null pointer
12220 /// \param IsEqual True when the comparison is equal to a null pointer
12221 /// \param Range Extra SourceRange to highlight in the diagnostic
12222 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12223                                         Expr::NullPointerConstantKind NullKind,
12224                                         bool IsEqual, SourceRange Range) {
12225   if (!E)
12226     return;
12227 
12228   // Don't warn inside macros.
12229   if (E->getExprLoc().isMacroID()) {
12230     const SourceManager &SM = getSourceManager();
12231     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12232         IsInAnyMacroBody(SM, Range.getBegin()))
12233       return;
12234   }
12235   E = E->IgnoreImpCasts();
12236 
12237   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12238 
12239   if (isa<CXXThisExpr>(E)) {
12240     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12241                                 : diag::warn_this_bool_conversion;
12242     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12243     return;
12244   }
12245 
12246   bool IsAddressOf = false;
12247 
12248   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12249     if (UO->getOpcode() != UO_AddrOf)
12250       return;
12251     IsAddressOf = true;
12252     E = UO->getSubExpr();
12253   }
12254 
12255   if (IsAddressOf) {
12256     unsigned DiagID = IsCompare
12257                           ? diag::warn_address_of_reference_null_compare
12258                           : diag::warn_address_of_reference_bool_conversion;
12259     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12260                                          << IsEqual;
12261     if (CheckForReference(*this, E, PD)) {
12262       return;
12263     }
12264   }
12265 
12266   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12267     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12268     std::string Str;
12269     llvm::raw_string_ostream S(Str);
12270     E->printPretty(S, nullptr, getPrintingPolicy());
12271     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12272                                 : diag::warn_cast_nonnull_to_bool;
12273     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12274       << E->getSourceRange() << Range << IsEqual;
12275     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12276   };
12277 
12278   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12279   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12280     if (auto *Callee = Call->getDirectCallee()) {
12281       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12282         ComplainAboutNonnullParamOrCall(A);
12283         return;
12284       }
12285     }
12286   }
12287 
12288   // Expect to find a single Decl.  Skip anything more complicated.
12289   ValueDecl *D = nullptr;
12290   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12291     D = R->getDecl();
12292   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12293     D = M->getMemberDecl();
12294   }
12295 
12296   // Weak Decls can be null.
12297   if (!D || D->isWeak())
12298     return;
12299 
12300   // Check for parameter decl with nonnull attribute
12301   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12302     if (getCurFunction() &&
12303         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12304       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12305         ComplainAboutNonnullParamOrCall(A);
12306         return;
12307       }
12308 
12309       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12310         // Skip function template not specialized yet.
12311         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12312           return;
12313         auto ParamIter = llvm::find(FD->parameters(), PV);
12314         assert(ParamIter != FD->param_end());
12315         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12316 
12317         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12318           if (!NonNull->args_size()) {
12319               ComplainAboutNonnullParamOrCall(NonNull);
12320               return;
12321           }
12322 
12323           for (const ParamIdx &ArgNo : NonNull->args()) {
12324             if (ArgNo.getASTIndex() == ParamNo) {
12325               ComplainAboutNonnullParamOrCall(NonNull);
12326               return;
12327             }
12328           }
12329         }
12330       }
12331     }
12332   }
12333 
12334   QualType T = D->getType();
12335   const bool IsArray = T->isArrayType();
12336   const bool IsFunction = T->isFunctionType();
12337 
12338   // Address of function is used to silence the function warning.
12339   if (IsAddressOf && IsFunction) {
12340     return;
12341   }
12342 
12343   // Found nothing.
12344   if (!IsAddressOf && !IsFunction && !IsArray)
12345     return;
12346 
12347   // Pretty print the expression for the diagnostic.
12348   std::string Str;
12349   llvm::raw_string_ostream S(Str);
12350   E->printPretty(S, nullptr, getPrintingPolicy());
12351 
12352   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12353                               : diag::warn_impcast_pointer_to_bool;
12354   enum {
12355     AddressOf,
12356     FunctionPointer,
12357     ArrayPointer
12358   } DiagType;
12359   if (IsAddressOf)
12360     DiagType = AddressOf;
12361   else if (IsFunction)
12362     DiagType = FunctionPointer;
12363   else if (IsArray)
12364     DiagType = ArrayPointer;
12365   else
12366     llvm_unreachable("Could not determine diagnostic.");
12367   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12368                                 << Range << IsEqual;
12369 
12370   if (!IsFunction)
12371     return;
12372 
12373   // Suggest '&' to silence the function warning.
12374   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12375       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12376 
12377   // Check to see if '()' fixit should be emitted.
12378   QualType ReturnType;
12379   UnresolvedSet<4> NonTemplateOverloads;
12380   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12381   if (ReturnType.isNull())
12382     return;
12383 
12384   if (IsCompare) {
12385     // There are two cases here.  If there is null constant, the only suggest
12386     // for a pointer return type.  If the null is 0, then suggest if the return
12387     // type is a pointer or an integer type.
12388     if (!ReturnType->isPointerType()) {
12389       if (NullKind == Expr::NPCK_ZeroExpression ||
12390           NullKind == Expr::NPCK_ZeroLiteral) {
12391         if (!ReturnType->isIntegerType())
12392           return;
12393       } else {
12394         return;
12395       }
12396     }
12397   } else { // !IsCompare
12398     // For function to bool, only suggest if the function pointer has bool
12399     // return type.
12400     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12401       return;
12402   }
12403   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12404       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12405 }
12406 
12407 /// Diagnoses "dangerous" implicit conversions within the given
12408 /// expression (which is a full expression).  Implements -Wconversion
12409 /// and -Wsign-compare.
12410 ///
12411 /// \param CC the "context" location of the implicit conversion, i.e.
12412 ///   the most location of the syntactic entity requiring the implicit
12413 ///   conversion
12414 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12415   // Don't diagnose in unevaluated contexts.
12416   if (isUnevaluatedContext())
12417     return;
12418 
12419   // Don't diagnose for value- or type-dependent expressions.
12420   if (E->isTypeDependent() || E->isValueDependent())
12421     return;
12422 
12423   // Check for array bounds violations in cases where the check isn't triggered
12424   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12425   // ArraySubscriptExpr is on the RHS of a variable initialization.
12426   CheckArrayAccess(E);
12427 
12428   // This is not the right CC for (e.g.) a variable initialization.
12429   AnalyzeImplicitConversions(*this, E, CC);
12430 }
12431 
12432 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12433 /// Input argument E is a logical expression.
12434 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12435   ::CheckBoolLikeConversion(*this, E, CC);
12436 }
12437 
12438 /// Diagnose when expression is an integer constant expression and its evaluation
12439 /// results in integer overflow
12440 void Sema::CheckForIntOverflow (Expr *E) {
12441   // Use a work list to deal with nested struct initializers.
12442   SmallVector<Expr *, 2> Exprs(1, E);
12443 
12444   do {
12445     Expr *OriginalE = Exprs.pop_back_val();
12446     Expr *E = OriginalE->IgnoreParenCasts();
12447 
12448     if (isa<BinaryOperator>(E)) {
12449       E->EvaluateForOverflow(Context);
12450       continue;
12451     }
12452 
12453     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12454       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12455     else if (isa<ObjCBoxedExpr>(OriginalE))
12456       E->EvaluateForOverflow(Context);
12457     else if (auto Call = dyn_cast<CallExpr>(E))
12458       Exprs.append(Call->arg_begin(), Call->arg_end());
12459     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12460       Exprs.append(Message->arg_begin(), Message->arg_end());
12461   } while (!Exprs.empty());
12462 }
12463 
12464 namespace {
12465 
12466 /// Visitor for expressions which looks for unsequenced operations on the
12467 /// same object.
12468 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12469   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12470 
12471   /// A tree of sequenced regions within an expression. Two regions are
12472   /// unsequenced if one is an ancestor or a descendent of the other. When we
12473   /// finish processing an expression with sequencing, such as a comma
12474   /// expression, we fold its tree nodes into its parent, since they are
12475   /// unsequenced with respect to nodes we will visit later.
12476   class SequenceTree {
12477     struct Value {
12478       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12479       unsigned Parent : 31;
12480       unsigned Merged : 1;
12481     };
12482     SmallVector<Value, 8> Values;
12483 
12484   public:
12485     /// A region within an expression which may be sequenced with respect
12486     /// to some other region.
12487     class Seq {
12488       friend class SequenceTree;
12489 
12490       unsigned Index;
12491 
12492       explicit Seq(unsigned N) : Index(N) {}
12493 
12494     public:
12495       Seq() : Index(0) {}
12496     };
12497 
12498     SequenceTree() { Values.push_back(Value(0)); }
12499     Seq root() const { return Seq(0); }
12500 
12501     /// Create a new sequence of operations, which is an unsequenced
12502     /// subset of \p Parent. This sequence of operations is sequenced with
12503     /// respect to other children of \p Parent.
12504     Seq allocate(Seq Parent) {
12505       Values.push_back(Value(Parent.Index));
12506       return Seq(Values.size() - 1);
12507     }
12508 
12509     /// Merge a sequence of operations into its parent.
12510     void merge(Seq S) {
12511       Values[S.Index].Merged = true;
12512     }
12513 
12514     /// Determine whether two operations are unsequenced. This operation
12515     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12516     /// should have been merged into its parent as appropriate.
12517     bool isUnsequenced(Seq Cur, Seq Old) {
12518       unsigned C = representative(Cur.Index);
12519       unsigned Target = representative(Old.Index);
12520       while (C >= Target) {
12521         if (C == Target)
12522           return true;
12523         C = Values[C].Parent;
12524       }
12525       return false;
12526     }
12527 
12528   private:
12529     /// Pick a representative for a sequence.
12530     unsigned representative(unsigned K) {
12531       if (Values[K].Merged)
12532         // Perform path compression as we go.
12533         return Values[K].Parent = representative(Values[K].Parent);
12534       return K;
12535     }
12536   };
12537 
12538   /// An object for which we can track unsequenced uses.
12539   using Object = const NamedDecl *;
12540 
12541   /// Different flavors of object usage which we track. We only track the
12542   /// least-sequenced usage of each kind.
12543   enum UsageKind {
12544     /// A read of an object. Multiple unsequenced reads are OK.
12545     UK_Use,
12546 
12547     /// A modification of an object which is sequenced before the value
12548     /// computation of the expression, such as ++n in C++.
12549     UK_ModAsValue,
12550 
12551     /// A modification of an object which is not sequenced before the value
12552     /// computation of the expression, such as n++.
12553     UK_ModAsSideEffect,
12554 
12555     UK_Count = UK_ModAsSideEffect + 1
12556   };
12557 
12558   /// Bundle together a sequencing region and the expression corresponding
12559   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12560   struct Usage {
12561     const Expr *UsageExpr;
12562     SequenceTree::Seq Seq;
12563 
12564     Usage() : UsageExpr(nullptr), Seq() {}
12565   };
12566 
12567   struct UsageInfo {
12568     Usage Uses[UK_Count];
12569 
12570     /// Have we issued a diagnostic for this object already?
12571     bool Diagnosed;
12572 
12573     UsageInfo() : Uses(), Diagnosed(false) {}
12574   };
12575   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12576 
12577   Sema &SemaRef;
12578 
12579   /// Sequenced regions within the expression.
12580   SequenceTree Tree;
12581 
12582   /// Declaration modifications and references which we have seen.
12583   UsageInfoMap UsageMap;
12584 
12585   /// The region we are currently within.
12586   SequenceTree::Seq Region;
12587 
12588   /// Filled in with declarations which were modified as a side-effect
12589   /// (that is, post-increment operations).
12590   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12591 
12592   /// Expressions to check later. We defer checking these to reduce
12593   /// stack usage.
12594   SmallVectorImpl<const Expr *> &WorkList;
12595 
12596   /// RAII object wrapping the visitation of a sequenced subexpression of an
12597   /// expression. At the end of this process, the side-effects of the evaluation
12598   /// become sequenced with respect to the value computation of the result, so
12599   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12600   /// UK_ModAsValue.
12601   struct SequencedSubexpression {
12602     SequencedSubexpression(SequenceChecker &Self)
12603       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12604       Self.ModAsSideEffect = &ModAsSideEffect;
12605     }
12606 
12607     ~SequencedSubexpression() {
12608       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12609         // Add a new usage with usage kind UK_ModAsValue, and then restore
12610         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12611         // the previous one was empty).
12612         UsageInfo &UI = Self.UsageMap[M.first];
12613         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12614         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12615         SideEffectUsage = M.second;
12616       }
12617       Self.ModAsSideEffect = OldModAsSideEffect;
12618     }
12619 
12620     SequenceChecker &Self;
12621     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12622     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12623   };
12624 
12625   /// RAII object wrapping the visitation of a subexpression which we might
12626   /// choose to evaluate as a constant. If any subexpression is evaluated and
12627   /// found to be non-constant, this allows us to suppress the evaluation of
12628   /// the outer expression.
12629   class EvaluationTracker {
12630   public:
12631     EvaluationTracker(SequenceChecker &Self)
12632         : Self(Self), Prev(Self.EvalTracker) {
12633       Self.EvalTracker = this;
12634     }
12635 
12636     ~EvaluationTracker() {
12637       Self.EvalTracker = Prev;
12638       if (Prev)
12639         Prev->EvalOK &= EvalOK;
12640     }
12641 
12642     bool evaluate(const Expr *E, bool &Result) {
12643       if (!EvalOK || E->isValueDependent())
12644         return false;
12645       EvalOK = E->EvaluateAsBooleanCondition(
12646           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12647       return EvalOK;
12648     }
12649 
12650   private:
12651     SequenceChecker &Self;
12652     EvaluationTracker *Prev;
12653     bool EvalOK = true;
12654   } *EvalTracker = nullptr;
12655 
12656   /// Find the object which is produced by the specified expression,
12657   /// if any.
12658   Object getObject(const Expr *E, bool Mod) const {
12659     E = E->IgnoreParenCasts();
12660     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12661       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12662         return getObject(UO->getSubExpr(), Mod);
12663     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12664       if (BO->getOpcode() == BO_Comma)
12665         return getObject(BO->getRHS(), Mod);
12666       if (Mod && BO->isAssignmentOp())
12667         return getObject(BO->getLHS(), Mod);
12668     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12669       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12670       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12671         return ME->getMemberDecl();
12672     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12673       // FIXME: If this is a reference, map through to its value.
12674       return DRE->getDecl();
12675     return nullptr;
12676   }
12677 
12678   /// Note that an object \p O was modified or used by an expression
12679   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12680   /// the object \p O as obtained via the \p UsageMap.
12681   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12682     // Get the old usage for the given object and usage kind.
12683     Usage &U = UI.Uses[UK];
12684     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12685       // If we have a modification as side effect and are in a sequenced
12686       // subexpression, save the old Usage so that we can restore it later
12687       // in SequencedSubexpression::~SequencedSubexpression.
12688       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12689         ModAsSideEffect->push_back(std::make_pair(O, U));
12690       // Then record the new usage with the current sequencing region.
12691       U.UsageExpr = UsageExpr;
12692       U.Seq = Region;
12693     }
12694   }
12695 
12696   /// Check whether a modification or use of an object \p O in an expression
12697   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12698   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12699   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12700   /// usage and false we are checking for a mod-use unsequenced usage.
12701   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12702                   UsageKind OtherKind, bool IsModMod) {
12703     if (UI.Diagnosed)
12704       return;
12705 
12706     const Usage &U = UI.Uses[OtherKind];
12707     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12708       return;
12709 
12710     const Expr *Mod = U.UsageExpr;
12711     const Expr *ModOrUse = UsageExpr;
12712     if (OtherKind == UK_Use)
12713       std::swap(Mod, ModOrUse);
12714 
12715     SemaRef.DiagRuntimeBehavior(
12716         Mod->getExprLoc(), {Mod, ModOrUse},
12717         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12718                                : diag::warn_unsequenced_mod_use)
12719             << O << SourceRange(ModOrUse->getExprLoc()));
12720     UI.Diagnosed = true;
12721   }
12722 
12723   // A note on note{Pre, Post}{Use, Mod}:
12724   //
12725   // (It helps to follow the algorithm with an expression such as
12726   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12727   //  operations before C++17 and both are well-defined in C++17).
12728   //
12729   // When visiting a node which uses/modify an object we first call notePreUse
12730   // or notePreMod before visiting its sub-expression(s). At this point the
12731   // children of the current node have not yet been visited and so the eventual
12732   // uses/modifications resulting from the children of the current node have not
12733   // been recorded yet.
12734   //
12735   // We then visit the children of the current node. After that notePostUse or
12736   // notePostMod is called. These will 1) detect an unsequenced modification
12737   // as side effect (as in "k++ + k") and 2) add a new usage with the
12738   // appropriate usage kind.
12739   //
12740   // We also have to be careful that some operation sequences modification as
12741   // side effect as well (for example: || or ,). To account for this we wrap
12742   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12743   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12744   // which record usages which are modifications as side effect, and then
12745   // downgrade them (or more accurately restore the previous usage which was a
12746   // modification as side effect) when exiting the scope of the sequenced
12747   // subexpression.
12748 
12749   void notePreUse(Object O, const Expr *UseExpr) {
12750     UsageInfo &UI = UsageMap[O];
12751     // Uses conflict with other modifications.
12752     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12753   }
12754 
12755   void notePostUse(Object O, const Expr *UseExpr) {
12756     UsageInfo &UI = UsageMap[O];
12757     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12758                /*IsModMod=*/false);
12759     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12760   }
12761 
12762   void notePreMod(Object O, const Expr *ModExpr) {
12763     UsageInfo &UI = UsageMap[O];
12764     // Modifications conflict with other modifications and with uses.
12765     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12766     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12767   }
12768 
12769   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12770     UsageInfo &UI = UsageMap[O];
12771     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12772                /*IsModMod=*/true);
12773     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12774   }
12775 
12776 public:
12777   SequenceChecker(Sema &S, const Expr *E,
12778                   SmallVectorImpl<const Expr *> &WorkList)
12779       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12780     Visit(E);
12781     // Silence a -Wunused-private-field since WorkList is now unused.
12782     // TODO: Evaluate if it can be used, and if not remove it.
12783     (void)this->WorkList;
12784   }
12785 
12786   void VisitStmt(const Stmt *S) {
12787     // Skip all statements which aren't expressions for now.
12788   }
12789 
12790   void VisitExpr(const Expr *E) {
12791     // By default, just recurse to evaluated subexpressions.
12792     Base::VisitStmt(E);
12793   }
12794 
12795   void VisitCastExpr(const CastExpr *E) {
12796     Object O = Object();
12797     if (E->getCastKind() == CK_LValueToRValue)
12798       O = getObject(E->getSubExpr(), false);
12799 
12800     if (O)
12801       notePreUse(O, E);
12802     VisitExpr(E);
12803     if (O)
12804       notePostUse(O, E);
12805   }
12806 
12807   void VisitSequencedExpressions(const Expr *SequencedBefore,
12808                                  const Expr *SequencedAfter) {
12809     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12810     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12811     SequenceTree::Seq OldRegion = Region;
12812 
12813     {
12814       SequencedSubexpression SeqBefore(*this);
12815       Region = BeforeRegion;
12816       Visit(SequencedBefore);
12817     }
12818 
12819     Region = AfterRegion;
12820     Visit(SequencedAfter);
12821 
12822     Region = OldRegion;
12823 
12824     Tree.merge(BeforeRegion);
12825     Tree.merge(AfterRegion);
12826   }
12827 
12828   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12829     // C++17 [expr.sub]p1:
12830     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12831     //   expression E1 is sequenced before the expression E2.
12832     if (SemaRef.getLangOpts().CPlusPlus17)
12833       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12834     else {
12835       Visit(ASE->getLHS());
12836       Visit(ASE->getRHS());
12837     }
12838   }
12839 
12840   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12841   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12842   void VisitBinPtrMem(const BinaryOperator *BO) {
12843     // C++17 [expr.mptr.oper]p4:
12844     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12845     //  the expression E1 is sequenced before the expression E2.
12846     if (SemaRef.getLangOpts().CPlusPlus17)
12847       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12848     else {
12849       Visit(BO->getLHS());
12850       Visit(BO->getRHS());
12851     }
12852   }
12853 
12854   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12855   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12856   void VisitBinShlShr(const BinaryOperator *BO) {
12857     // C++17 [expr.shift]p4:
12858     //  The expression E1 is sequenced before the expression E2.
12859     if (SemaRef.getLangOpts().CPlusPlus17)
12860       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12861     else {
12862       Visit(BO->getLHS());
12863       Visit(BO->getRHS());
12864     }
12865   }
12866 
12867   void VisitBinComma(const BinaryOperator *BO) {
12868     // C++11 [expr.comma]p1:
12869     //   Every value computation and side effect associated with the left
12870     //   expression is sequenced before every value computation and side
12871     //   effect associated with the right expression.
12872     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12873   }
12874 
12875   void VisitBinAssign(const BinaryOperator *BO) {
12876     SequenceTree::Seq RHSRegion;
12877     SequenceTree::Seq LHSRegion;
12878     if (SemaRef.getLangOpts().CPlusPlus17) {
12879       RHSRegion = Tree.allocate(Region);
12880       LHSRegion = Tree.allocate(Region);
12881     } else {
12882       RHSRegion = Region;
12883       LHSRegion = Region;
12884     }
12885     SequenceTree::Seq OldRegion = Region;
12886 
12887     // C++11 [expr.ass]p1:
12888     //  [...] the assignment is sequenced after the value computation
12889     //  of the right and left operands, [...]
12890     //
12891     // so check it before inspecting the operands and update the
12892     // map afterwards.
12893     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12894     if (O)
12895       notePreMod(O, BO);
12896 
12897     if (SemaRef.getLangOpts().CPlusPlus17) {
12898       // C++17 [expr.ass]p1:
12899       //  [...] The right operand is sequenced before the left operand. [...]
12900       {
12901         SequencedSubexpression SeqBefore(*this);
12902         Region = RHSRegion;
12903         Visit(BO->getRHS());
12904       }
12905 
12906       Region = LHSRegion;
12907       Visit(BO->getLHS());
12908 
12909       if (O && isa<CompoundAssignOperator>(BO))
12910         notePostUse(O, BO);
12911 
12912     } else {
12913       // C++11 does not specify any sequencing between the LHS and RHS.
12914       Region = LHSRegion;
12915       Visit(BO->getLHS());
12916 
12917       if (O && isa<CompoundAssignOperator>(BO))
12918         notePostUse(O, BO);
12919 
12920       Region = RHSRegion;
12921       Visit(BO->getRHS());
12922     }
12923 
12924     // C++11 [expr.ass]p1:
12925     //  the assignment is sequenced [...] before the value computation of the
12926     //  assignment expression.
12927     // C11 6.5.16/3 has no such rule.
12928     Region = OldRegion;
12929     if (O)
12930       notePostMod(O, BO,
12931                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12932                                                   : UK_ModAsSideEffect);
12933     if (SemaRef.getLangOpts().CPlusPlus17) {
12934       Tree.merge(RHSRegion);
12935       Tree.merge(LHSRegion);
12936     }
12937   }
12938 
12939   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12940     VisitBinAssign(CAO);
12941   }
12942 
12943   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12944   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12945   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12946     Object O = getObject(UO->getSubExpr(), true);
12947     if (!O)
12948       return VisitExpr(UO);
12949 
12950     notePreMod(O, UO);
12951     Visit(UO->getSubExpr());
12952     // C++11 [expr.pre.incr]p1:
12953     //   the expression ++x is equivalent to x+=1
12954     notePostMod(O, UO,
12955                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12956                                                 : UK_ModAsSideEffect);
12957   }
12958 
12959   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12960   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12961   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12962     Object O = getObject(UO->getSubExpr(), true);
12963     if (!O)
12964       return VisitExpr(UO);
12965 
12966     notePreMod(O, UO);
12967     Visit(UO->getSubExpr());
12968     notePostMod(O, UO, UK_ModAsSideEffect);
12969   }
12970 
12971   void VisitBinLOr(const BinaryOperator *BO) {
12972     // C++11 [expr.log.or]p2:
12973     //  If the second expression is evaluated, every value computation and
12974     //  side effect associated with the first expression is sequenced before
12975     //  every value computation and side effect associated with the
12976     //  second expression.
12977     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12978     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12979     SequenceTree::Seq OldRegion = Region;
12980 
12981     EvaluationTracker Eval(*this);
12982     {
12983       SequencedSubexpression Sequenced(*this);
12984       Region = LHSRegion;
12985       Visit(BO->getLHS());
12986     }
12987 
12988     // C++11 [expr.log.or]p1:
12989     //  [...] the second operand is not evaluated if the first operand
12990     //  evaluates to true.
12991     bool EvalResult = false;
12992     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12993     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12994     if (ShouldVisitRHS) {
12995       Region = RHSRegion;
12996       Visit(BO->getRHS());
12997     }
12998 
12999     Region = OldRegion;
13000     Tree.merge(LHSRegion);
13001     Tree.merge(RHSRegion);
13002   }
13003 
13004   void VisitBinLAnd(const BinaryOperator *BO) {
13005     // C++11 [expr.log.and]p2:
13006     //  If the second expression is evaluated, every value computation and
13007     //  side effect associated with the first expression is sequenced before
13008     //  every value computation and side effect associated with the
13009     //  second expression.
13010     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13011     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13012     SequenceTree::Seq OldRegion = Region;
13013 
13014     EvaluationTracker Eval(*this);
13015     {
13016       SequencedSubexpression Sequenced(*this);
13017       Region = LHSRegion;
13018       Visit(BO->getLHS());
13019     }
13020 
13021     // C++11 [expr.log.and]p1:
13022     //  [...] the second operand is not evaluated if the first operand is false.
13023     bool EvalResult = false;
13024     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13025     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13026     if (ShouldVisitRHS) {
13027       Region = RHSRegion;
13028       Visit(BO->getRHS());
13029     }
13030 
13031     Region = OldRegion;
13032     Tree.merge(LHSRegion);
13033     Tree.merge(RHSRegion);
13034   }
13035 
13036   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13037     // C++11 [expr.cond]p1:
13038     //  [...] Every value computation and side effect associated with the first
13039     //  expression is sequenced before every value computation and side effect
13040     //  associated with the second or third expression.
13041     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13042 
13043     // No sequencing is specified between the true and false expression.
13044     // However since exactly one of both is going to be evaluated we can
13045     // consider them to be sequenced. This is needed to avoid warning on
13046     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13047     // both the true and false expressions because we can't evaluate x.
13048     // This will still allow us to detect an expression like (pre C++17)
13049     // "(x ? y += 1 : y += 2) = y".
13050     //
13051     // We don't wrap the visitation of the true and false expression with
13052     // SequencedSubexpression because we don't want to downgrade modifications
13053     // as side effect in the true and false expressions after the visition
13054     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13055     // not warn between the two "y++", but we should warn between the "y++"
13056     // and the "y".
13057     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13058     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13059     SequenceTree::Seq OldRegion = Region;
13060 
13061     EvaluationTracker Eval(*this);
13062     {
13063       SequencedSubexpression Sequenced(*this);
13064       Region = ConditionRegion;
13065       Visit(CO->getCond());
13066     }
13067 
13068     // C++11 [expr.cond]p1:
13069     // [...] The first expression is contextually converted to bool (Clause 4).
13070     // It is evaluated and if it is true, the result of the conditional
13071     // expression is the value of the second expression, otherwise that of the
13072     // third expression. Only one of the second and third expressions is
13073     // evaluated. [...]
13074     bool EvalResult = false;
13075     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13076     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13077     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13078     if (ShouldVisitTrueExpr) {
13079       Region = TrueRegion;
13080       Visit(CO->getTrueExpr());
13081     }
13082     if (ShouldVisitFalseExpr) {
13083       Region = FalseRegion;
13084       Visit(CO->getFalseExpr());
13085     }
13086 
13087     Region = OldRegion;
13088     Tree.merge(ConditionRegion);
13089     Tree.merge(TrueRegion);
13090     Tree.merge(FalseRegion);
13091   }
13092 
13093   void VisitCallExpr(const CallExpr *CE) {
13094     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13095 
13096     if (CE->isUnevaluatedBuiltinCall(Context))
13097       return;
13098 
13099     // C++11 [intro.execution]p15:
13100     //   When calling a function [...], every value computation and side effect
13101     //   associated with any argument expression, or with the postfix expression
13102     //   designating the called function, is sequenced before execution of every
13103     //   expression or statement in the body of the function [and thus before
13104     //   the value computation of its result].
13105     SequencedSubexpression Sequenced(*this);
13106     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13107       // C++17 [expr.call]p5
13108       //   The postfix-expression is sequenced before each expression in the
13109       //   expression-list and any default argument. [...]
13110       SequenceTree::Seq CalleeRegion;
13111       SequenceTree::Seq OtherRegion;
13112       if (SemaRef.getLangOpts().CPlusPlus17) {
13113         CalleeRegion = Tree.allocate(Region);
13114         OtherRegion = Tree.allocate(Region);
13115       } else {
13116         CalleeRegion = Region;
13117         OtherRegion = Region;
13118       }
13119       SequenceTree::Seq OldRegion = Region;
13120 
13121       // Visit the callee expression first.
13122       Region = CalleeRegion;
13123       if (SemaRef.getLangOpts().CPlusPlus17) {
13124         SequencedSubexpression Sequenced(*this);
13125         Visit(CE->getCallee());
13126       } else {
13127         Visit(CE->getCallee());
13128       }
13129 
13130       // Then visit the argument expressions.
13131       Region = OtherRegion;
13132       for (const Expr *Argument : CE->arguments())
13133         Visit(Argument);
13134 
13135       Region = OldRegion;
13136       if (SemaRef.getLangOpts().CPlusPlus17) {
13137         Tree.merge(CalleeRegion);
13138         Tree.merge(OtherRegion);
13139       }
13140     });
13141   }
13142 
13143   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13144     // C++17 [over.match.oper]p2:
13145     //   [...] the operator notation is first transformed to the equivalent
13146     //   function-call notation as summarized in Table 12 (where @ denotes one
13147     //   of the operators covered in the specified subclause). However, the
13148     //   operands are sequenced in the order prescribed for the built-in
13149     //   operator (Clause 8).
13150     //
13151     // From the above only overloaded binary operators and overloaded call
13152     // operators have sequencing rules in C++17 that we need to handle
13153     // separately.
13154     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13155         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13156       return VisitCallExpr(CXXOCE);
13157 
13158     enum {
13159       NoSequencing,
13160       LHSBeforeRHS,
13161       RHSBeforeLHS,
13162       LHSBeforeRest
13163     } SequencingKind;
13164     switch (CXXOCE->getOperator()) {
13165     case OO_Equal:
13166     case OO_PlusEqual:
13167     case OO_MinusEqual:
13168     case OO_StarEqual:
13169     case OO_SlashEqual:
13170     case OO_PercentEqual:
13171     case OO_CaretEqual:
13172     case OO_AmpEqual:
13173     case OO_PipeEqual:
13174     case OO_LessLessEqual:
13175     case OO_GreaterGreaterEqual:
13176       SequencingKind = RHSBeforeLHS;
13177       break;
13178 
13179     case OO_LessLess:
13180     case OO_GreaterGreater:
13181     case OO_AmpAmp:
13182     case OO_PipePipe:
13183     case OO_Comma:
13184     case OO_ArrowStar:
13185     case OO_Subscript:
13186       SequencingKind = LHSBeforeRHS;
13187       break;
13188 
13189     case OO_Call:
13190       SequencingKind = LHSBeforeRest;
13191       break;
13192 
13193     default:
13194       SequencingKind = NoSequencing;
13195       break;
13196     }
13197 
13198     if (SequencingKind == NoSequencing)
13199       return VisitCallExpr(CXXOCE);
13200 
13201     // This is a call, so all subexpressions are sequenced before the result.
13202     SequencedSubexpression Sequenced(*this);
13203 
13204     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13205       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13206              "Should only get there with C++17 and above!");
13207       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13208              "Should only get there with an overloaded binary operator"
13209              " or an overloaded call operator!");
13210 
13211       if (SequencingKind == LHSBeforeRest) {
13212         assert(CXXOCE->getOperator() == OO_Call &&
13213                "We should only have an overloaded call operator here!");
13214 
13215         // This is very similar to VisitCallExpr, except that we only have the
13216         // C++17 case. The postfix-expression is the first argument of the
13217         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13218         // are in the following arguments.
13219         //
13220         // Note that we intentionally do not visit the callee expression since
13221         // it is just a decayed reference to a function.
13222         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13223         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13224         SequenceTree::Seq OldRegion = Region;
13225 
13226         assert(CXXOCE->getNumArgs() >= 1 &&
13227                "An overloaded call operator must have at least one argument"
13228                " for the postfix-expression!");
13229         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13230         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13231                                           CXXOCE->getNumArgs() - 1);
13232 
13233         // Visit the postfix-expression first.
13234         {
13235           Region = PostfixExprRegion;
13236           SequencedSubexpression Sequenced(*this);
13237           Visit(PostfixExpr);
13238         }
13239 
13240         // Then visit the argument expressions.
13241         Region = ArgsRegion;
13242         for (const Expr *Arg : Args)
13243           Visit(Arg);
13244 
13245         Region = OldRegion;
13246         Tree.merge(PostfixExprRegion);
13247         Tree.merge(ArgsRegion);
13248       } else {
13249         assert(CXXOCE->getNumArgs() == 2 &&
13250                "Should only have two arguments here!");
13251         assert((SequencingKind == LHSBeforeRHS ||
13252                 SequencingKind == RHSBeforeLHS) &&
13253                "Unexpected sequencing kind!");
13254 
13255         // We do not visit the callee expression since it is just a decayed
13256         // reference to a function.
13257         const Expr *E1 = CXXOCE->getArg(0);
13258         const Expr *E2 = CXXOCE->getArg(1);
13259         if (SequencingKind == RHSBeforeLHS)
13260           std::swap(E1, E2);
13261 
13262         return VisitSequencedExpressions(E1, E2);
13263       }
13264     });
13265   }
13266 
13267   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13268     // This is a call, so all subexpressions are sequenced before the result.
13269     SequencedSubexpression Sequenced(*this);
13270 
13271     if (!CCE->isListInitialization())
13272       return VisitExpr(CCE);
13273 
13274     // In C++11, list initializations are sequenced.
13275     SmallVector<SequenceTree::Seq, 32> Elts;
13276     SequenceTree::Seq Parent = Region;
13277     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13278                                               E = CCE->arg_end();
13279          I != E; ++I) {
13280       Region = Tree.allocate(Parent);
13281       Elts.push_back(Region);
13282       Visit(*I);
13283     }
13284 
13285     // Forget that the initializers are sequenced.
13286     Region = Parent;
13287     for (unsigned I = 0; I < Elts.size(); ++I)
13288       Tree.merge(Elts[I]);
13289   }
13290 
13291   void VisitInitListExpr(const InitListExpr *ILE) {
13292     if (!SemaRef.getLangOpts().CPlusPlus11)
13293       return VisitExpr(ILE);
13294 
13295     // In C++11, list initializations are sequenced.
13296     SmallVector<SequenceTree::Seq, 32> Elts;
13297     SequenceTree::Seq Parent = Region;
13298     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13299       const Expr *E = ILE->getInit(I);
13300       if (!E)
13301         continue;
13302       Region = Tree.allocate(Parent);
13303       Elts.push_back(Region);
13304       Visit(E);
13305     }
13306 
13307     // Forget that the initializers are sequenced.
13308     Region = Parent;
13309     for (unsigned I = 0; I < Elts.size(); ++I)
13310       Tree.merge(Elts[I]);
13311   }
13312 };
13313 
13314 } // namespace
13315 
13316 void Sema::CheckUnsequencedOperations(const Expr *E) {
13317   SmallVector<const Expr *, 8> WorkList;
13318   WorkList.push_back(E);
13319   while (!WorkList.empty()) {
13320     const Expr *Item = WorkList.pop_back_val();
13321     SequenceChecker(*this, Item, WorkList);
13322   }
13323 }
13324 
13325 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13326                               bool IsConstexpr) {
13327   llvm::SaveAndRestore<bool> ConstantContext(
13328       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13329   CheckImplicitConversions(E, CheckLoc);
13330   if (!E->isInstantiationDependent())
13331     CheckUnsequencedOperations(E);
13332   if (!IsConstexpr && !E->isValueDependent())
13333     CheckForIntOverflow(E);
13334   DiagnoseMisalignedMembers();
13335 }
13336 
13337 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13338                                        FieldDecl *BitField,
13339                                        Expr *Init) {
13340   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13341 }
13342 
13343 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13344                                          SourceLocation Loc) {
13345   if (!PType->isVariablyModifiedType())
13346     return;
13347   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13348     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13349     return;
13350   }
13351   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13352     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13353     return;
13354   }
13355   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13356     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13357     return;
13358   }
13359 
13360   const ArrayType *AT = S.Context.getAsArrayType(PType);
13361   if (!AT)
13362     return;
13363 
13364   if (AT->getSizeModifier() != ArrayType::Star) {
13365     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13366     return;
13367   }
13368 
13369   S.Diag(Loc, diag::err_array_star_in_function_definition);
13370 }
13371 
13372 /// CheckParmsForFunctionDef - Check that the parameters of the given
13373 /// function are appropriate for the definition of a function. This
13374 /// takes care of any checks that cannot be performed on the
13375 /// declaration itself, e.g., that the types of each of the function
13376 /// parameters are complete.
13377 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13378                                     bool CheckParameterNames) {
13379   bool HasInvalidParm = false;
13380   for (ParmVarDecl *Param : Parameters) {
13381     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13382     // function declarator that is part of a function definition of
13383     // that function shall not have incomplete type.
13384     //
13385     // This is also C++ [dcl.fct]p6.
13386     if (!Param->isInvalidDecl() &&
13387         RequireCompleteType(Param->getLocation(), Param->getType(),
13388                             diag::err_typecheck_decl_incomplete_type)) {
13389       Param->setInvalidDecl();
13390       HasInvalidParm = true;
13391     }
13392 
13393     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13394     // declaration of each parameter shall include an identifier.
13395     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13396         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13397       // Diagnose this as an extension in C17 and earlier.
13398       if (!getLangOpts().C2x)
13399         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13400     }
13401 
13402     // C99 6.7.5.3p12:
13403     //   If the function declarator is not part of a definition of that
13404     //   function, parameters may have incomplete type and may use the [*]
13405     //   notation in their sequences of declarator specifiers to specify
13406     //   variable length array types.
13407     QualType PType = Param->getOriginalType();
13408     // FIXME: This diagnostic should point the '[*]' if source-location
13409     // information is added for it.
13410     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13411 
13412     // If the parameter is a c++ class type and it has to be destructed in the
13413     // callee function, declare the destructor so that it can be called by the
13414     // callee function. Do not perform any direct access check on the dtor here.
13415     if (!Param->isInvalidDecl()) {
13416       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13417         if (!ClassDecl->isInvalidDecl() &&
13418             !ClassDecl->hasIrrelevantDestructor() &&
13419             !ClassDecl->isDependentContext() &&
13420             ClassDecl->isParamDestroyedInCallee()) {
13421           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13422           MarkFunctionReferenced(Param->getLocation(), Destructor);
13423           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13424         }
13425       }
13426     }
13427 
13428     // Parameters with the pass_object_size attribute only need to be marked
13429     // constant at function definitions. Because we lack information about
13430     // whether we're on a declaration or definition when we're instantiating the
13431     // attribute, we need to check for constness here.
13432     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13433       if (!Param->getType().isConstQualified())
13434         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13435             << Attr->getSpelling() << 1;
13436 
13437     // Check for parameter names shadowing fields from the class.
13438     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13439       // The owning context for the parameter should be the function, but we
13440       // want to see if this function's declaration context is a record.
13441       DeclContext *DC = Param->getDeclContext();
13442       if (DC && DC->isFunctionOrMethod()) {
13443         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13444           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13445                                      RD, /*DeclIsField*/ false);
13446       }
13447     }
13448   }
13449 
13450   return HasInvalidParm;
13451 }
13452 
13453 Optional<std::pair<CharUnits, CharUnits>>
13454 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13455 
13456 /// Compute the alignment and offset of the base class object given the
13457 /// derived-to-base cast expression and the alignment and offset of the derived
13458 /// class object.
13459 static std::pair<CharUnits, CharUnits>
13460 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13461                                    CharUnits BaseAlignment, CharUnits Offset,
13462                                    ASTContext &Ctx) {
13463   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13464        ++PathI) {
13465     const CXXBaseSpecifier *Base = *PathI;
13466     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13467     if (Base->isVirtual()) {
13468       // The complete object may have a lower alignment than the non-virtual
13469       // alignment of the base, in which case the base may be misaligned. Choose
13470       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13471       // conservative lower bound of the complete object alignment.
13472       CharUnits NonVirtualAlignment =
13473           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13474       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13475       Offset = CharUnits::Zero();
13476     } else {
13477       const ASTRecordLayout &RL =
13478           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13479       Offset += RL.getBaseClassOffset(BaseDecl);
13480     }
13481     DerivedType = Base->getType();
13482   }
13483 
13484   return std::make_pair(BaseAlignment, Offset);
13485 }
13486 
13487 /// Compute the alignment and offset of a binary additive operator.
13488 static Optional<std::pair<CharUnits, CharUnits>>
13489 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13490                                      bool IsSub, ASTContext &Ctx) {
13491   QualType PointeeType = PtrE->getType()->getPointeeType();
13492 
13493   if (!PointeeType->isConstantSizeType())
13494     return llvm::None;
13495 
13496   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13497 
13498   if (!P)
13499     return llvm::None;
13500 
13501   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13502   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13503     CharUnits Offset = EltSize * IdxRes->getExtValue();
13504     if (IsSub)
13505       Offset = -Offset;
13506     return std::make_pair(P->first, P->second + Offset);
13507   }
13508 
13509   // If the integer expression isn't a constant expression, compute the lower
13510   // bound of the alignment using the alignment and offset of the pointer
13511   // expression and the element size.
13512   return std::make_pair(
13513       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13514       CharUnits::Zero());
13515 }
13516 
13517 /// This helper function takes an lvalue expression and returns the alignment of
13518 /// a VarDecl and a constant offset from the VarDecl.
13519 Optional<std::pair<CharUnits, CharUnits>>
13520 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13521   E = E->IgnoreParens();
13522   switch (E->getStmtClass()) {
13523   default:
13524     break;
13525   case Stmt::CStyleCastExprClass:
13526   case Stmt::CXXStaticCastExprClass:
13527   case Stmt::ImplicitCastExprClass: {
13528     auto *CE = cast<CastExpr>(E);
13529     const Expr *From = CE->getSubExpr();
13530     switch (CE->getCastKind()) {
13531     default:
13532       break;
13533     case CK_NoOp:
13534       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13535     case CK_UncheckedDerivedToBase:
13536     case CK_DerivedToBase: {
13537       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13538       if (!P)
13539         break;
13540       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13541                                                 P->second, Ctx);
13542     }
13543     }
13544     break;
13545   }
13546   case Stmt::ArraySubscriptExprClass: {
13547     auto *ASE = cast<ArraySubscriptExpr>(E);
13548     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13549                                                 false, Ctx);
13550   }
13551   case Stmt::DeclRefExprClass: {
13552     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13553       // FIXME: If VD is captured by copy or is an escaping __block variable,
13554       // use the alignment of VD's type.
13555       if (!VD->getType()->isReferenceType())
13556         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13557       if (VD->hasInit())
13558         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13559     }
13560     break;
13561   }
13562   case Stmt::MemberExprClass: {
13563     auto *ME = cast<MemberExpr>(E);
13564     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13565     if (!FD || FD->getType()->isReferenceType())
13566       break;
13567     Optional<std::pair<CharUnits, CharUnits>> P;
13568     if (ME->isArrow())
13569       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
13570     else
13571       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13572     if (!P)
13573       break;
13574     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13575     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13576     return std::make_pair(P->first,
13577                           P->second + CharUnits::fromQuantity(Offset));
13578   }
13579   case Stmt::UnaryOperatorClass: {
13580     auto *UO = cast<UnaryOperator>(E);
13581     switch (UO->getOpcode()) {
13582     default:
13583       break;
13584     case UO_Deref:
13585       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13586     }
13587     break;
13588   }
13589   case Stmt::BinaryOperatorClass: {
13590     auto *BO = cast<BinaryOperator>(E);
13591     auto Opcode = BO->getOpcode();
13592     switch (Opcode) {
13593     default:
13594       break;
13595     case BO_Comma:
13596       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13597     }
13598     break;
13599   }
13600   }
13601   return llvm::None;
13602 }
13603 
13604 /// This helper function takes a pointer expression and returns the alignment of
13605 /// a VarDecl and a constant offset from the VarDecl.
13606 Optional<std::pair<CharUnits, CharUnits>>
13607 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13608   E = E->IgnoreParens();
13609   switch (E->getStmtClass()) {
13610   default:
13611     break;
13612   case Stmt::CStyleCastExprClass:
13613   case Stmt::CXXStaticCastExprClass:
13614   case Stmt::ImplicitCastExprClass: {
13615     auto *CE = cast<CastExpr>(E);
13616     const Expr *From = CE->getSubExpr();
13617     switch (CE->getCastKind()) {
13618     default:
13619       break;
13620     case CK_NoOp:
13621       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13622     case CK_ArrayToPointerDecay:
13623       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13624     case CK_UncheckedDerivedToBase:
13625     case CK_DerivedToBase: {
13626       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13627       if (!P)
13628         break;
13629       return getDerivedToBaseAlignmentAndOffset(
13630           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13631     }
13632     }
13633     break;
13634   }
13635   case Stmt::CXXThisExprClass: {
13636     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13637     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
13638     return std::make_pair(Alignment, CharUnits::Zero());
13639   }
13640   case Stmt::UnaryOperatorClass: {
13641     auto *UO = cast<UnaryOperator>(E);
13642     if (UO->getOpcode() == UO_AddrOf)
13643       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13644     break;
13645   }
13646   case Stmt::BinaryOperatorClass: {
13647     auto *BO = cast<BinaryOperator>(E);
13648     auto Opcode = BO->getOpcode();
13649     switch (Opcode) {
13650     default:
13651       break;
13652     case BO_Add:
13653     case BO_Sub: {
13654       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13655       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13656         std::swap(LHS, RHS);
13657       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13658                                                   Ctx);
13659     }
13660     case BO_Comma:
13661       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13662     }
13663     break;
13664   }
13665   }
13666   return llvm::None;
13667 }
13668 
13669 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13670   // See if we can compute the alignment of a VarDecl and an offset from it.
13671   Optional<std::pair<CharUnits, CharUnits>> P =
13672       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13673 
13674   if (P)
13675     return P->first.alignmentAtOffset(P->second);
13676 
13677   // If that failed, return the type's alignment.
13678   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13679 }
13680 
13681 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13682 /// pointer cast increases the alignment requirements.
13683 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13684   // This is actually a lot of work to potentially be doing on every
13685   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13686   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13687     return;
13688 
13689   // Ignore dependent types.
13690   if (T->isDependentType() || Op->getType()->isDependentType())
13691     return;
13692 
13693   // Require that the destination be a pointer type.
13694   const PointerType *DestPtr = T->getAs<PointerType>();
13695   if (!DestPtr) return;
13696 
13697   // If the destination has alignment 1, we're done.
13698   QualType DestPointee = DestPtr->getPointeeType();
13699   if (DestPointee->isIncompleteType()) return;
13700   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13701   if (DestAlign.isOne()) return;
13702 
13703   // Require that the source be a pointer type.
13704   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13705   if (!SrcPtr) return;
13706   QualType SrcPointee = SrcPtr->getPointeeType();
13707 
13708   // Explicitly allow casts from cv void*.  We already implicitly
13709   // allowed casts to cv void*, since they have alignment 1.
13710   // Also allow casts involving incomplete types, which implicitly
13711   // includes 'void'.
13712   if (SrcPointee->isIncompleteType()) return;
13713 
13714   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13715 
13716   if (SrcAlign >= DestAlign) return;
13717 
13718   Diag(TRange.getBegin(), diag::warn_cast_align)
13719     << Op->getType() << T
13720     << static_cast<unsigned>(SrcAlign.getQuantity())
13721     << static_cast<unsigned>(DestAlign.getQuantity())
13722     << TRange << Op->getSourceRange();
13723 }
13724 
13725 /// Check whether this array fits the idiom of a size-one tail padded
13726 /// array member of a struct.
13727 ///
13728 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13729 /// commonly used to emulate flexible arrays in C89 code.
13730 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13731                                     const NamedDecl *ND) {
13732   if (Size != 1 || !ND) return false;
13733 
13734   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13735   if (!FD) return false;
13736 
13737   // Don't consider sizes resulting from macro expansions or template argument
13738   // substitution to form C89 tail-padded arrays.
13739 
13740   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13741   while (TInfo) {
13742     TypeLoc TL = TInfo->getTypeLoc();
13743     // Look through typedefs.
13744     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13745       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13746       TInfo = TDL->getTypeSourceInfo();
13747       continue;
13748     }
13749     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13750       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13751       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13752         return false;
13753     }
13754     break;
13755   }
13756 
13757   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13758   if (!RD) return false;
13759   if (RD->isUnion()) return false;
13760   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13761     if (!CRD->isStandardLayout()) return false;
13762   }
13763 
13764   // See if this is the last field decl in the record.
13765   const Decl *D = FD;
13766   while ((D = D->getNextDeclInContext()))
13767     if (isa<FieldDecl>(D))
13768       return false;
13769   return true;
13770 }
13771 
13772 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13773                             const ArraySubscriptExpr *ASE,
13774                             bool AllowOnePastEnd, bool IndexNegated) {
13775   // Already diagnosed by the constant evaluator.
13776   if (isConstantEvaluated())
13777     return;
13778 
13779   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13780   if (IndexExpr->isValueDependent())
13781     return;
13782 
13783   const Type *EffectiveType =
13784       BaseExpr->getType()->getPointeeOrArrayElementType();
13785   BaseExpr = BaseExpr->IgnoreParenCasts();
13786   const ConstantArrayType *ArrayTy =
13787       Context.getAsConstantArrayType(BaseExpr->getType());
13788 
13789   if (!ArrayTy)
13790     return;
13791 
13792   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13793   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13794     return;
13795 
13796   Expr::EvalResult Result;
13797   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13798     return;
13799 
13800   llvm::APSInt index = Result.Val.getInt();
13801   if (IndexNegated)
13802     index = -index;
13803 
13804   const NamedDecl *ND = nullptr;
13805   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13806     ND = DRE->getDecl();
13807   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13808     ND = ME->getMemberDecl();
13809 
13810   if (index.isUnsigned() || !index.isNegative()) {
13811     // It is possible that the type of the base expression after
13812     // IgnoreParenCasts is incomplete, even though the type of the base
13813     // expression before IgnoreParenCasts is complete (see PR39746 for an
13814     // example). In this case we have no information about whether the array
13815     // access exceeds the array bounds. However we can still diagnose an array
13816     // access which precedes the array bounds.
13817     if (BaseType->isIncompleteType())
13818       return;
13819 
13820     llvm::APInt size = ArrayTy->getSize();
13821     if (!size.isStrictlyPositive())
13822       return;
13823 
13824     if (BaseType != EffectiveType) {
13825       // Make sure we're comparing apples to apples when comparing index to size
13826       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13827       uint64_t array_typesize = Context.getTypeSize(BaseType);
13828       // Handle ptrarith_typesize being zero, such as when casting to void*
13829       if (!ptrarith_typesize) ptrarith_typesize = 1;
13830       if (ptrarith_typesize != array_typesize) {
13831         // There's a cast to a different size type involved
13832         uint64_t ratio = array_typesize / ptrarith_typesize;
13833         // TODO: Be smarter about handling cases where array_typesize is not a
13834         // multiple of ptrarith_typesize
13835         if (ptrarith_typesize * ratio == array_typesize)
13836           size *= llvm::APInt(size.getBitWidth(), ratio);
13837       }
13838     }
13839 
13840     if (size.getBitWidth() > index.getBitWidth())
13841       index = index.zext(size.getBitWidth());
13842     else if (size.getBitWidth() < index.getBitWidth())
13843       size = size.zext(index.getBitWidth());
13844 
13845     // For array subscripting the index must be less than size, but for pointer
13846     // arithmetic also allow the index (offset) to be equal to size since
13847     // computing the next address after the end of the array is legal and
13848     // commonly done e.g. in C++ iterators and range-based for loops.
13849     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13850       return;
13851 
13852     // Also don't warn for arrays of size 1 which are members of some
13853     // structure. These are often used to approximate flexible arrays in C89
13854     // code.
13855     if (IsTailPaddedMemberArray(*this, size, ND))
13856       return;
13857 
13858     // Suppress the warning if the subscript expression (as identified by the
13859     // ']' location) and the index expression are both from macro expansions
13860     // within a system header.
13861     if (ASE) {
13862       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13863           ASE->getRBracketLoc());
13864       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13865         SourceLocation IndexLoc =
13866             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13867         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13868           return;
13869       }
13870     }
13871 
13872     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13873     if (ASE)
13874       DiagID = diag::warn_array_index_exceeds_bounds;
13875 
13876     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13877                         PDiag(DiagID) << index.toString(10, true)
13878                                       << size.toString(10, true)
13879                                       << (unsigned)size.getLimitedValue(~0U)
13880                                       << IndexExpr->getSourceRange());
13881   } else {
13882     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13883     if (!ASE) {
13884       DiagID = diag::warn_ptr_arith_precedes_bounds;
13885       if (index.isNegative()) index = -index;
13886     }
13887 
13888     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13889                         PDiag(DiagID) << index.toString(10, true)
13890                                       << IndexExpr->getSourceRange());
13891   }
13892 
13893   if (!ND) {
13894     // Try harder to find a NamedDecl to point at in the note.
13895     while (const ArraySubscriptExpr *ASE =
13896            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13897       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13898     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13899       ND = DRE->getDecl();
13900     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13901       ND = ME->getMemberDecl();
13902   }
13903 
13904   if (ND)
13905     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13906                         PDiag(diag::note_array_declared_here)
13907                             << ND->getDeclName());
13908 }
13909 
13910 void Sema::CheckArrayAccess(const Expr *expr) {
13911   int AllowOnePastEnd = 0;
13912   while (expr) {
13913     expr = expr->IgnoreParenImpCasts();
13914     switch (expr->getStmtClass()) {
13915       case Stmt::ArraySubscriptExprClass: {
13916         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13917         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13918                          AllowOnePastEnd > 0);
13919         expr = ASE->getBase();
13920         break;
13921       }
13922       case Stmt::MemberExprClass: {
13923         expr = cast<MemberExpr>(expr)->getBase();
13924         break;
13925       }
13926       case Stmt::OMPArraySectionExprClass: {
13927         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13928         if (ASE->getLowerBound())
13929           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13930                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13931         return;
13932       }
13933       case Stmt::UnaryOperatorClass: {
13934         // Only unwrap the * and & unary operators
13935         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13936         expr = UO->getSubExpr();
13937         switch (UO->getOpcode()) {
13938           case UO_AddrOf:
13939             AllowOnePastEnd++;
13940             break;
13941           case UO_Deref:
13942             AllowOnePastEnd--;
13943             break;
13944           default:
13945             return;
13946         }
13947         break;
13948       }
13949       case Stmt::ConditionalOperatorClass: {
13950         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13951         if (const Expr *lhs = cond->getLHS())
13952           CheckArrayAccess(lhs);
13953         if (const Expr *rhs = cond->getRHS())
13954           CheckArrayAccess(rhs);
13955         return;
13956       }
13957       case Stmt::CXXOperatorCallExprClass: {
13958         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13959         for (const auto *Arg : OCE->arguments())
13960           CheckArrayAccess(Arg);
13961         return;
13962       }
13963       default:
13964         return;
13965     }
13966   }
13967 }
13968 
13969 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13970 
13971 namespace {
13972 
13973 struct RetainCycleOwner {
13974   VarDecl *Variable = nullptr;
13975   SourceRange Range;
13976   SourceLocation Loc;
13977   bool Indirect = false;
13978 
13979   RetainCycleOwner() = default;
13980 
13981   void setLocsFrom(Expr *e) {
13982     Loc = e->getExprLoc();
13983     Range = e->getSourceRange();
13984   }
13985 };
13986 
13987 } // namespace
13988 
13989 /// Consider whether capturing the given variable can possibly lead to
13990 /// a retain cycle.
13991 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13992   // In ARC, it's captured strongly iff the variable has __strong
13993   // lifetime.  In MRR, it's captured strongly if the variable is
13994   // __block and has an appropriate type.
13995   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13996     return false;
13997 
13998   owner.Variable = var;
13999   if (ref)
14000     owner.setLocsFrom(ref);
14001   return true;
14002 }
14003 
14004 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14005   while (true) {
14006     e = e->IgnoreParens();
14007     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14008       switch (cast->getCastKind()) {
14009       case CK_BitCast:
14010       case CK_LValueBitCast:
14011       case CK_LValueToRValue:
14012       case CK_ARCReclaimReturnedObject:
14013         e = cast->getSubExpr();
14014         continue;
14015 
14016       default:
14017         return false;
14018       }
14019     }
14020 
14021     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14022       ObjCIvarDecl *ivar = ref->getDecl();
14023       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14024         return false;
14025 
14026       // Try to find a retain cycle in the base.
14027       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14028         return false;
14029 
14030       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14031       owner.Indirect = true;
14032       return true;
14033     }
14034 
14035     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14036       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14037       if (!var) return false;
14038       return considerVariable(var, ref, owner);
14039     }
14040 
14041     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14042       if (member->isArrow()) return false;
14043 
14044       // Don't count this as an indirect ownership.
14045       e = member->getBase();
14046       continue;
14047     }
14048 
14049     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14050       // Only pay attention to pseudo-objects on property references.
14051       ObjCPropertyRefExpr *pre
14052         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14053                                               ->IgnoreParens());
14054       if (!pre) return false;
14055       if (pre->isImplicitProperty()) return false;
14056       ObjCPropertyDecl *property = pre->getExplicitProperty();
14057       if (!property->isRetaining() &&
14058           !(property->getPropertyIvarDecl() &&
14059             property->getPropertyIvarDecl()->getType()
14060               .getObjCLifetime() == Qualifiers::OCL_Strong))
14061           return false;
14062 
14063       owner.Indirect = true;
14064       if (pre->isSuperReceiver()) {
14065         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14066         if (!owner.Variable)
14067           return false;
14068         owner.Loc = pre->getLocation();
14069         owner.Range = pre->getSourceRange();
14070         return true;
14071       }
14072       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14073                               ->getSourceExpr());
14074       continue;
14075     }
14076 
14077     // Array ivars?
14078 
14079     return false;
14080   }
14081 }
14082 
14083 namespace {
14084 
14085   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14086     ASTContext &Context;
14087     VarDecl *Variable;
14088     Expr *Capturer = nullptr;
14089     bool VarWillBeReased = false;
14090 
14091     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14092         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14093           Context(Context), Variable(variable) {}
14094 
14095     void VisitDeclRefExpr(DeclRefExpr *ref) {
14096       if (ref->getDecl() == Variable && !Capturer)
14097         Capturer = ref;
14098     }
14099 
14100     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14101       if (Capturer) return;
14102       Visit(ref->getBase());
14103       if (Capturer && ref->isFreeIvar())
14104         Capturer = ref;
14105     }
14106 
14107     void VisitBlockExpr(BlockExpr *block) {
14108       // Look inside nested blocks
14109       if (block->getBlockDecl()->capturesVariable(Variable))
14110         Visit(block->getBlockDecl()->getBody());
14111     }
14112 
14113     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14114       if (Capturer) return;
14115       if (OVE->getSourceExpr())
14116         Visit(OVE->getSourceExpr());
14117     }
14118 
14119     void VisitBinaryOperator(BinaryOperator *BinOp) {
14120       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14121         return;
14122       Expr *LHS = BinOp->getLHS();
14123       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14124         if (DRE->getDecl() != Variable)
14125           return;
14126         if (Expr *RHS = BinOp->getRHS()) {
14127           RHS = RHS->IgnoreParenCasts();
14128           Optional<llvm::APSInt> Value;
14129           VarWillBeReased =
14130               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14131                *Value == 0);
14132         }
14133       }
14134     }
14135   };
14136 
14137 } // namespace
14138 
14139 /// Check whether the given argument is a block which captures a
14140 /// variable.
14141 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14142   assert(owner.Variable && owner.Loc.isValid());
14143 
14144   e = e->IgnoreParenCasts();
14145 
14146   // Look through [^{...} copy] and Block_copy(^{...}).
14147   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14148     Selector Cmd = ME->getSelector();
14149     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14150       e = ME->getInstanceReceiver();
14151       if (!e)
14152         return nullptr;
14153       e = e->IgnoreParenCasts();
14154     }
14155   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14156     if (CE->getNumArgs() == 1) {
14157       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14158       if (Fn) {
14159         const IdentifierInfo *FnI = Fn->getIdentifier();
14160         if (FnI && FnI->isStr("_Block_copy")) {
14161           e = CE->getArg(0)->IgnoreParenCasts();
14162         }
14163       }
14164     }
14165   }
14166 
14167   BlockExpr *block = dyn_cast<BlockExpr>(e);
14168   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14169     return nullptr;
14170 
14171   FindCaptureVisitor visitor(S.Context, owner.Variable);
14172   visitor.Visit(block->getBlockDecl()->getBody());
14173   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14174 }
14175 
14176 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14177                                 RetainCycleOwner &owner) {
14178   assert(capturer);
14179   assert(owner.Variable && owner.Loc.isValid());
14180 
14181   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14182     << owner.Variable << capturer->getSourceRange();
14183   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14184     << owner.Indirect << owner.Range;
14185 }
14186 
14187 /// Check for a keyword selector that starts with the word 'add' or
14188 /// 'set'.
14189 static bool isSetterLikeSelector(Selector sel) {
14190   if (sel.isUnarySelector()) return false;
14191 
14192   StringRef str = sel.getNameForSlot(0);
14193   while (!str.empty() && str.front() == '_') str = str.substr(1);
14194   if (str.startswith("set"))
14195     str = str.substr(3);
14196   else if (str.startswith("add")) {
14197     // Specially allow 'addOperationWithBlock:'.
14198     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14199       return false;
14200     str = str.substr(3);
14201   }
14202   else
14203     return false;
14204 
14205   if (str.empty()) return true;
14206   return !isLowercase(str.front());
14207 }
14208 
14209 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14210                                                     ObjCMessageExpr *Message) {
14211   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14212                                                 Message->getReceiverInterface(),
14213                                                 NSAPI::ClassId_NSMutableArray);
14214   if (!IsMutableArray) {
14215     return None;
14216   }
14217 
14218   Selector Sel = Message->getSelector();
14219 
14220   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14221     S.NSAPIObj->getNSArrayMethodKind(Sel);
14222   if (!MKOpt) {
14223     return None;
14224   }
14225 
14226   NSAPI::NSArrayMethodKind MK = *MKOpt;
14227 
14228   switch (MK) {
14229     case NSAPI::NSMutableArr_addObject:
14230     case NSAPI::NSMutableArr_insertObjectAtIndex:
14231     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14232       return 0;
14233     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14234       return 1;
14235 
14236     default:
14237       return None;
14238   }
14239 
14240   return None;
14241 }
14242 
14243 static
14244 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14245                                                   ObjCMessageExpr *Message) {
14246   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14247                                             Message->getReceiverInterface(),
14248                                             NSAPI::ClassId_NSMutableDictionary);
14249   if (!IsMutableDictionary) {
14250     return None;
14251   }
14252 
14253   Selector Sel = Message->getSelector();
14254 
14255   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14256     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14257   if (!MKOpt) {
14258     return None;
14259   }
14260 
14261   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14262 
14263   switch (MK) {
14264     case NSAPI::NSMutableDict_setObjectForKey:
14265     case NSAPI::NSMutableDict_setValueForKey:
14266     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14267       return 0;
14268 
14269     default:
14270       return None;
14271   }
14272 
14273   return None;
14274 }
14275 
14276 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14277   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14278                                                 Message->getReceiverInterface(),
14279                                                 NSAPI::ClassId_NSMutableSet);
14280 
14281   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14282                                             Message->getReceiverInterface(),
14283                                             NSAPI::ClassId_NSMutableOrderedSet);
14284   if (!IsMutableSet && !IsMutableOrderedSet) {
14285     return None;
14286   }
14287 
14288   Selector Sel = Message->getSelector();
14289 
14290   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14291   if (!MKOpt) {
14292     return None;
14293   }
14294 
14295   NSAPI::NSSetMethodKind MK = *MKOpt;
14296 
14297   switch (MK) {
14298     case NSAPI::NSMutableSet_addObject:
14299     case NSAPI::NSOrderedSet_setObjectAtIndex:
14300     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14301     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14302       return 0;
14303     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14304       return 1;
14305   }
14306 
14307   return None;
14308 }
14309 
14310 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14311   if (!Message->isInstanceMessage()) {
14312     return;
14313   }
14314 
14315   Optional<int> ArgOpt;
14316 
14317   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14318       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14319       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14320     return;
14321   }
14322 
14323   int ArgIndex = *ArgOpt;
14324 
14325   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14326   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14327     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14328   }
14329 
14330   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14331     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14332       if (ArgRE->isObjCSelfExpr()) {
14333         Diag(Message->getSourceRange().getBegin(),
14334              diag::warn_objc_circular_container)
14335           << ArgRE->getDecl() << StringRef("'super'");
14336       }
14337     }
14338   } else {
14339     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14340 
14341     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14342       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14343     }
14344 
14345     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14346       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14347         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14348           ValueDecl *Decl = ReceiverRE->getDecl();
14349           Diag(Message->getSourceRange().getBegin(),
14350                diag::warn_objc_circular_container)
14351             << Decl << Decl;
14352           if (!ArgRE->isObjCSelfExpr()) {
14353             Diag(Decl->getLocation(),
14354                  diag::note_objc_circular_container_declared_here)
14355               << Decl;
14356           }
14357         }
14358       }
14359     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14360       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14361         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14362           ObjCIvarDecl *Decl = IvarRE->getDecl();
14363           Diag(Message->getSourceRange().getBegin(),
14364                diag::warn_objc_circular_container)
14365             << Decl << Decl;
14366           Diag(Decl->getLocation(),
14367                diag::note_objc_circular_container_declared_here)
14368             << Decl;
14369         }
14370       }
14371     }
14372   }
14373 }
14374 
14375 /// Check a message send to see if it's likely to cause a retain cycle.
14376 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14377   // Only check instance methods whose selector looks like a setter.
14378   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14379     return;
14380 
14381   // Try to find a variable that the receiver is strongly owned by.
14382   RetainCycleOwner owner;
14383   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14384     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14385       return;
14386   } else {
14387     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14388     owner.Variable = getCurMethodDecl()->getSelfDecl();
14389     owner.Loc = msg->getSuperLoc();
14390     owner.Range = msg->getSuperLoc();
14391   }
14392 
14393   // Check whether the receiver is captured by any of the arguments.
14394   const ObjCMethodDecl *MD = msg->getMethodDecl();
14395   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14396     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14397       // noescape blocks should not be retained by the method.
14398       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14399         continue;
14400       return diagnoseRetainCycle(*this, capturer, owner);
14401     }
14402   }
14403 }
14404 
14405 /// Check a property assign to see if it's likely to cause a retain cycle.
14406 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14407   RetainCycleOwner owner;
14408   if (!findRetainCycleOwner(*this, receiver, owner))
14409     return;
14410 
14411   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14412     diagnoseRetainCycle(*this, capturer, owner);
14413 }
14414 
14415 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14416   RetainCycleOwner Owner;
14417   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14418     return;
14419 
14420   // Because we don't have an expression for the variable, we have to set the
14421   // location explicitly here.
14422   Owner.Loc = Var->getLocation();
14423   Owner.Range = Var->getSourceRange();
14424 
14425   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14426     diagnoseRetainCycle(*this, Capturer, Owner);
14427 }
14428 
14429 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14430                                      Expr *RHS, bool isProperty) {
14431   // Check if RHS is an Objective-C object literal, which also can get
14432   // immediately zapped in a weak reference.  Note that we explicitly
14433   // allow ObjCStringLiterals, since those are designed to never really die.
14434   RHS = RHS->IgnoreParenImpCasts();
14435 
14436   // This enum needs to match with the 'select' in
14437   // warn_objc_arc_literal_assign (off-by-1).
14438   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14439   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14440     return false;
14441 
14442   S.Diag(Loc, diag::warn_arc_literal_assign)
14443     << (unsigned) Kind
14444     << (isProperty ? 0 : 1)
14445     << RHS->getSourceRange();
14446 
14447   return true;
14448 }
14449 
14450 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14451                                     Qualifiers::ObjCLifetime LT,
14452                                     Expr *RHS, bool isProperty) {
14453   // Strip off any implicit cast added to get to the one ARC-specific.
14454   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14455     if (cast->getCastKind() == CK_ARCConsumeObject) {
14456       S.Diag(Loc, diag::warn_arc_retained_assign)
14457         << (LT == Qualifiers::OCL_ExplicitNone)
14458         << (isProperty ? 0 : 1)
14459         << RHS->getSourceRange();
14460       return true;
14461     }
14462     RHS = cast->getSubExpr();
14463   }
14464 
14465   if (LT == Qualifiers::OCL_Weak &&
14466       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14467     return true;
14468 
14469   return false;
14470 }
14471 
14472 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14473                               QualType LHS, Expr *RHS) {
14474   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14475 
14476   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14477     return false;
14478 
14479   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14480     return true;
14481 
14482   return false;
14483 }
14484 
14485 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14486                               Expr *LHS, Expr *RHS) {
14487   QualType LHSType;
14488   // PropertyRef on LHS type need be directly obtained from
14489   // its declaration as it has a PseudoType.
14490   ObjCPropertyRefExpr *PRE
14491     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14492   if (PRE && !PRE->isImplicitProperty()) {
14493     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14494     if (PD)
14495       LHSType = PD->getType();
14496   }
14497 
14498   if (LHSType.isNull())
14499     LHSType = LHS->getType();
14500 
14501   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14502 
14503   if (LT == Qualifiers::OCL_Weak) {
14504     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14505       getCurFunction()->markSafeWeakUse(LHS);
14506   }
14507 
14508   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14509     return;
14510 
14511   // FIXME. Check for other life times.
14512   if (LT != Qualifiers::OCL_None)
14513     return;
14514 
14515   if (PRE) {
14516     if (PRE->isImplicitProperty())
14517       return;
14518     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14519     if (!PD)
14520       return;
14521 
14522     unsigned Attributes = PD->getPropertyAttributes();
14523     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14524       // when 'assign' attribute was not explicitly specified
14525       // by user, ignore it and rely on property type itself
14526       // for lifetime info.
14527       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14528       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14529           LHSType->isObjCRetainableType())
14530         return;
14531 
14532       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14533         if (cast->getCastKind() == CK_ARCConsumeObject) {
14534           Diag(Loc, diag::warn_arc_retained_property_assign)
14535           << RHS->getSourceRange();
14536           return;
14537         }
14538         RHS = cast->getSubExpr();
14539       }
14540     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14541       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14542         return;
14543     }
14544   }
14545 }
14546 
14547 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14548 
14549 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14550                                         SourceLocation StmtLoc,
14551                                         const NullStmt *Body) {
14552   // Do not warn if the body is a macro that expands to nothing, e.g:
14553   //
14554   // #define CALL(x)
14555   // if (condition)
14556   //   CALL(0);
14557   if (Body->hasLeadingEmptyMacro())
14558     return false;
14559 
14560   // Get line numbers of statement and body.
14561   bool StmtLineInvalid;
14562   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14563                                                       &StmtLineInvalid);
14564   if (StmtLineInvalid)
14565     return false;
14566 
14567   bool BodyLineInvalid;
14568   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14569                                                       &BodyLineInvalid);
14570   if (BodyLineInvalid)
14571     return false;
14572 
14573   // Warn if null statement and body are on the same line.
14574   if (StmtLine != BodyLine)
14575     return false;
14576 
14577   return true;
14578 }
14579 
14580 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14581                                  const Stmt *Body,
14582                                  unsigned DiagID) {
14583   // Since this is a syntactic check, don't emit diagnostic for template
14584   // instantiations, this just adds noise.
14585   if (CurrentInstantiationScope)
14586     return;
14587 
14588   // The body should be a null statement.
14589   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14590   if (!NBody)
14591     return;
14592 
14593   // Do the usual checks.
14594   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14595     return;
14596 
14597   Diag(NBody->getSemiLoc(), DiagID);
14598   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14599 }
14600 
14601 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14602                                  const Stmt *PossibleBody) {
14603   assert(!CurrentInstantiationScope); // Ensured by caller
14604 
14605   SourceLocation StmtLoc;
14606   const Stmt *Body;
14607   unsigned DiagID;
14608   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14609     StmtLoc = FS->getRParenLoc();
14610     Body = FS->getBody();
14611     DiagID = diag::warn_empty_for_body;
14612   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14613     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14614     Body = WS->getBody();
14615     DiagID = diag::warn_empty_while_body;
14616   } else
14617     return; // Neither `for' nor `while'.
14618 
14619   // The body should be a null statement.
14620   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14621   if (!NBody)
14622     return;
14623 
14624   // Skip expensive checks if diagnostic is disabled.
14625   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14626     return;
14627 
14628   // Do the usual checks.
14629   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14630     return;
14631 
14632   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14633   // noise level low, emit diagnostics only if for/while is followed by a
14634   // CompoundStmt, e.g.:
14635   //    for (int i = 0; i < n; i++);
14636   //    {
14637   //      a(i);
14638   //    }
14639   // or if for/while is followed by a statement with more indentation
14640   // than for/while itself:
14641   //    for (int i = 0; i < n; i++);
14642   //      a(i);
14643   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14644   if (!ProbableTypo) {
14645     bool BodyColInvalid;
14646     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14647         PossibleBody->getBeginLoc(), &BodyColInvalid);
14648     if (BodyColInvalid)
14649       return;
14650 
14651     bool StmtColInvalid;
14652     unsigned StmtCol =
14653         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14654     if (StmtColInvalid)
14655       return;
14656 
14657     if (BodyCol > StmtCol)
14658       ProbableTypo = true;
14659   }
14660 
14661   if (ProbableTypo) {
14662     Diag(NBody->getSemiLoc(), DiagID);
14663     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14664   }
14665 }
14666 
14667 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14668 
14669 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14670 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14671                              SourceLocation OpLoc) {
14672   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14673     return;
14674 
14675   if (inTemplateInstantiation())
14676     return;
14677 
14678   // Strip parens and casts away.
14679   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14680   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14681 
14682   // Check for a call expression
14683   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14684   if (!CE || CE->getNumArgs() != 1)
14685     return;
14686 
14687   // Check for a call to std::move
14688   if (!CE->isCallToStdMove())
14689     return;
14690 
14691   // Get argument from std::move
14692   RHSExpr = CE->getArg(0);
14693 
14694   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14695   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14696 
14697   // Two DeclRefExpr's, check that the decls are the same.
14698   if (LHSDeclRef && RHSDeclRef) {
14699     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14700       return;
14701     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14702         RHSDeclRef->getDecl()->getCanonicalDecl())
14703       return;
14704 
14705     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14706                                         << LHSExpr->getSourceRange()
14707                                         << RHSExpr->getSourceRange();
14708     return;
14709   }
14710 
14711   // Member variables require a different approach to check for self moves.
14712   // MemberExpr's are the same if every nested MemberExpr refers to the same
14713   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14714   // the base Expr's are CXXThisExpr's.
14715   const Expr *LHSBase = LHSExpr;
14716   const Expr *RHSBase = RHSExpr;
14717   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14718   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14719   if (!LHSME || !RHSME)
14720     return;
14721 
14722   while (LHSME && RHSME) {
14723     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14724         RHSME->getMemberDecl()->getCanonicalDecl())
14725       return;
14726 
14727     LHSBase = LHSME->getBase();
14728     RHSBase = RHSME->getBase();
14729     LHSME = dyn_cast<MemberExpr>(LHSBase);
14730     RHSME = dyn_cast<MemberExpr>(RHSBase);
14731   }
14732 
14733   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14734   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14735   if (LHSDeclRef && RHSDeclRef) {
14736     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14737       return;
14738     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14739         RHSDeclRef->getDecl()->getCanonicalDecl())
14740       return;
14741 
14742     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14743                                         << LHSExpr->getSourceRange()
14744                                         << RHSExpr->getSourceRange();
14745     return;
14746   }
14747 
14748   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14749     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14750                                         << LHSExpr->getSourceRange()
14751                                         << RHSExpr->getSourceRange();
14752 }
14753 
14754 //===--- Layout compatibility ----------------------------------------------//
14755 
14756 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14757 
14758 /// Check if two enumeration types are layout-compatible.
14759 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14760   // C++11 [dcl.enum] p8:
14761   // Two enumeration types are layout-compatible if they have the same
14762   // underlying type.
14763   return ED1->isComplete() && ED2->isComplete() &&
14764          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14765 }
14766 
14767 /// Check if two fields are layout-compatible.
14768 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14769                                FieldDecl *Field2) {
14770   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14771     return false;
14772 
14773   if (Field1->isBitField() != Field2->isBitField())
14774     return false;
14775 
14776   if (Field1->isBitField()) {
14777     // Make sure that the bit-fields are the same length.
14778     unsigned Bits1 = Field1->getBitWidthValue(C);
14779     unsigned Bits2 = Field2->getBitWidthValue(C);
14780 
14781     if (Bits1 != Bits2)
14782       return false;
14783   }
14784 
14785   return true;
14786 }
14787 
14788 /// Check if two standard-layout structs are layout-compatible.
14789 /// (C++11 [class.mem] p17)
14790 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14791                                      RecordDecl *RD2) {
14792   // If both records are C++ classes, check that base classes match.
14793   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14794     // If one of records is a CXXRecordDecl we are in C++ mode,
14795     // thus the other one is a CXXRecordDecl, too.
14796     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14797     // Check number of base classes.
14798     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14799       return false;
14800 
14801     // Check the base classes.
14802     for (CXXRecordDecl::base_class_const_iterator
14803                Base1 = D1CXX->bases_begin(),
14804            BaseEnd1 = D1CXX->bases_end(),
14805               Base2 = D2CXX->bases_begin();
14806          Base1 != BaseEnd1;
14807          ++Base1, ++Base2) {
14808       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14809         return false;
14810     }
14811   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14812     // If only RD2 is a C++ class, it should have zero base classes.
14813     if (D2CXX->getNumBases() > 0)
14814       return false;
14815   }
14816 
14817   // Check the fields.
14818   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14819                              Field2End = RD2->field_end(),
14820                              Field1 = RD1->field_begin(),
14821                              Field1End = RD1->field_end();
14822   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14823     if (!isLayoutCompatible(C, *Field1, *Field2))
14824       return false;
14825   }
14826   if (Field1 != Field1End || Field2 != Field2End)
14827     return false;
14828 
14829   return true;
14830 }
14831 
14832 /// Check if two standard-layout unions are layout-compatible.
14833 /// (C++11 [class.mem] p18)
14834 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14835                                     RecordDecl *RD2) {
14836   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14837   for (auto *Field2 : RD2->fields())
14838     UnmatchedFields.insert(Field2);
14839 
14840   for (auto *Field1 : RD1->fields()) {
14841     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14842         I = UnmatchedFields.begin(),
14843         E = UnmatchedFields.end();
14844 
14845     for ( ; I != E; ++I) {
14846       if (isLayoutCompatible(C, Field1, *I)) {
14847         bool Result = UnmatchedFields.erase(*I);
14848         (void) Result;
14849         assert(Result);
14850         break;
14851       }
14852     }
14853     if (I == E)
14854       return false;
14855   }
14856 
14857   return UnmatchedFields.empty();
14858 }
14859 
14860 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14861                                RecordDecl *RD2) {
14862   if (RD1->isUnion() != RD2->isUnion())
14863     return false;
14864 
14865   if (RD1->isUnion())
14866     return isLayoutCompatibleUnion(C, RD1, RD2);
14867   else
14868     return isLayoutCompatibleStruct(C, RD1, RD2);
14869 }
14870 
14871 /// Check if two types are layout-compatible in C++11 sense.
14872 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14873   if (T1.isNull() || T2.isNull())
14874     return false;
14875 
14876   // C++11 [basic.types] p11:
14877   // If two types T1 and T2 are the same type, then T1 and T2 are
14878   // layout-compatible types.
14879   if (C.hasSameType(T1, T2))
14880     return true;
14881 
14882   T1 = T1.getCanonicalType().getUnqualifiedType();
14883   T2 = T2.getCanonicalType().getUnqualifiedType();
14884 
14885   const Type::TypeClass TC1 = T1->getTypeClass();
14886   const Type::TypeClass TC2 = T2->getTypeClass();
14887 
14888   if (TC1 != TC2)
14889     return false;
14890 
14891   if (TC1 == Type::Enum) {
14892     return isLayoutCompatible(C,
14893                               cast<EnumType>(T1)->getDecl(),
14894                               cast<EnumType>(T2)->getDecl());
14895   } else if (TC1 == Type::Record) {
14896     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14897       return false;
14898 
14899     return isLayoutCompatible(C,
14900                               cast<RecordType>(T1)->getDecl(),
14901                               cast<RecordType>(T2)->getDecl());
14902   }
14903 
14904   return false;
14905 }
14906 
14907 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14908 
14909 /// Given a type tag expression find the type tag itself.
14910 ///
14911 /// \param TypeExpr Type tag expression, as it appears in user's code.
14912 ///
14913 /// \param VD Declaration of an identifier that appears in a type tag.
14914 ///
14915 /// \param MagicValue Type tag magic value.
14916 ///
14917 /// \param isConstantEvaluated wether the evalaution should be performed in
14918 
14919 /// constant context.
14920 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14921                             const ValueDecl **VD, uint64_t *MagicValue,
14922                             bool isConstantEvaluated) {
14923   while(true) {
14924     if (!TypeExpr)
14925       return false;
14926 
14927     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14928 
14929     switch (TypeExpr->getStmtClass()) {
14930     case Stmt::UnaryOperatorClass: {
14931       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14932       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14933         TypeExpr = UO->getSubExpr();
14934         continue;
14935       }
14936       return false;
14937     }
14938 
14939     case Stmt::DeclRefExprClass: {
14940       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14941       *VD = DRE->getDecl();
14942       return true;
14943     }
14944 
14945     case Stmt::IntegerLiteralClass: {
14946       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14947       llvm::APInt MagicValueAPInt = IL->getValue();
14948       if (MagicValueAPInt.getActiveBits() <= 64) {
14949         *MagicValue = MagicValueAPInt.getZExtValue();
14950         return true;
14951       } else
14952         return false;
14953     }
14954 
14955     case Stmt::BinaryConditionalOperatorClass:
14956     case Stmt::ConditionalOperatorClass: {
14957       const AbstractConditionalOperator *ACO =
14958           cast<AbstractConditionalOperator>(TypeExpr);
14959       bool Result;
14960       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14961                                                      isConstantEvaluated)) {
14962         if (Result)
14963           TypeExpr = ACO->getTrueExpr();
14964         else
14965           TypeExpr = ACO->getFalseExpr();
14966         continue;
14967       }
14968       return false;
14969     }
14970 
14971     case Stmt::BinaryOperatorClass: {
14972       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14973       if (BO->getOpcode() == BO_Comma) {
14974         TypeExpr = BO->getRHS();
14975         continue;
14976       }
14977       return false;
14978     }
14979 
14980     default:
14981       return false;
14982     }
14983   }
14984 }
14985 
14986 /// Retrieve the C type corresponding to type tag TypeExpr.
14987 ///
14988 /// \param TypeExpr Expression that specifies a type tag.
14989 ///
14990 /// \param MagicValues Registered magic values.
14991 ///
14992 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14993 ///        kind.
14994 ///
14995 /// \param TypeInfo Information about the corresponding C type.
14996 ///
14997 /// \param isConstantEvaluated wether the evalaution should be performed in
14998 /// constant context.
14999 ///
15000 /// \returns true if the corresponding C type was found.
15001 static bool GetMatchingCType(
15002     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15003     const ASTContext &Ctx,
15004     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15005         *MagicValues,
15006     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15007     bool isConstantEvaluated) {
15008   FoundWrongKind = false;
15009 
15010   // Variable declaration that has type_tag_for_datatype attribute.
15011   const ValueDecl *VD = nullptr;
15012 
15013   uint64_t MagicValue;
15014 
15015   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15016     return false;
15017 
15018   if (VD) {
15019     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15020       if (I->getArgumentKind() != ArgumentKind) {
15021         FoundWrongKind = true;
15022         return false;
15023       }
15024       TypeInfo.Type = I->getMatchingCType();
15025       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15026       TypeInfo.MustBeNull = I->getMustBeNull();
15027       return true;
15028     }
15029     return false;
15030   }
15031 
15032   if (!MagicValues)
15033     return false;
15034 
15035   llvm::DenseMap<Sema::TypeTagMagicValue,
15036                  Sema::TypeTagData>::const_iterator I =
15037       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15038   if (I == MagicValues->end())
15039     return false;
15040 
15041   TypeInfo = I->second;
15042   return true;
15043 }
15044 
15045 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15046                                       uint64_t MagicValue, QualType Type,
15047                                       bool LayoutCompatible,
15048                                       bool MustBeNull) {
15049   if (!TypeTagForDatatypeMagicValues)
15050     TypeTagForDatatypeMagicValues.reset(
15051         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15052 
15053   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15054   (*TypeTagForDatatypeMagicValues)[Magic] =
15055       TypeTagData(Type, LayoutCompatible, MustBeNull);
15056 }
15057 
15058 static bool IsSameCharType(QualType T1, QualType T2) {
15059   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15060   if (!BT1)
15061     return false;
15062 
15063   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15064   if (!BT2)
15065     return false;
15066 
15067   BuiltinType::Kind T1Kind = BT1->getKind();
15068   BuiltinType::Kind T2Kind = BT2->getKind();
15069 
15070   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15071          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15072          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15073          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15074 }
15075 
15076 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15077                                     const ArrayRef<const Expr *> ExprArgs,
15078                                     SourceLocation CallSiteLoc) {
15079   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15080   bool IsPointerAttr = Attr->getIsPointer();
15081 
15082   // Retrieve the argument representing the 'type_tag'.
15083   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15084   if (TypeTagIdxAST >= ExprArgs.size()) {
15085     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15086         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15087     return;
15088   }
15089   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15090   bool FoundWrongKind;
15091   TypeTagData TypeInfo;
15092   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15093                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15094                         TypeInfo, isConstantEvaluated())) {
15095     if (FoundWrongKind)
15096       Diag(TypeTagExpr->getExprLoc(),
15097            diag::warn_type_tag_for_datatype_wrong_kind)
15098         << TypeTagExpr->getSourceRange();
15099     return;
15100   }
15101 
15102   // Retrieve the argument representing the 'arg_idx'.
15103   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15104   if (ArgumentIdxAST >= ExprArgs.size()) {
15105     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15106         << 1 << Attr->getArgumentIdx().getSourceIndex();
15107     return;
15108   }
15109   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15110   if (IsPointerAttr) {
15111     // Skip implicit cast of pointer to `void *' (as a function argument).
15112     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15113       if (ICE->getType()->isVoidPointerType() &&
15114           ICE->getCastKind() == CK_BitCast)
15115         ArgumentExpr = ICE->getSubExpr();
15116   }
15117   QualType ArgumentType = ArgumentExpr->getType();
15118 
15119   // Passing a `void*' pointer shouldn't trigger a warning.
15120   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15121     return;
15122 
15123   if (TypeInfo.MustBeNull) {
15124     // Type tag with matching void type requires a null pointer.
15125     if (!ArgumentExpr->isNullPointerConstant(Context,
15126                                              Expr::NPC_ValueDependentIsNotNull)) {
15127       Diag(ArgumentExpr->getExprLoc(),
15128            diag::warn_type_safety_null_pointer_required)
15129           << ArgumentKind->getName()
15130           << ArgumentExpr->getSourceRange()
15131           << TypeTagExpr->getSourceRange();
15132     }
15133     return;
15134   }
15135 
15136   QualType RequiredType = TypeInfo.Type;
15137   if (IsPointerAttr)
15138     RequiredType = Context.getPointerType(RequiredType);
15139 
15140   bool mismatch = false;
15141   if (!TypeInfo.LayoutCompatible) {
15142     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15143 
15144     // C++11 [basic.fundamental] p1:
15145     // Plain char, signed char, and unsigned char are three distinct types.
15146     //
15147     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15148     // char' depending on the current char signedness mode.
15149     if (mismatch)
15150       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15151                                            RequiredType->getPointeeType())) ||
15152           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15153         mismatch = false;
15154   } else
15155     if (IsPointerAttr)
15156       mismatch = !isLayoutCompatible(Context,
15157                                      ArgumentType->getPointeeType(),
15158                                      RequiredType->getPointeeType());
15159     else
15160       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15161 
15162   if (mismatch)
15163     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15164         << ArgumentType << ArgumentKind
15165         << TypeInfo.LayoutCompatible << RequiredType
15166         << ArgumentExpr->getSourceRange()
15167         << TypeTagExpr->getSourceRange();
15168 }
15169 
15170 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15171                                          CharUnits Alignment) {
15172   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15173 }
15174 
15175 void Sema::DiagnoseMisalignedMembers() {
15176   for (MisalignedMember &m : MisalignedMembers) {
15177     const NamedDecl *ND = m.RD;
15178     if (ND->getName().empty()) {
15179       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15180         ND = TD;
15181     }
15182     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15183         << m.MD << ND << m.E->getSourceRange();
15184   }
15185   MisalignedMembers.clear();
15186 }
15187 
15188 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15189   E = E->IgnoreParens();
15190   if (!T->isPointerType() && !T->isIntegerType())
15191     return;
15192   if (isa<UnaryOperator>(E) &&
15193       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15194     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15195     if (isa<MemberExpr>(Op)) {
15196       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15197       if (MA != MisalignedMembers.end() &&
15198           (T->isIntegerType() ||
15199            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15200                                    Context.getTypeAlignInChars(
15201                                        T->getPointeeType()) <= MA->Alignment))))
15202         MisalignedMembers.erase(MA);
15203     }
15204   }
15205 }
15206 
15207 void Sema::RefersToMemberWithReducedAlignment(
15208     Expr *E,
15209     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15210         Action) {
15211   const auto *ME = dyn_cast<MemberExpr>(E);
15212   if (!ME)
15213     return;
15214 
15215   // No need to check expressions with an __unaligned-qualified type.
15216   if (E->getType().getQualifiers().hasUnaligned())
15217     return;
15218 
15219   // For a chain of MemberExpr like "a.b.c.d" this list
15220   // will keep FieldDecl's like [d, c, b].
15221   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15222   const MemberExpr *TopME = nullptr;
15223   bool AnyIsPacked = false;
15224   do {
15225     QualType BaseType = ME->getBase()->getType();
15226     if (BaseType->isDependentType())
15227       return;
15228     if (ME->isArrow())
15229       BaseType = BaseType->getPointeeType();
15230     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15231     if (RD->isInvalidDecl())
15232       return;
15233 
15234     ValueDecl *MD = ME->getMemberDecl();
15235     auto *FD = dyn_cast<FieldDecl>(MD);
15236     // We do not care about non-data members.
15237     if (!FD || FD->isInvalidDecl())
15238       return;
15239 
15240     AnyIsPacked =
15241         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15242     ReverseMemberChain.push_back(FD);
15243 
15244     TopME = ME;
15245     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15246   } while (ME);
15247   assert(TopME && "We did not compute a topmost MemberExpr!");
15248 
15249   // Not the scope of this diagnostic.
15250   if (!AnyIsPacked)
15251     return;
15252 
15253   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15254   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15255   // TODO: The innermost base of the member expression may be too complicated.
15256   // For now, just disregard these cases. This is left for future
15257   // improvement.
15258   if (!DRE && !isa<CXXThisExpr>(TopBase))
15259       return;
15260 
15261   // Alignment expected by the whole expression.
15262   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15263 
15264   // No need to do anything else with this case.
15265   if (ExpectedAlignment.isOne())
15266     return;
15267 
15268   // Synthesize offset of the whole access.
15269   CharUnits Offset;
15270   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15271        I++) {
15272     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15273   }
15274 
15275   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15276   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15277       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15278 
15279   // The base expression of the innermost MemberExpr may give
15280   // stronger guarantees than the class containing the member.
15281   if (DRE && !TopME->isArrow()) {
15282     const ValueDecl *VD = DRE->getDecl();
15283     if (!VD->getType()->isReferenceType())
15284       CompleteObjectAlignment =
15285           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15286   }
15287 
15288   // Check if the synthesized offset fulfills the alignment.
15289   if (Offset % ExpectedAlignment != 0 ||
15290       // It may fulfill the offset it but the effective alignment may still be
15291       // lower than the expected expression alignment.
15292       CompleteObjectAlignment < ExpectedAlignment) {
15293     // If this happens, we want to determine a sensible culprit of this.
15294     // Intuitively, watching the chain of member expressions from right to
15295     // left, we start with the required alignment (as required by the field
15296     // type) but some packed attribute in that chain has reduced the alignment.
15297     // It may happen that another packed structure increases it again. But if
15298     // we are here such increase has not been enough. So pointing the first
15299     // FieldDecl that either is packed or else its RecordDecl is,
15300     // seems reasonable.
15301     FieldDecl *FD = nullptr;
15302     CharUnits Alignment;
15303     for (FieldDecl *FDI : ReverseMemberChain) {
15304       if (FDI->hasAttr<PackedAttr>() ||
15305           FDI->getParent()->hasAttr<PackedAttr>()) {
15306         FD = FDI;
15307         Alignment = std::min(
15308             Context.getTypeAlignInChars(FD->getType()),
15309             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15310         break;
15311       }
15312     }
15313     assert(FD && "We did not find a packed FieldDecl!");
15314     Action(E, FD->getParent(), FD, Alignment);
15315   }
15316 }
15317 
15318 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15319   using namespace std::placeholders;
15320 
15321   RefersToMemberWithReducedAlignment(
15322       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15323                      _2, _3, _4));
15324 }
15325 
15326 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15327                                             ExprResult CallResult) {
15328   if (checkArgCount(*this, TheCall, 1))
15329     return ExprError();
15330 
15331   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15332   if (MatrixArg.isInvalid())
15333     return MatrixArg;
15334   Expr *Matrix = MatrixArg.get();
15335 
15336   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15337   if (!MType) {
15338     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15339     return ExprError();
15340   }
15341 
15342   // Create returned matrix type by swapping rows and columns of the argument
15343   // matrix type.
15344   QualType ResultType = Context.getConstantMatrixType(
15345       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15346 
15347   // Change the return type to the type of the returned matrix.
15348   TheCall->setType(ResultType);
15349 
15350   // Update call argument to use the possibly converted matrix argument.
15351   TheCall->setArg(0, Matrix);
15352   return CallResult;
15353 }
15354 
15355 // Get and verify the matrix dimensions.
15356 static llvm::Optional<unsigned>
15357 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15358   SourceLocation ErrorPos;
15359   Optional<llvm::APSInt> Value =
15360       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15361   if (!Value) {
15362     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15363         << Name;
15364     return {};
15365   }
15366   uint64_t Dim = Value->getZExtValue();
15367   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15368     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15369         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15370     return {};
15371   }
15372   return Dim;
15373 }
15374 
15375 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15376                                                   ExprResult CallResult) {
15377   if (!getLangOpts().MatrixTypes) {
15378     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15379     return ExprError();
15380   }
15381 
15382   if (checkArgCount(*this, TheCall, 4))
15383     return ExprError();
15384 
15385   unsigned PtrArgIdx = 0;
15386   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15387   Expr *RowsExpr = TheCall->getArg(1);
15388   Expr *ColumnsExpr = TheCall->getArg(2);
15389   Expr *StrideExpr = TheCall->getArg(3);
15390 
15391   bool ArgError = false;
15392 
15393   // Check pointer argument.
15394   {
15395     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15396     if (PtrConv.isInvalid())
15397       return PtrConv;
15398     PtrExpr = PtrConv.get();
15399     TheCall->setArg(0, PtrExpr);
15400     if (PtrExpr->isTypeDependent()) {
15401       TheCall->setType(Context.DependentTy);
15402       return TheCall;
15403     }
15404   }
15405 
15406   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15407   QualType ElementTy;
15408   if (!PtrTy) {
15409     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15410         << PtrArgIdx + 1;
15411     ArgError = true;
15412   } else {
15413     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15414 
15415     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15416       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15417           << PtrArgIdx + 1;
15418       ArgError = true;
15419     }
15420   }
15421 
15422   // Apply default Lvalue conversions and convert the expression to size_t.
15423   auto ApplyArgumentConversions = [this](Expr *E) {
15424     ExprResult Conv = DefaultLvalueConversion(E);
15425     if (Conv.isInvalid())
15426       return Conv;
15427 
15428     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15429   };
15430 
15431   // Apply conversion to row and column expressions.
15432   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15433   if (!RowsConv.isInvalid()) {
15434     RowsExpr = RowsConv.get();
15435     TheCall->setArg(1, RowsExpr);
15436   } else
15437     RowsExpr = nullptr;
15438 
15439   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15440   if (!ColumnsConv.isInvalid()) {
15441     ColumnsExpr = ColumnsConv.get();
15442     TheCall->setArg(2, ColumnsExpr);
15443   } else
15444     ColumnsExpr = nullptr;
15445 
15446   // If any any part of the result matrix type is still pending, just use
15447   // Context.DependentTy, until all parts are resolved.
15448   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15449       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15450     TheCall->setType(Context.DependentTy);
15451     return CallResult;
15452   }
15453 
15454   // Check row and column dimenions.
15455   llvm::Optional<unsigned> MaybeRows;
15456   if (RowsExpr)
15457     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15458 
15459   llvm::Optional<unsigned> MaybeColumns;
15460   if (ColumnsExpr)
15461     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15462 
15463   // Check stride argument.
15464   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15465   if (StrideConv.isInvalid())
15466     return ExprError();
15467   StrideExpr = StrideConv.get();
15468   TheCall->setArg(3, StrideExpr);
15469 
15470   if (MaybeRows) {
15471     if (Optional<llvm::APSInt> Value =
15472             StrideExpr->getIntegerConstantExpr(Context)) {
15473       uint64_t Stride = Value->getZExtValue();
15474       if (Stride < *MaybeRows) {
15475         Diag(StrideExpr->getBeginLoc(),
15476              diag::err_builtin_matrix_stride_too_small);
15477         ArgError = true;
15478       }
15479     }
15480   }
15481 
15482   if (ArgError || !MaybeRows || !MaybeColumns)
15483     return ExprError();
15484 
15485   TheCall->setType(
15486       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15487   return CallResult;
15488 }
15489 
15490 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15491                                                    ExprResult CallResult) {
15492   if (checkArgCount(*this, TheCall, 3))
15493     return ExprError();
15494 
15495   unsigned PtrArgIdx = 1;
15496   Expr *MatrixExpr = TheCall->getArg(0);
15497   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15498   Expr *StrideExpr = TheCall->getArg(2);
15499 
15500   bool ArgError = false;
15501 
15502   {
15503     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15504     if (MatrixConv.isInvalid())
15505       return MatrixConv;
15506     MatrixExpr = MatrixConv.get();
15507     TheCall->setArg(0, MatrixExpr);
15508   }
15509   if (MatrixExpr->isTypeDependent()) {
15510     TheCall->setType(Context.DependentTy);
15511     return TheCall;
15512   }
15513 
15514   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15515   if (!MatrixTy) {
15516     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15517     ArgError = true;
15518   }
15519 
15520   {
15521     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15522     if (PtrConv.isInvalid())
15523       return PtrConv;
15524     PtrExpr = PtrConv.get();
15525     TheCall->setArg(1, PtrExpr);
15526     if (PtrExpr->isTypeDependent()) {
15527       TheCall->setType(Context.DependentTy);
15528       return TheCall;
15529     }
15530   }
15531 
15532   // Check pointer argument.
15533   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15534   if (!PtrTy) {
15535     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15536         << PtrArgIdx + 1;
15537     ArgError = true;
15538   } else {
15539     QualType ElementTy = PtrTy->getPointeeType();
15540     if (ElementTy.isConstQualified()) {
15541       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15542       ArgError = true;
15543     }
15544     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15545     if (MatrixTy &&
15546         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15547       Diag(PtrExpr->getBeginLoc(),
15548            diag::err_builtin_matrix_pointer_arg_mismatch)
15549           << ElementTy << MatrixTy->getElementType();
15550       ArgError = true;
15551     }
15552   }
15553 
15554   // Apply default Lvalue conversions and convert the stride expression to
15555   // size_t.
15556   {
15557     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15558     if (StrideConv.isInvalid())
15559       return StrideConv;
15560 
15561     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15562     if (StrideConv.isInvalid())
15563       return StrideConv;
15564     StrideExpr = StrideConv.get();
15565     TheCall->setArg(2, StrideExpr);
15566   }
15567 
15568   // Check stride argument.
15569   if (MatrixTy) {
15570     if (Optional<llvm::APSInt> Value =
15571             StrideExpr->getIntegerConstantExpr(Context)) {
15572       uint64_t Stride = Value->getZExtValue();
15573       if (Stride < MatrixTy->getNumRows()) {
15574         Diag(StrideExpr->getBeginLoc(),
15575              diag::err_builtin_matrix_stride_too_small);
15576         ArgError = true;
15577       }
15578     }
15579   }
15580 
15581   if (ArgError)
15582     return ExprError();
15583 
15584   return CallResult;
15585 }
15586