xref: /openbsd/gnu/llvm/clang/lib/Sema/SemaChecking.cpp (revision 771fbea0)
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__builtin_classify_type:
1577     if (checkArgCount(*this, TheCall, 1)) return true;
1578     TheCall->setType(Context.IntTy);
1579     break;
1580   case Builtin::BI__builtin_constant_p: {
1581     if (checkArgCount(*this, TheCall, 1)) return true;
1582     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1583     if (Arg.isInvalid()) return true;
1584     TheCall->setArg(0, Arg.get());
1585     TheCall->setType(Context.IntTy);
1586     break;
1587   }
1588   case Builtin::BI__builtin_launder:
1589     return SemaBuiltinLaunder(*this, TheCall);
1590   case Builtin::BI__sync_fetch_and_add:
1591   case Builtin::BI__sync_fetch_and_add_1:
1592   case Builtin::BI__sync_fetch_and_add_2:
1593   case Builtin::BI__sync_fetch_and_add_4:
1594   case Builtin::BI__sync_fetch_and_add_8:
1595   case Builtin::BI__sync_fetch_and_add_16:
1596   case Builtin::BI__sync_fetch_and_sub:
1597   case Builtin::BI__sync_fetch_and_sub_1:
1598   case Builtin::BI__sync_fetch_and_sub_2:
1599   case Builtin::BI__sync_fetch_and_sub_4:
1600   case Builtin::BI__sync_fetch_and_sub_8:
1601   case Builtin::BI__sync_fetch_and_sub_16:
1602   case Builtin::BI__sync_fetch_and_or:
1603   case Builtin::BI__sync_fetch_and_or_1:
1604   case Builtin::BI__sync_fetch_and_or_2:
1605   case Builtin::BI__sync_fetch_and_or_4:
1606   case Builtin::BI__sync_fetch_and_or_8:
1607   case Builtin::BI__sync_fetch_and_or_16:
1608   case Builtin::BI__sync_fetch_and_and:
1609   case Builtin::BI__sync_fetch_and_and_1:
1610   case Builtin::BI__sync_fetch_and_and_2:
1611   case Builtin::BI__sync_fetch_and_and_4:
1612   case Builtin::BI__sync_fetch_and_and_8:
1613   case Builtin::BI__sync_fetch_and_and_16:
1614   case Builtin::BI__sync_fetch_and_xor:
1615   case Builtin::BI__sync_fetch_and_xor_1:
1616   case Builtin::BI__sync_fetch_and_xor_2:
1617   case Builtin::BI__sync_fetch_and_xor_4:
1618   case Builtin::BI__sync_fetch_and_xor_8:
1619   case Builtin::BI__sync_fetch_and_xor_16:
1620   case Builtin::BI__sync_fetch_and_nand:
1621   case Builtin::BI__sync_fetch_and_nand_1:
1622   case Builtin::BI__sync_fetch_and_nand_2:
1623   case Builtin::BI__sync_fetch_and_nand_4:
1624   case Builtin::BI__sync_fetch_and_nand_8:
1625   case Builtin::BI__sync_fetch_and_nand_16:
1626   case Builtin::BI__sync_add_and_fetch:
1627   case Builtin::BI__sync_add_and_fetch_1:
1628   case Builtin::BI__sync_add_and_fetch_2:
1629   case Builtin::BI__sync_add_and_fetch_4:
1630   case Builtin::BI__sync_add_and_fetch_8:
1631   case Builtin::BI__sync_add_and_fetch_16:
1632   case Builtin::BI__sync_sub_and_fetch:
1633   case Builtin::BI__sync_sub_and_fetch_1:
1634   case Builtin::BI__sync_sub_and_fetch_2:
1635   case Builtin::BI__sync_sub_and_fetch_4:
1636   case Builtin::BI__sync_sub_and_fetch_8:
1637   case Builtin::BI__sync_sub_and_fetch_16:
1638   case Builtin::BI__sync_and_and_fetch:
1639   case Builtin::BI__sync_and_and_fetch_1:
1640   case Builtin::BI__sync_and_and_fetch_2:
1641   case Builtin::BI__sync_and_and_fetch_4:
1642   case Builtin::BI__sync_and_and_fetch_8:
1643   case Builtin::BI__sync_and_and_fetch_16:
1644   case Builtin::BI__sync_or_and_fetch:
1645   case Builtin::BI__sync_or_and_fetch_1:
1646   case Builtin::BI__sync_or_and_fetch_2:
1647   case Builtin::BI__sync_or_and_fetch_4:
1648   case Builtin::BI__sync_or_and_fetch_8:
1649   case Builtin::BI__sync_or_and_fetch_16:
1650   case Builtin::BI__sync_xor_and_fetch:
1651   case Builtin::BI__sync_xor_and_fetch_1:
1652   case Builtin::BI__sync_xor_and_fetch_2:
1653   case Builtin::BI__sync_xor_and_fetch_4:
1654   case Builtin::BI__sync_xor_and_fetch_8:
1655   case Builtin::BI__sync_xor_and_fetch_16:
1656   case Builtin::BI__sync_nand_and_fetch:
1657   case Builtin::BI__sync_nand_and_fetch_1:
1658   case Builtin::BI__sync_nand_and_fetch_2:
1659   case Builtin::BI__sync_nand_and_fetch_4:
1660   case Builtin::BI__sync_nand_and_fetch_8:
1661   case Builtin::BI__sync_nand_and_fetch_16:
1662   case Builtin::BI__sync_val_compare_and_swap:
1663   case Builtin::BI__sync_val_compare_and_swap_1:
1664   case Builtin::BI__sync_val_compare_and_swap_2:
1665   case Builtin::BI__sync_val_compare_and_swap_4:
1666   case Builtin::BI__sync_val_compare_and_swap_8:
1667   case Builtin::BI__sync_val_compare_and_swap_16:
1668   case Builtin::BI__sync_bool_compare_and_swap:
1669   case Builtin::BI__sync_bool_compare_and_swap_1:
1670   case Builtin::BI__sync_bool_compare_and_swap_2:
1671   case Builtin::BI__sync_bool_compare_and_swap_4:
1672   case Builtin::BI__sync_bool_compare_and_swap_8:
1673   case Builtin::BI__sync_bool_compare_and_swap_16:
1674   case Builtin::BI__sync_lock_test_and_set:
1675   case Builtin::BI__sync_lock_test_and_set_1:
1676   case Builtin::BI__sync_lock_test_and_set_2:
1677   case Builtin::BI__sync_lock_test_and_set_4:
1678   case Builtin::BI__sync_lock_test_and_set_8:
1679   case Builtin::BI__sync_lock_test_and_set_16:
1680   case Builtin::BI__sync_lock_release:
1681   case Builtin::BI__sync_lock_release_1:
1682   case Builtin::BI__sync_lock_release_2:
1683   case Builtin::BI__sync_lock_release_4:
1684   case Builtin::BI__sync_lock_release_8:
1685   case Builtin::BI__sync_lock_release_16:
1686   case Builtin::BI__sync_swap:
1687   case Builtin::BI__sync_swap_1:
1688   case Builtin::BI__sync_swap_2:
1689   case Builtin::BI__sync_swap_4:
1690   case Builtin::BI__sync_swap_8:
1691   case Builtin::BI__sync_swap_16:
1692     return SemaBuiltinAtomicOverloaded(TheCallResult);
1693   case Builtin::BI__sync_synchronize:
1694     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1695         << TheCall->getCallee()->getSourceRange();
1696     break;
1697   case Builtin::BI__builtin_nontemporal_load:
1698   case Builtin::BI__builtin_nontemporal_store:
1699     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1700   case Builtin::BI__builtin_memcpy_inline: {
1701     clang::Expr *SizeOp = TheCall->getArg(2);
1702     // We warn about copying to or from `nullptr` pointers when `size` is
1703     // greater than 0. When `size` is value dependent we cannot evaluate its
1704     // value so we bail out.
1705     if (SizeOp->isValueDependent())
1706       break;
1707     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1708       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1709       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1710     }
1711     break;
1712   }
1713 #define BUILTIN(ID, TYPE, ATTRS)
1714 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1715   case Builtin::BI##ID: \
1716     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1717 #include "clang/Basic/Builtins.def"
1718   case Builtin::BI__annotation:
1719     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1720       return ExprError();
1721     break;
1722   case Builtin::BI__builtin_annotation:
1723     if (SemaBuiltinAnnotation(*this, TheCall))
1724       return ExprError();
1725     break;
1726   case Builtin::BI__builtin_addressof:
1727     if (SemaBuiltinAddressof(*this, TheCall))
1728       return ExprError();
1729     break;
1730   case Builtin::BI__builtin_is_aligned:
1731   case Builtin::BI__builtin_align_up:
1732   case Builtin::BI__builtin_align_down:
1733     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1734       return ExprError();
1735     break;
1736   case Builtin::BI__builtin_add_overflow:
1737   case Builtin::BI__builtin_sub_overflow:
1738   case Builtin::BI__builtin_mul_overflow:
1739     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1740       return ExprError();
1741     break;
1742   case Builtin::BI__builtin_operator_new:
1743   case Builtin::BI__builtin_operator_delete: {
1744     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1745     ExprResult Res =
1746         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1747     if (Res.isInvalid())
1748       CorrectDelayedTyposInExpr(TheCallResult.get());
1749     return Res;
1750   }
1751   case Builtin::BI__builtin_dump_struct: {
1752     // We first want to ensure we are called with 2 arguments
1753     if (checkArgCount(*this, TheCall, 2))
1754       return ExprError();
1755     // Ensure that the first argument is of type 'struct XX *'
1756     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1757     const QualType PtrArgType = PtrArg->getType();
1758     if (!PtrArgType->isPointerType() ||
1759         !PtrArgType->getPointeeType()->isRecordType()) {
1760       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1761           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1762           << "structure pointer";
1763       return ExprError();
1764     }
1765 
1766     // Ensure that the second argument is of type 'FunctionType'
1767     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1768     const QualType FnPtrArgType = FnPtrArg->getType();
1769     if (!FnPtrArgType->isPointerType()) {
1770       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1771           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1772           << FnPtrArgType << "'int (*)(const char *, ...)'";
1773       return ExprError();
1774     }
1775 
1776     const auto *FuncType =
1777         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1778 
1779     if (!FuncType) {
1780       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1781           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1782           << FnPtrArgType << "'int (*)(const char *, ...)'";
1783       return ExprError();
1784     }
1785 
1786     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1787       if (!FT->getNumParams()) {
1788         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1789             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1790             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1791         return ExprError();
1792       }
1793       QualType PT = FT->getParamType(0);
1794       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1795           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1796           !PT->getPointeeType().isConstQualified()) {
1797         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1798             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1799             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1800         return ExprError();
1801       }
1802     }
1803 
1804     TheCall->setType(Context.IntTy);
1805     break;
1806   }
1807   case Builtin::BI__builtin_expect_with_probability: {
1808     // We first want to ensure we are called with 3 arguments
1809     if (checkArgCount(*this, TheCall, 3))
1810       return ExprError();
1811     // then check probability is constant float in range [0.0, 1.0]
1812     const Expr *ProbArg = TheCall->getArg(2);
1813     SmallVector<PartialDiagnosticAt, 8> Notes;
1814     Expr::EvalResult Eval;
1815     Eval.Diag = &Notes;
1816     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
1817                                           Context)) ||
1818         !Eval.Val.isFloat()) {
1819       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1820           << ProbArg->getSourceRange();
1821       for (const PartialDiagnosticAt &PDiag : Notes)
1822         Diag(PDiag.first, PDiag.second);
1823       return ExprError();
1824     }
1825     llvm::APFloat Probability = Eval.Val.getFloat();
1826     bool LoseInfo = false;
1827     Probability.convert(llvm::APFloat::IEEEdouble(),
1828                         llvm::RoundingMode::Dynamic, &LoseInfo);
1829     if (!(Probability >= llvm::APFloat(0.0) &&
1830           Probability <= llvm::APFloat(1.0))) {
1831       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1832           << ProbArg->getSourceRange();
1833       return ExprError();
1834     }
1835     break;
1836   }
1837   case Builtin::BI__builtin_preserve_access_index:
1838     if (SemaBuiltinPreserveAI(*this, TheCall))
1839       return ExprError();
1840     break;
1841   case Builtin::BI__builtin_call_with_static_chain:
1842     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1843       return ExprError();
1844     break;
1845   case Builtin::BI__exception_code:
1846   case Builtin::BI_exception_code:
1847     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1848                                  diag::err_seh___except_block))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__exception_info:
1852   case Builtin::BI_exception_info:
1853     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1854                                  diag::err_seh___except_filter))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__GetExceptionInfo:
1858     if (checkArgCount(*this, TheCall, 1))
1859       return ExprError();
1860 
1861     if (CheckCXXThrowOperand(
1862             TheCall->getBeginLoc(),
1863             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1864             TheCall))
1865       return ExprError();
1866 
1867     TheCall->setType(Context.VoidPtrTy);
1868     break;
1869   // OpenCL v2.0, s6.13.16 - Pipe functions
1870   case Builtin::BIread_pipe:
1871   case Builtin::BIwrite_pipe:
1872     // Since those two functions are declared with var args, we need a semantic
1873     // check for the argument.
1874     if (SemaBuiltinRWPipe(*this, TheCall))
1875       return ExprError();
1876     break;
1877   case Builtin::BIreserve_read_pipe:
1878   case Builtin::BIreserve_write_pipe:
1879   case Builtin::BIwork_group_reserve_read_pipe:
1880   case Builtin::BIwork_group_reserve_write_pipe:
1881     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1882       return ExprError();
1883     break;
1884   case Builtin::BIsub_group_reserve_read_pipe:
1885   case Builtin::BIsub_group_reserve_write_pipe:
1886     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1887         SemaBuiltinReserveRWPipe(*this, TheCall))
1888       return ExprError();
1889     break;
1890   case Builtin::BIcommit_read_pipe:
1891   case Builtin::BIcommit_write_pipe:
1892   case Builtin::BIwork_group_commit_read_pipe:
1893   case Builtin::BIwork_group_commit_write_pipe:
1894     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1895       return ExprError();
1896     break;
1897   case Builtin::BIsub_group_commit_read_pipe:
1898   case Builtin::BIsub_group_commit_write_pipe:
1899     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1900         SemaBuiltinCommitRWPipe(*this, TheCall))
1901       return ExprError();
1902     break;
1903   case Builtin::BIget_pipe_num_packets:
1904   case Builtin::BIget_pipe_max_packets:
1905     if (SemaBuiltinPipePackets(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIto_global:
1909   case Builtin::BIto_local:
1910   case Builtin::BIto_private:
1911     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1912       return ExprError();
1913     break;
1914   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1915   case Builtin::BIenqueue_kernel:
1916     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1917       return ExprError();
1918     break;
1919   case Builtin::BIget_kernel_work_group_size:
1920   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1921     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1925   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1926     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BI__builtin_os_log_format:
1930     Cleanup.setExprNeedsCleanups(true);
1931     LLVM_FALLTHROUGH;
1932   case Builtin::BI__builtin_os_log_format_buffer_size:
1933     if (SemaBuiltinOSLogFormat(TheCall))
1934       return ExprError();
1935     break;
1936   case Builtin::BI__builtin_frame_address:
1937   case Builtin::BI__builtin_return_address: {
1938     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1939       return ExprError();
1940 
1941     // -Wframe-address warning if non-zero passed to builtin
1942     // return/frame address.
1943     Expr::EvalResult Result;
1944     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1945         Result.Val.getInt() != 0)
1946       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1947           << ((BuiltinID == Builtin::BI__builtin_return_address)
1948                   ? "__builtin_return_address"
1949                   : "__builtin_frame_address")
1950           << TheCall->getSourceRange();
1951     break;
1952   }
1953 
1954   case Builtin::BI__builtin_matrix_transpose:
1955     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1956 
1957   case Builtin::BI__builtin_matrix_column_major_load:
1958     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1959 
1960   case Builtin::BI__builtin_matrix_column_major_store:
1961     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1962   }
1963 
1964   // Since the target specific builtins for each arch overlap, only check those
1965   // of the arch we are compiling for.
1966   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1967     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1968       assert(Context.getAuxTargetInfo() &&
1969              "Aux Target Builtin, but not an aux target?");
1970 
1971       if (CheckTSBuiltinFunctionCall(
1972               *Context.getAuxTargetInfo(),
1973               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1974         return ExprError();
1975     } else {
1976       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1977                                      TheCall))
1978         return ExprError();
1979     }
1980   }
1981 
1982   return TheCallResult;
1983 }
1984 
1985 // Get the valid immediate range for the specified NEON type code.
1986 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1987   NeonTypeFlags Type(t);
1988   int IsQuad = ForceQuad ? true : Type.isQuad();
1989   switch (Type.getEltType()) {
1990   case NeonTypeFlags::Int8:
1991   case NeonTypeFlags::Poly8:
1992     return shift ? 7 : (8 << IsQuad) - 1;
1993   case NeonTypeFlags::Int16:
1994   case NeonTypeFlags::Poly16:
1995     return shift ? 15 : (4 << IsQuad) - 1;
1996   case NeonTypeFlags::Int32:
1997     return shift ? 31 : (2 << IsQuad) - 1;
1998   case NeonTypeFlags::Int64:
1999   case NeonTypeFlags::Poly64:
2000     return shift ? 63 : (1 << IsQuad) - 1;
2001   case NeonTypeFlags::Poly128:
2002     return shift ? 127 : (1 << IsQuad) - 1;
2003   case NeonTypeFlags::Float16:
2004     assert(!shift && "cannot shift float types!");
2005     return (4 << IsQuad) - 1;
2006   case NeonTypeFlags::Float32:
2007     assert(!shift && "cannot shift float types!");
2008     return (2 << IsQuad) - 1;
2009   case NeonTypeFlags::Float64:
2010     assert(!shift && "cannot shift float types!");
2011     return (1 << IsQuad) - 1;
2012   case NeonTypeFlags::BFloat16:
2013     assert(!shift && "cannot shift float types!");
2014     return (4 << IsQuad) - 1;
2015   }
2016   llvm_unreachable("Invalid NeonTypeFlag!");
2017 }
2018 
2019 /// getNeonEltType - Return the QualType corresponding to the elements of
2020 /// the vector type specified by the NeonTypeFlags.  This is used to check
2021 /// the pointer arguments for Neon load/store intrinsics.
2022 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2023                                bool IsPolyUnsigned, bool IsInt64Long) {
2024   switch (Flags.getEltType()) {
2025   case NeonTypeFlags::Int8:
2026     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2027   case NeonTypeFlags::Int16:
2028     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2029   case NeonTypeFlags::Int32:
2030     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2031   case NeonTypeFlags::Int64:
2032     if (IsInt64Long)
2033       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2034     else
2035       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2036                                 : Context.LongLongTy;
2037   case NeonTypeFlags::Poly8:
2038     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2039   case NeonTypeFlags::Poly16:
2040     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2041   case NeonTypeFlags::Poly64:
2042     if (IsInt64Long)
2043       return Context.UnsignedLongTy;
2044     else
2045       return Context.UnsignedLongLongTy;
2046   case NeonTypeFlags::Poly128:
2047     break;
2048   case NeonTypeFlags::Float16:
2049     return Context.HalfTy;
2050   case NeonTypeFlags::Float32:
2051     return Context.FloatTy;
2052   case NeonTypeFlags::Float64:
2053     return Context.DoubleTy;
2054   case NeonTypeFlags::BFloat16:
2055     return Context.BFloat16Ty;
2056   }
2057   llvm_unreachable("Invalid NeonTypeFlag!");
2058 }
2059 
2060 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2061   // Range check SVE intrinsics that take immediate values.
2062   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2063 
2064   switch (BuiltinID) {
2065   default:
2066     return false;
2067 #define GET_SVE_IMMEDIATE_CHECK
2068 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2069 #undef GET_SVE_IMMEDIATE_CHECK
2070   }
2071 
2072   // Perform all the immediate checks for this builtin call.
2073   bool HasError = false;
2074   for (auto &I : ImmChecks) {
2075     int ArgNum, CheckTy, ElementSizeInBits;
2076     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2077 
2078     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2079 
2080     // Function that checks whether the operand (ArgNum) is an immediate
2081     // that is one of the predefined values.
2082     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2083                                    int ErrDiag) -> bool {
2084       // We can't check the value of a dependent argument.
2085       Expr *Arg = TheCall->getArg(ArgNum);
2086       if (Arg->isTypeDependent() || Arg->isValueDependent())
2087         return false;
2088 
2089       // Check constant-ness first.
2090       llvm::APSInt Imm;
2091       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2092         return true;
2093 
2094       if (!CheckImm(Imm.getSExtValue()))
2095         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2096       return false;
2097     };
2098 
2099     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2100     case SVETypeFlags::ImmCheck0_31:
2101       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2102         HasError = true;
2103       break;
2104     case SVETypeFlags::ImmCheck0_13:
2105       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2106         HasError = true;
2107       break;
2108     case SVETypeFlags::ImmCheck1_16:
2109       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2110         HasError = true;
2111       break;
2112     case SVETypeFlags::ImmCheck0_7:
2113       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2114         HasError = true;
2115       break;
2116     case SVETypeFlags::ImmCheckExtract:
2117       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2118                                       (2048 / ElementSizeInBits) - 1))
2119         HasError = true;
2120       break;
2121     case SVETypeFlags::ImmCheckShiftRight:
2122       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2123         HasError = true;
2124       break;
2125     case SVETypeFlags::ImmCheckShiftRightNarrow:
2126       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2127                                       ElementSizeInBits / 2))
2128         HasError = true;
2129       break;
2130     case SVETypeFlags::ImmCheckShiftLeft:
2131       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2132                                       ElementSizeInBits - 1))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheckLaneIndex:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2137                                       (128 / (1 * ElementSizeInBits)) - 1))
2138         HasError = true;
2139       break;
2140     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2141       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2142                                       (128 / (2 * ElementSizeInBits)) - 1))
2143         HasError = true;
2144       break;
2145     case SVETypeFlags::ImmCheckLaneIndexDot:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2147                                       (128 / (4 * ElementSizeInBits)) - 1))
2148         HasError = true;
2149       break;
2150     case SVETypeFlags::ImmCheckComplexRot90_270:
2151       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2152                               diag::err_rotation_argument_to_cadd))
2153         HasError = true;
2154       break;
2155     case SVETypeFlags::ImmCheckComplexRotAll90:
2156       if (CheckImmediateInSet(
2157               [](int64_t V) {
2158                 return V == 0 || V == 90 || V == 180 || V == 270;
2159               },
2160               diag::err_rotation_argument_to_cmla))
2161         HasError = true;
2162       break;
2163     case SVETypeFlags::ImmCheck0_1:
2164       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheck0_2:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheck0_3:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2173         HasError = true;
2174       break;
2175     }
2176   }
2177 
2178   return HasError;
2179 }
2180 
2181 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2182                                         unsigned BuiltinID, CallExpr *TheCall) {
2183   llvm::APSInt Result;
2184   uint64_t mask = 0;
2185   unsigned TV = 0;
2186   int PtrArgNum = -1;
2187   bool HasConstPtr = false;
2188   switch (BuiltinID) {
2189 #define GET_NEON_OVERLOAD_CHECK
2190 #include "clang/Basic/arm_neon.inc"
2191 #include "clang/Basic/arm_fp16.inc"
2192 #undef GET_NEON_OVERLOAD_CHECK
2193   }
2194 
2195   // For NEON intrinsics which are overloaded on vector element type, validate
2196   // the immediate which specifies which variant to emit.
2197   unsigned ImmArg = TheCall->getNumArgs()-1;
2198   if (mask) {
2199     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2200       return true;
2201 
2202     TV = Result.getLimitedValue(64);
2203     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2204       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2205              << TheCall->getArg(ImmArg)->getSourceRange();
2206   }
2207 
2208   if (PtrArgNum >= 0) {
2209     // Check that pointer arguments have the specified type.
2210     Expr *Arg = TheCall->getArg(PtrArgNum);
2211     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2212       Arg = ICE->getSubExpr();
2213     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2214     QualType RHSTy = RHS.get()->getType();
2215 
2216     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2217     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2218                           Arch == llvm::Triple::aarch64_32 ||
2219                           Arch == llvm::Triple::aarch64_be;
2220     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2221     QualType EltTy =
2222         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2223     if (HasConstPtr)
2224       EltTy = EltTy.withConst();
2225     QualType LHSTy = Context.getPointerType(EltTy);
2226     AssignConvertType ConvTy;
2227     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2228     if (RHS.isInvalid())
2229       return true;
2230     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2231                                  RHS.get(), AA_Assigning))
2232       return true;
2233   }
2234 
2235   // For NEON intrinsics which take an immediate value as part of the
2236   // instruction, range check them here.
2237   unsigned i = 0, l = 0, u = 0;
2238   switch (BuiltinID) {
2239   default:
2240     return false;
2241   #define GET_NEON_IMMEDIATE_CHECK
2242   #include "clang/Basic/arm_neon.inc"
2243   #include "clang/Basic/arm_fp16.inc"
2244   #undef GET_NEON_IMMEDIATE_CHECK
2245   }
2246 
2247   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2248 }
2249 
2250 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2251   switch (BuiltinID) {
2252   default:
2253     return false;
2254   #include "clang/Basic/arm_mve_builtin_sema.inc"
2255   }
2256 }
2257 
2258 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2259                                        CallExpr *TheCall) {
2260   bool Err = false;
2261   switch (BuiltinID) {
2262   default:
2263     return false;
2264 #include "clang/Basic/arm_cde_builtin_sema.inc"
2265   }
2266 
2267   if (Err)
2268     return true;
2269 
2270   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2271 }
2272 
2273 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2274                                         const Expr *CoprocArg, bool WantCDE) {
2275   if (isConstantEvaluated())
2276     return false;
2277 
2278   // We can't check the value of a dependent argument.
2279   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2280     return false;
2281 
2282   llvm::APSInt CoprocNoAP;
2283   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2284   (void)IsICE;
2285   assert(IsICE && "Coprocossor immediate is not a constant expression");
2286   int64_t CoprocNo = CoprocNoAP.getExtValue();
2287   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2288 
2289   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2290   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2291 
2292   if (IsCDECoproc != WantCDE)
2293     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2294            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2295 
2296   return false;
2297 }
2298 
2299 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2300                                         unsigned MaxWidth) {
2301   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2302           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2303           BuiltinID == ARM::BI__builtin_arm_strex ||
2304           BuiltinID == ARM::BI__builtin_arm_stlex ||
2305           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2306           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2307           BuiltinID == AArch64::BI__builtin_arm_strex ||
2308           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2309          "unexpected ARM builtin");
2310   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2311                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2312                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2313                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2314 
2315   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2316 
2317   // Ensure that we have the proper number of arguments.
2318   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2319     return true;
2320 
2321   // Inspect the pointer argument of the atomic builtin.  This should always be
2322   // a pointer type, whose element is an integral scalar or pointer type.
2323   // Because it is a pointer type, we don't have to worry about any implicit
2324   // casts here.
2325   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2326   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2327   if (PointerArgRes.isInvalid())
2328     return true;
2329   PointerArg = PointerArgRes.get();
2330 
2331   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2332   if (!pointerType) {
2333     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2334         << PointerArg->getType() << PointerArg->getSourceRange();
2335     return true;
2336   }
2337 
2338   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2339   // task is to insert the appropriate casts into the AST. First work out just
2340   // what the appropriate type is.
2341   QualType ValType = pointerType->getPointeeType();
2342   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2343   if (IsLdrex)
2344     AddrType.addConst();
2345 
2346   // Issue a warning if the cast is dodgy.
2347   CastKind CastNeeded = CK_NoOp;
2348   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2349     CastNeeded = CK_BitCast;
2350     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2351         << PointerArg->getType() << Context.getPointerType(AddrType)
2352         << AA_Passing << PointerArg->getSourceRange();
2353   }
2354 
2355   // Finally, do the cast and replace the argument with the corrected version.
2356   AddrType = Context.getPointerType(AddrType);
2357   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2358   if (PointerArgRes.isInvalid())
2359     return true;
2360   PointerArg = PointerArgRes.get();
2361 
2362   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2363 
2364   // In general, we allow ints, floats and pointers to be loaded and stored.
2365   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2366       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2367     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2368         << PointerArg->getType() << PointerArg->getSourceRange();
2369     return true;
2370   }
2371 
2372   // But ARM doesn't have instructions to deal with 128-bit versions.
2373   if (Context.getTypeSize(ValType) > MaxWidth) {
2374     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2375     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2376         << PointerArg->getType() << PointerArg->getSourceRange();
2377     return true;
2378   }
2379 
2380   switch (ValType.getObjCLifetime()) {
2381   case Qualifiers::OCL_None:
2382   case Qualifiers::OCL_ExplicitNone:
2383     // okay
2384     break;
2385 
2386   case Qualifiers::OCL_Weak:
2387   case Qualifiers::OCL_Strong:
2388   case Qualifiers::OCL_Autoreleasing:
2389     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2390         << ValType << PointerArg->getSourceRange();
2391     return true;
2392   }
2393 
2394   if (IsLdrex) {
2395     TheCall->setType(ValType);
2396     return false;
2397   }
2398 
2399   // Initialize the argument to be stored.
2400   ExprResult ValArg = TheCall->getArg(0);
2401   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2402       Context, ValType, /*consume*/ false);
2403   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2404   if (ValArg.isInvalid())
2405     return true;
2406   TheCall->setArg(0, ValArg.get());
2407 
2408   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2409   // but the custom checker bypasses all default analysis.
2410   TheCall->setType(Context.IntTy);
2411   return false;
2412 }
2413 
2414 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2415                                        CallExpr *TheCall) {
2416   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2417       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2418       BuiltinID == ARM::BI__builtin_arm_strex ||
2419       BuiltinID == ARM::BI__builtin_arm_stlex) {
2420     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2421   }
2422 
2423   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2424     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2425       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2426   }
2427 
2428   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2429       BuiltinID == ARM::BI__builtin_arm_wsr64)
2430     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2431 
2432   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2433       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2434       BuiltinID == ARM::BI__builtin_arm_wsr ||
2435       BuiltinID == ARM::BI__builtin_arm_wsrp)
2436     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2437 
2438   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2439     return true;
2440   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2441     return true;
2442   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2443     return true;
2444 
2445   // For intrinsics which take an immediate value as part of the instruction,
2446   // range check them here.
2447   // FIXME: VFP Intrinsics should error if VFP not present.
2448   switch (BuiltinID) {
2449   default: return false;
2450   case ARM::BI__builtin_arm_ssat:
2451     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2452   case ARM::BI__builtin_arm_usat:
2453     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2454   case ARM::BI__builtin_arm_ssat16:
2455     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2456   case ARM::BI__builtin_arm_usat16:
2457     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2458   case ARM::BI__builtin_arm_vcvtr_f:
2459   case ARM::BI__builtin_arm_vcvtr_d:
2460     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2461   case ARM::BI__builtin_arm_dmb:
2462   case ARM::BI__builtin_arm_dsb:
2463   case ARM::BI__builtin_arm_isb:
2464   case ARM::BI__builtin_arm_dbg:
2465     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2466   case ARM::BI__builtin_arm_cdp:
2467   case ARM::BI__builtin_arm_cdp2:
2468   case ARM::BI__builtin_arm_mcr:
2469   case ARM::BI__builtin_arm_mcr2:
2470   case ARM::BI__builtin_arm_mrc:
2471   case ARM::BI__builtin_arm_mrc2:
2472   case ARM::BI__builtin_arm_mcrr:
2473   case ARM::BI__builtin_arm_mcrr2:
2474   case ARM::BI__builtin_arm_mrrc:
2475   case ARM::BI__builtin_arm_mrrc2:
2476   case ARM::BI__builtin_arm_ldc:
2477   case ARM::BI__builtin_arm_ldcl:
2478   case ARM::BI__builtin_arm_ldc2:
2479   case ARM::BI__builtin_arm_ldc2l:
2480   case ARM::BI__builtin_arm_stc:
2481   case ARM::BI__builtin_arm_stcl:
2482   case ARM::BI__builtin_arm_stc2:
2483   case ARM::BI__builtin_arm_stc2l:
2484     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2485            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2486                                         /*WantCDE*/ false);
2487   }
2488 }
2489 
2490 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2491                                            unsigned BuiltinID,
2492                                            CallExpr *TheCall) {
2493   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2494       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2495       BuiltinID == AArch64::BI__builtin_arm_strex ||
2496       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2497     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2498   }
2499 
2500   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2501     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2502       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2503       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2504       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2505   }
2506 
2507   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2508       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2509     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2510 
2511   // Memory Tagging Extensions (MTE) Intrinsics
2512   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2513       BuiltinID == AArch64::BI__builtin_arm_addg ||
2514       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2515       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2516       BuiltinID == AArch64::BI__builtin_arm_stg ||
2517       BuiltinID == AArch64::BI__builtin_arm_subp) {
2518     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2519   }
2520 
2521   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2522       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2523       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2524       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2525     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2526 
2527   // Only check the valid encoding range. Any constant in this range would be
2528   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2529   // an exception for incorrect registers. This matches MSVC behavior.
2530   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2531       BuiltinID == AArch64::BI_WriteStatusReg)
2532     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2533 
2534   if (BuiltinID == AArch64::BI__getReg)
2535     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2536 
2537   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2538     return true;
2539 
2540   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2541     return true;
2542 
2543   // For intrinsics which take an immediate value as part of the instruction,
2544   // range check them here.
2545   unsigned i = 0, l = 0, u = 0;
2546   switch (BuiltinID) {
2547   default: return false;
2548   case AArch64::BI__builtin_arm_dmb:
2549   case AArch64::BI__builtin_arm_dsb:
2550   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2551   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2552   }
2553 
2554   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2555 }
2556 
2557 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2558                                        CallExpr *TheCall) {
2559   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2560           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2561          "unexpected ARM builtin");
2562 
2563   if (checkArgCount(*this, TheCall, 2))
2564     return true;
2565 
2566   Expr *Arg;
2567   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2568     // The second argument needs to be a constant int
2569     llvm::APSInt Value;
2570     Arg = TheCall->getArg(1);
2571     if (!Arg->isIntegerConstantExpr(Value, Context)) {
2572       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2573           << 2 << Arg->getSourceRange();
2574       return true;
2575     }
2576 
2577     TheCall->setType(Context.UnsignedIntTy);
2578     return false;
2579   }
2580 
2581   // The first argument needs to be a record field access.
2582   // If it is an array element access, we delay decision
2583   // to BPF backend to check whether the access is a
2584   // field access or not.
2585   Arg = TheCall->getArg(0);
2586   if (Arg->getType()->getAsPlaceholderType() ||
2587       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2588        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2589        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2590     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2591         << 1 << Arg->getSourceRange();
2592     return true;
2593   }
2594 
2595   // The second argument needs to be a constant int
2596   Arg = TheCall->getArg(1);
2597   llvm::APSInt Value;
2598   if (!Arg->isIntegerConstantExpr(Value, 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     llvm::APSInt AbortCode(32);
3197     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3198         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3199       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3200              << Arg->getSourceRange();
3201   }
3202 
3203   // For intrinsics which take an immediate value as part of the instruction,
3204   // range check them here.
3205   unsigned i = 0, l = 0, u = 0;
3206   switch (BuiltinID) {
3207   default: return false;
3208   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3209   case SystemZ::BI__builtin_s390_verimb:
3210   case SystemZ::BI__builtin_s390_verimh:
3211   case SystemZ::BI__builtin_s390_verimf:
3212   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3213   case SystemZ::BI__builtin_s390_vfaeb:
3214   case SystemZ::BI__builtin_s390_vfaeh:
3215   case SystemZ::BI__builtin_s390_vfaef:
3216   case SystemZ::BI__builtin_s390_vfaebs:
3217   case SystemZ::BI__builtin_s390_vfaehs:
3218   case SystemZ::BI__builtin_s390_vfaefs:
3219   case SystemZ::BI__builtin_s390_vfaezb:
3220   case SystemZ::BI__builtin_s390_vfaezh:
3221   case SystemZ::BI__builtin_s390_vfaezf:
3222   case SystemZ::BI__builtin_s390_vfaezbs:
3223   case SystemZ::BI__builtin_s390_vfaezhs:
3224   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3225   case SystemZ::BI__builtin_s390_vfisb:
3226   case SystemZ::BI__builtin_s390_vfidb:
3227     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3228            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3229   case SystemZ::BI__builtin_s390_vftcisb:
3230   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3231   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3232   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3233   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3234   case SystemZ::BI__builtin_s390_vstrcb:
3235   case SystemZ::BI__builtin_s390_vstrch:
3236   case SystemZ::BI__builtin_s390_vstrcf:
3237   case SystemZ::BI__builtin_s390_vstrczb:
3238   case SystemZ::BI__builtin_s390_vstrczh:
3239   case SystemZ::BI__builtin_s390_vstrczf:
3240   case SystemZ::BI__builtin_s390_vstrcbs:
3241   case SystemZ::BI__builtin_s390_vstrchs:
3242   case SystemZ::BI__builtin_s390_vstrcfs:
3243   case SystemZ::BI__builtin_s390_vstrczbs:
3244   case SystemZ::BI__builtin_s390_vstrczhs:
3245   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3246   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3247   case SystemZ::BI__builtin_s390_vfminsb:
3248   case SystemZ::BI__builtin_s390_vfmaxsb:
3249   case SystemZ::BI__builtin_s390_vfmindb:
3250   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3251   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3252   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3253   }
3254   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3255 }
3256 
3257 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3258 /// This checks that the target supports __builtin_cpu_supports and
3259 /// that the string argument is constant and valid.
3260 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3261                                    CallExpr *TheCall) {
3262   Expr *Arg = TheCall->getArg(0);
3263 
3264   // Check if the argument is a string literal.
3265   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3266     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3267            << Arg->getSourceRange();
3268 
3269   // Check the contents of the string.
3270   StringRef Feature =
3271       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3272   if (!TI.validateCpuSupports(Feature))
3273     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3274            << Arg->getSourceRange();
3275   return false;
3276 }
3277 
3278 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3279 /// This checks that the target supports __builtin_cpu_is and
3280 /// that the string argument is constant and valid.
3281 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3282   Expr *Arg = TheCall->getArg(0);
3283 
3284   // Check if the argument is a string literal.
3285   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3286     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3287            << Arg->getSourceRange();
3288 
3289   // Check the contents of the string.
3290   StringRef Feature =
3291       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3292   if (!TI.validateCpuIs(Feature))
3293     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3294            << Arg->getSourceRange();
3295   return false;
3296 }
3297 
3298 // Check if the rounding mode is legal.
3299 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3300   // Indicates if this instruction has rounding control or just SAE.
3301   bool HasRC = false;
3302 
3303   unsigned ArgNum = 0;
3304   switch (BuiltinID) {
3305   default:
3306     return false;
3307   case X86::BI__builtin_ia32_vcvttsd2si32:
3308   case X86::BI__builtin_ia32_vcvttsd2si64:
3309   case X86::BI__builtin_ia32_vcvttsd2usi32:
3310   case X86::BI__builtin_ia32_vcvttsd2usi64:
3311   case X86::BI__builtin_ia32_vcvttss2si32:
3312   case X86::BI__builtin_ia32_vcvttss2si64:
3313   case X86::BI__builtin_ia32_vcvttss2usi32:
3314   case X86::BI__builtin_ia32_vcvttss2usi64:
3315     ArgNum = 1;
3316     break;
3317   case X86::BI__builtin_ia32_maxpd512:
3318   case X86::BI__builtin_ia32_maxps512:
3319   case X86::BI__builtin_ia32_minpd512:
3320   case X86::BI__builtin_ia32_minps512:
3321     ArgNum = 2;
3322     break;
3323   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3324   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3325   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3326   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3327   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3328   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3329   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3330   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3331   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3332   case X86::BI__builtin_ia32_exp2pd_mask:
3333   case X86::BI__builtin_ia32_exp2ps_mask:
3334   case X86::BI__builtin_ia32_getexppd512_mask:
3335   case X86::BI__builtin_ia32_getexpps512_mask:
3336   case X86::BI__builtin_ia32_rcp28pd_mask:
3337   case X86::BI__builtin_ia32_rcp28ps_mask:
3338   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3339   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3340   case X86::BI__builtin_ia32_vcomisd:
3341   case X86::BI__builtin_ia32_vcomiss:
3342   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3343     ArgNum = 3;
3344     break;
3345   case X86::BI__builtin_ia32_cmppd512_mask:
3346   case X86::BI__builtin_ia32_cmpps512_mask:
3347   case X86::BI__builtin_ia32_cmpsd_mask:
3348   case X86::BI__builtin_ia32_cmpss_mask:
3349   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3350   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3351   case X86::BI__builtin_ia32_getexpss128_round_mask:
3352   case X86::BI__builtin_ia32_getmantpd512_mask:
3353   case X86::BI__builtin_ia32_getmantps512_mask:
3354   case X86::BI__builtin_ia32_maxsd_round_mask:
3355   case X86::BI__builtin_ia32_maxss_round_mask:
3356   case X86::BI__builtin_ia32_minsd_round_mask:
3357   case X86::BI__builtin_ia32_minss_round_mask:
3358   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3359   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3360   case X86::BI__builtin_ia32_reducepd512_mask:
3361   case X86::BI__builtin_ia32_reduceps512_mask:
3362   case X86::BI__builtin_ia32_rndscalepd_mask:
3363   case X86::BI__builtin_ia32_rndscaleps_mask:
3364   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3365   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3366     ArgNum = 4;
3367     break;
3368   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3369   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3370   case X86::BI__builtin_ia32_fixupimmps512_mask:
3371   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3372   case X86::BI__builtin_ia32_fixupimmsd_mask:
3373   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3374   case X86::BI__builtin_ia32_fixupimmss_mask:
3375   case X86::BI__builtin_ia32_fixupimmss_maskz:
3376   case X86::BI__builtin_ia32_getmantsd_round_mask:
3377   case X86::BI__builtin_ia32_getmantss_round_mask:
3378   case X86::BI__builtin_ia32_rangepd512_mask:
3379   case X86::BI__builtin_ia32_rangeps512_mask:
3380   case X86::BI__builtin_ia32_rangesd128_round_mask:
3381   case X86::BI__builtin_ia32_rangess128_round_mask:
3382   case X86::BI__builtin_ia32_reducesd_mask:
3383   case X86::BI__builtin_ia32_reducess_mask:
3384   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3385   case X86::BI__builtin_ia32_rndscaless_round_mask:
3386     ArgNum = 5;
3387     break;
3388   case X86::BI__builtin_ia32_vcvtsd2si64:
3389   case X86::BI__builtin_ia32_vcvtsd2si32:
3390   case X86::BI__builtin_ia32_vcvtsd2usi32:
3391   case X86::BI__builtin_ia32_vcvtsd2usi64:
3392   case X86::BI__builtin_ia32_vcvtss2si32:
3393   case X86::BI__builtin_ia32_vcvtss2si64:
3394   case X86::BI__builtin_ia32_vcvtss2usi32:
3395   case X86::BI__builtin_ia32_vcvtss2usi64:
3396   case X86::BI__builtin_ia32_sqrtpd512:
3397   case X86::BI__builtin_ia32_sqrtps512:
3398     ArgNum = 1;
3399     HasRC = true;
3400     break;
3401   case X86::BI__builtin_ia32_addpd512:
3402   case X86::BI__builtin_ia32_addps512:
3403   case X86::BI__builtin_ia32_divpd512:
3404   case X86::BI__builtin_ia32_divps512:
3405   case X86::BI__builtin_ia32_mulpd512:
3406   case X86::BI__builtin_ia32_mulps512:
3407   case X86::BI__builtin_ia32_subpd512:
3408   case X86::BI__builtin_ia32_subps512:
3409   case X86::BI__builtin_ia32_cvtsi2sd64:
3410   case X86::BI__builtin_ia32_cvtsi2ss32:
3411   case X86::BI__builtin_ia32_cvtsi2ss64:
3412   case X86::BI__builtin_ia32_cvtusi2sd64:
3413   case X86::BI__builtin_ia32_cvtusi2ss32:
3414   case X86::BI__builtin_ia32_cvtusi2ss64:
3415     ArgNum = 2;
3416     HasRC = true;
3417     break;
3418   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3419   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3420   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3421   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3422   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3423   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3424   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3425   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3426   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3427   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3428   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3429   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3430   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3431   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3432   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3433     ArgNum = 3;
3434     HasRC = true;
3435     break;
3436   case X86::BI__builtin_ia32_addss_round_mask:
3437   case X86::BI__builtin_ia32_addsd_round_mask:
3438   case X86::BI__builtin_ia32_divss_round_mask:
3439   case X86::BI__builtin_ia32_divsd_round_mask:
3440   case X86::BI__builtin_ia32_mulss_round_mask:
3441   case X86::BI__builtin_ia32_mulsd_round_mask:
3442   case X86::BI__builtin_ia32_subss_round_mask:
3443   case X86::BI__builtin_ia32_subsd_round_mask:
3444   case X86::BI__builtin_ia32_scalefpd512_mask:
3445   case X86::BI__builtin_ia32_scalefps512_mask:
3446   case X86::BI__builtin_ia32_scalefsd_round_mask:
3447   case X86::BI__builtin_ia32_scalefss_round_mask:
3448   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3449   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3450   case X86::BI__builtin_ia32_sqrtss_round_mask:
3451   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3452   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3453   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3454   case X86::BI__builtin_ia32_vfmaddss3_mask:
3455   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3456   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3457   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3458   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3459   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3460   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3461   case X86::BI__builtin_ia32_vfmaddps512_mask:
3462   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3463   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3464   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3465   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3466   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3467   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3468   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3469   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3470   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3471   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3472   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3473     ArgNum = 4;
3474     HasRC = true;
3475     break;
3476   }
3477 
3478   llvm::APSInt Result;
3479 
3480   // We can't check the value of a dependent argument.
3481   Expr *Arg = TheCall->getArg(ArgNum);
3482   if (Arg->isTypeDependent() || Arg->isValueDependent())
3483     return false;
3484 
3485   // Check constant-ness first.
3486   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3487     return true;
3488 
3489   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3490   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3491   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3492   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3493   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3494       Result == 8/*ROUND_NO_EXC*/ ||
3495       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3496       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3497     return false;
3498 
3499   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3500          << Arg->getSourceRange();
3501 }
3502 
3503 // Check if the gather/scatter scale is legal.
3504 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3505                                              CallExpr *TheCall) {
3506   unsigned ArgNum = 0;
3507   switch (BuiltinID) {
3508   default:
3509     return false;
3510   case X86::BI__builtin_ia32_gatherpfdpd:
3511   case X86::BI__builtin_ia32_gatherpfdps:
3512   case X86::BI__builtin_ia32_gatherpfqpd:
3513   case X86::BI__builtin_ia32_gatherpfqps:
3514   case X86::BI__builtin_ia32_scatterpfdpd:
3515   case X86::BI__builtin_ia32_scatterpfdps:
3516   case X86::BI__builtin_ia32_scatterpfqpd:
3517   case X86::BI__builtin_ia32_scatterpfqps:
3518     ArgNum = 3;
3519     break;
3520   case X86::BI__builtin_ia32_gatherd_pd:
3521   case X86::BI__builtin_ia32_gatherd_pd256:
3522   case X86::BI__builtin_ia32_gatherq_pd:
3523   case X86::BI__builtin_ia32_gatherq_pd256:
3524   case X86::BI__builtin_ia32_gatherd_ps:
3525   case X86::BI__builtin_ia32_gatherd_ps256:
3526   case X86::BI__builtin_ia32_gatherq_ps:
3527   case X86::BI__builtin_ia32_gatherq_ps256:
3528   case X86::BI__builtin_ia32_gatherd_q:
3529   case X86::BI__builtin_ia32_gatherd_q256:
3530   case X86::BI__builtin_ia32_gatherq_q:
3531   case X86::BI__builtin_ia32_gatherq_q256:
3532   case X86::BI__builtin_ia32_gatherd_d:
3533   case X86::BI__builtin_ia32_gatherd_d256:
3534   case X86::BI__builtin_ia32_gatherq_d:
3535   case X86::BI__builtin_ia32_gatherq_d256:
3536   case X86::BI__builtin_ia32_gather3div2df:
3537   case X86::BI__builtin_ia32_gather3div2di:
3538   case X86::BI__builtin_ia32_gather3div4df:
3539   case X86::BI__builtin_ia32_gather3div4di:
3540   case X86::BI__builtin_ia32_gather3div4sf:
3541   case X86::BI__builtin_ia32_gather3div4si:
3542   case X86::BI__builtin_ia32_gather3div8sf:
3543   case X86::BI__builtin_ia32_gather3div8si:
3544   case X86::BI__builtin_ia32_gather3siv2df:
3545   case X86::BI__builtin_ia32_gather3siv2di:
3546   case X86::BI__builtin_ia32_gather3siv4df:
3547   case X86::BI__builtin_ia32_gather3siv4di:
3548   case X86::BI__builtin_ia32_gather3siv4sf:
3549   case X86::BI__builtin_ia32_gather3siv4si:
3550   case X86::BI__builtin_ia32_gather3siv8sf:
3551   case X86::BI__builtin_ia32_gather3siv8si:
3552   case X86::BI__builtin_ia32_gathersiv8df:
3553   case X86::BI__builtin_ia32_gathersiv16sf:
3554   case X86::BI__builtin_ia32_gatherdiv8df:
3555   case X86::BI__builtin_ia32_gatherdiv16sf:
3556   case X86::BI__builtin_ia32_gathersiv8di:
3557   case X86::BI__builtin_ia32_gathersiv16si:
3558   case X86::BI__builtin_ia32_gatherdiv8di:
3559   case X86::BI__builtin_ia32_gatherdiv16si:
3560   case X86::BI__builtin_ia32_scatterdiv2df:
3561   case X86::BI__builtin_ia32_scatterdiv2di:
3562   case X86::BI__builtin_ia32_scatterdiv4df:
3563   case X86::BI__builtin_ia32_scatterdiv4di:
3564   case X86::BI__builtin_ia32_scatterdiv4sf:
3565   case X86::BI__builtin_ia32_scatterdiv4si:
3566   case X86::BI__builtin_ia32_scatterdiv8sf:
3567   case X86::BI__builtin_ia32_scatterdiv8si:
3568   case X86::BI__builtin_ia32_scattersiv2df:
3569   case X86::BI__builtin_ia32_scattersiv2di:
3570   case X86::BI__builtin_ia32_scattersiv4df:
3571   case X86::BI__builtin_ia32_scattersiv4di:
3572   case X86::BI__builtin_ia32_scattersiv4sf:
3573   case X86::BI__builtin_ia32_scattersiv4si:
3574   case X86::BI__builtin_ia32_scattersiv8sf:
3575   case X86::BI__builtin_ia32_scattersiv8si:
3576   case X86::BI__builtin_ia32_scattersiv8df:
3577   case X86::BI__builtin_ia32_scattersiv16sf:
3578   case X86::BI__builtin_ia32_scatterdiv8df:
3579   case X86::BI__builtin_ia32_scatterdiv16sf:
3580   case X86::BI__builtin_ia32_scattersiv8di:
3581   case X86::BI__builtin_ia32_scattersiv16si:
3582   case X86::BI__builtin_ia32_scatterdiv8di:
3583   case X86::BI__builtin_ia32_scatterdiv16si:
3584     ArgNum = 4;
3585     break;
3586   }
3587 
3588   llvm::APSInt Result;
3589 
3590   // We can't check the value of a dependent argument.
3591   Expr *Arg = TheCall->getArg(ArgNum);
3592   if (Arg->isTypeDependent() || Arg->isValueDependent())
3593     return false;
3594 
3595   // Check constant-ness first.
3596   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3597     return true;
3598 
3599   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3600     return false;
3601 
3602   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3603          << Arg->getSourceRange();
3604 }
3605 
3606 enum { TileRegLow = 0, TileRegHigh = 7 };
3607 
3608 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3609                                     ArrayRef<int> ArgNums) {
3610   for (int ArgNum : ArgNums) {
3611     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3612       return true;
3613   }
3614   return false;
3615 }
3616 
3617 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum) {
3618   return SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh);
3619 }
3620 
3621 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3622                                         ArrayRef<int> ArgNums) {
3623   // Because the max number of tile register is TileRegHigh + 1, so here we use
3624   // each bit to represent the usage of them in bitset.
3625   std::bitset<TileRegHigh + 1> ArgValues;
3626   for (int ArgNum : ArgNums) {
3627     llvm::APSInt Arg;
3628     SemaBuiltinConstantArg(TheCall, ArgNum, Arg);
3629     int ArgExtValue = Arg.getExtValue();
3630     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3631            "Incorrect tile register num.");
3632     if (ArgValues.test(ArgExtValue))
3633       return Diag(TheCall->getBeginLoc(),
3634                   diag::err_x86_builtin_tile_arg_duplicate)
3635              << TheCall->getArg(ArgNum)->getSourceRange();
3636     ArgValues.set(ArgExtValue);
3637   }
3638   return false;
3639 }
3640 
3641 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3642                                                 ArrayRef<int> ArgNums) {
3643   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3644          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3645 }
3646 
3647 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3648   switch (BuiltinID) {
3649   default:
3650     return false;
3651   case X86::BI__builtin_ia32_tileloadd64:
3652   case X86::BI__builtin_ia32_tileloaddt164:
3653   case X86::BI__builtin_ia32_tilestored64:
3654   case X86::BI__builtin_ia32_tilezero:
3655     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3656   case X86::BI__builtin_ia32_tdpbssd:
3657   case X86::BI__builtin_ia32_tdpbsud:
3658   case X86::BI__builtin_ia32_tdpbusd:
3659   case X86::BI__builtin_ia32_tdpbuud:
3660   case X86::BI__builtin_ia32_tdpbf16ps:
3661     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3662   }
3663 }
3664 static bool isX86_32Builtin(unsigned BuiltinID) {
3665   // These builtins only work on x86-32 targets.
3666   switch (BuiltinID) {
3667   case X86::BI__builtin_ia32_readeflags_u32:
3668   case X86::BI__builtin_ia32_writeeflags_u32:
3669     return true;
3670   }
3671 
3672   return false;
3673 }
3674 
3675 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3676                                        CallExpr *TheCall) {
3677   if (BuiltinID == X86::BI__builtin_cpu_supports)
3678     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3679 
3680   if (BuiltinID == X86::BI__builtin_cpu_is)
3681     return SemaBuiltinCpuIs(*this, TI, TheCall);
3682 
3683   // Check for 32-bit only builtins on a 64-bit target.
3684   const llvm::Triple &TT = TI.getTriple();
3685   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3686     return Diag(TheCall->getCallee()->getBeginLoc(),
3687                 diag::err_32_bit_builtin_64_bit_tgt);
3688 
3689   // If the intrinsic has rounding or SAE make sure its valid.
3690   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3691     return true;
3692 
3693   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3694   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3695     return true;
3696 
3697   // If the intrinsic has a tile arguments, make sure they are valid.
3698   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3699     return true;
3700 
3701   // For intrinsics which take an immediate value as part of the instruction,
3702   // range check them here.
3703   int i = 0, l = 0, u = 0;
3704   switch (BuiltinID) {
3705   default:
3706     return false;
3707   case X86::BI__builtin_ia32_vec_ext_v2si:
3708   case X86::BI__builtin_ia32_vec_ext_v2di:
3709   case X86::BI__builtin_ia32_vextractf128_pd256:
3710   case X86::BI__builtin_ia32_vextractf128_ps256:
3711   case X86::BI__builtin_ia32_vextractf128_si256:
3712   case X86::BI__builtin_ia32_extract128i256:
3713   case X86::BI__builtin_ia32_extractf64x4_mask:
3714   case X86::BI__builtin_ia32_extracti64x4_mask:
3715   case X86::BI__builtin_ia32_extractf32x8_mask:
3716   case X86::BI__builtin_ia32_extracti32x8_mask:
3717   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3718   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3719   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3720   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3721     i = 1; l = 0; u = 1;
3722     break;
3723   case X86::BI__builtin_ia32_vec_set_v2di:
3724   case X86::BI__builtin_ia32_vinsertf128_pd256:
3725   case X86::BI__builtin_ia32_vinsertf128_ps256:
3726   case X86::BI__builtin_ia32_vinsertf128_si256:
3727   case X86::BI__builtin_ia32_insert128i256:
3728   case X86::BI__builtin_ia32_insertf32x8:
3729   case X86::BI__builtin_ia32_inserti32x8:
3730   case X86::BI__builtin_ia32_insertf64x4:
3731   case X86::BI__builtin_ia32_inserti64x4:
3732   case X86::BI__builtin_ia32_insertf64x2_256:
3733   case X86::BI__builtin_ia32_inserti64x2_256:
3734   case X86::BI__builtin_ia32_insertf32x4_256:
3735   case X86::BI__builtin_ia32_inserti32x4_256:
3736     i = 2; l = 0; u = 1;
3737     break;
3738   case X86::BI__builtin_ia32_vpermilpd:
3739   case X86::BI__builtin_ia32_vec_ext_v4hi:
3740   case X86::BI__builtin_ia32_vec_ext_v4si:
3741   case X86::BI__builtin_ia32_vec_ext_v4sf:
3742   case X86::BI__builtin_ia32_vec_ext_v4di:
3743   case X86::BI__builtin_ia32_extractf32x4_mask:
3744   case X86::BI__builtin_ia32_extracti32x4_mask:
3745   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3746   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3747     i = 1; l = 0; u = 3;
3748     break;
3749   case X86::BI_mm_prefetch:
3750   case X86::BI__builtin_ia32_vec_ext_v8hi:
3751   case X86::BI__builtin_ia32_vec_ext_v8si:
3752     i = 1; l = 0; u = 7;
3753     break;
3754   case X86::BI__builtin_ia32_sha1rnds4:
3755   case X86::BI__builtin_ia32_blendpd:
3756   case X86::BI__builtin_ia32_shufpd:
3757   case X86::BI__builtin_ia32_vec_set_v4hi:
3758   case X86::BI__builtin_ia32_vec_set_v4si:
3759   case X86::BI__builtin_ia32_vec_set_v4di:
3760   case X86::BI__builtin_ia32_shuf_f32x4_256:
3761   case X86::BI__builtin_ia32_shuf_f64x2_256:
3762   case X86::BI__builtin_ia32_shuf_i32x4_256:
3763   case X86::BI__builtin_ia32_shuf_i64x2_256:
3764   case X86::BI__builtin_ia32_insertf64x2_512:
3765   case X86::BI__builtin_ia32_inserti64x2_512:
3766   case X86::BI__builtin_ia32_insertf32x4:
3767   case X86::BI__builtin_ia32_inserti32x4:
3768     i = 2; l = 0; u = 3;
3769     break;
3770   case X86::BI__builtin_ia32_vpermil2pd:
3771   case X86::BI__builtin_ia32_vpermil2pd256:
3772   case X86::BI__builtin_ia32_vpermil2ps:
3773   case X86::BI__builtin_ia32_vpermil2ps256:
3774     i = 3; l = 0; u = 3;
3775     break;
3776   case X86::BI__builtin_ia32_cmpb128_mask:
3777   case X86::BI__builtin_ia32_cmpw128_mask:
3778   case X86::BI__builtin_ia32_cmpd128_mask:
3779   case X86::BI__builtin_ia32_cmpq128_mask:
3780   case X86::BI__builtin_ia32_cmpb256_mask:
3781   case X86::BI__builtin_ia32_cmpw256_mask:
3782   case X86::BI__builtin_ia32_cmpd256_mask:
3783   case X86::BI__builtin_ia32_cmpq256_mask:
3784   case X86::BI__builtin_ia32_cmpb512_mask:
3785   case X86::BI__builtin_ia32_cmpw512_mask:
3786   case X86::BI__builtin_ia32_cmpd512_mask:
3787   case X86::BI__builtin_ia32_cmpq512_mask:
3788   case X86::BI__builtin_ia32_ucmpb128_mask:
3789   case X86::BI__builtin_ia32_ucmpw128_mask:
3790   case X86::BI__builtin_ia32_ucmpd128_mask:
3791   case X86::BI__builtin_ia32_ucmpq128_mask:
3792   case X86::BI__builtin_ia32_ucmpb256_mask:
3793   case X86::BI__builtin_ia32_ucmpw256_mask:
3794   case X86::BI__builtin_ia32_ucmpd256_mask:
3795   case X86::BI__builtin_ia32_ucmpq256_mask:
3796   case X86::BI__builtin_ia32_ucmpb512_mask:
3797   case X86::BI__builtin_ia32_ucmpw512_mask:
3798   case X86::BI__builtin_ia32_ucmpd512_mask:
3799   case X86::BI__builtin_ia32_ucmpq512_mask:
3800   case X86::BI__builtin_ia32_vpcomub:
3801   case X86::BI__builtin_ia32_vpcomuw:
3802   case X86::BI__builtin_ia32_vpcomud:
3803   case X86::BI__builtin_ia32_vpcomuq:
3804   case X86::BI__builtin_ia32_vpcomb:
3805   case X86::BI__builtin_ia32_vpcomw:
3806   case X86::BI__builtin_ia32_vpcomd:
3807   case X86::BI__builtin_ia32_vpcomq:
3808   case X86::BI__builtin_ia32_vec_set_v8hi:
3809   case X86::BI__builtin_ia32_vec_set_v8si:
3810     i = 2; l = 0; u = 7;
3811     break;
3812   case X86::BI__builtin_ia32_vpermilpd256:
3813   case X86::BI__builtin_ia32_roundps:
3814   case X86::BI__builtin_ia32_roundpd:
3815   case X86::BI__builtin_ia32_roundps256:
3816   case X86::BI__builtin_ia32_roundpd256:
3817   case X86::BI__builtin_ia32_getmantpd128_mask:
3818   case X86::BI__builtin_ia32_getmantpd256_mask:
3819   case X86::BI__builtin_ia32_getmantps128_mask:
3820   case X86::BI__builtin_ia32_getmantps256_mask:
3821   case X86::BI__builtin_ia32_getmantpd512_mask:
3822   case X86::BI__builtin_ia32_getmantps512_mask:
3823   case X86::BI__builtin_ia32_vec_ext_v16qi:
3824   case X86::BI__builtin_ia32_vec_ext_v16hi:
3825     i = 1; l = 0; u = 15;
3826     break;
3827   case X86::BI__builtin_ia32_pblendd128:
3828   case X86::BI__builtin_ia32_blendps:
3829   case X86::BI__builtin_ia32_blendpd256:
3830   case X86::BI__builtin_ia32_shufpd256:
3831   case X86::BI__builtin_ia32_roundss:
3832   case X86::BI__builtin_ia32_roundsd:
3833   case X86::BI__builtin_ia32_rangepd128_mask:
3834   case X86::BI__builtin_ia32_rangepd256_mask:
3835   case X86::BI__builtin_ia32_rangepd512_mask:
3836   case X86::BI__builtin_ia32_rangeps128_mask:
3837   case X86::BI__builtin_ia32_rangeps256_mask:
3838   case X86::BI__builtin_ia32_rangeps512_mask:
3839   case X86::BI__builtin_ia32_getmantsd_round_mask:
3840   case X86::BI__builtin_ia32_getmantss_round_mask:
3841   case X86::BI__builtin_ia32_vec_set_v16qi:
3842   case X86::BI__builtin_ia32_vec_set_v16hi:
3843     i = 2; l = 0; u = 15;
3844     break;
3845   case X86::BI__builtin_ia32_vec_ext_v32qi:
3846     i = 1; l = 0; u = 31;
3847     break;
3848   case X86::BI__builtin_ia32_cmpps:
3849   case X86::BI__builtin_ia32_cmpss:
3850   case X86::BI__builtin_ia32_cmppd:
3851   case X86::BI__builtin_ia32_cmpsd:
3852   case X86::BI__builtin_ia32_cmpps256:
3853   case X86::BI__builtin_ia32_cmppd256:
3854   case X86::BI__builtin_ia32_cmpps128_mask:
3855   case X86::BI__builtin_ia32_cmppd128_mask:
3856   case X86::BI__builtin_ia32_cmpps256_mask:
3857   case X86::BI__builtin_ia32_cmppd256_mask:
3858   case X86::BI__builtin_ia32_cmpps512_mask:
3859   case X86::BI__builtin_ia32_cmppd512_mask:
3860   case X86::BI__builtin_ia32_cmpsd_mask:
3861   case X86::BI__builtin_ia32_cmpss_mask:
3862   case X86::BI__builtin_ia32_vec_set_v32qi:
3863     i = 2; l = 0; u = 31;
3864     break;
3865   case X86::BI__builtin_ia32_permdf256:
3866   case X86::BI__builtin_ia32_permdi256:
3867   case X86::BI__builtin_ia32_permdf512:
3868   case X86::BI__builtin_ia32_permdi512:
3869   case X86::BI__builtin_ia32_vpermilps:
3870   case X86::BI__builtin_ia32_vpermilps256:
3871   case X86::BI__builtin_ia32_vpermilpd512:
3872   case X86::BI__builtin_ia32_vpermilps512:
3873   case X86::BI__builtin_ia32_pshufd:
3874   case X86::BI__builtin_ia32_pshufd256:
3875   case X86::BI__builtin_ia32_pshufd512:
3876   case X86::BI__builtin_ia32_pshufhw:
3877   case X86::BI__builtin_ia32_pshufhw256:
3878   case X86::BI__builtin_ia32_pshufhw512:
3879   case X86::BI__builtin_ia32_pshuflw:
3880   case X86::BI__builtin_ia32_pshuflw256:
3881   case X86::BI__builtin_ia32_pshuflw512:
3882   case X86::BI__builtin_ia32_vcvtps2ph:
3883   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3884   case X86::BI__builtin_ia32_vcvtps2ph256:
3885   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3886   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3887   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3888   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3889   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3890   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3891   case X86::BI__builtin_ia32_rndscaleps_mask:
3892   case X86::BI__builtin_ia32_rndscalepd_mask:
3893   case X86::BI__builtin_ia32_reducepd128_mask:
3894   case X86::BI__builtin_ia32_reducepd256_mask:
3895   case X86::BI__builtin_ia32_reducepd512_mask:
3896   case X86::BI__builtin_ia32_reduceps128_mask:
3897   case X86::BI__builtin_ia32_reduceps256_mask:
3898   case X86::BI__builtin_ia32_reduceps512_mask:
3899   case X86::BI__builtin_ia32_prold512:
3900   case X86::BI__builtin_ia32_prolq512:
3901   case X86::BI__builtin_ia32_prold128:
3902   case X86::BI__builtin_ia32_prold256:
3903   case X86::BI__builtin_ia32_prolq128:
3904   case X86::BI__builtin_ia32_prolq256:
3905   case X86::BI__builtin_ia32_prord512:
3906   case X86::BI__builtin_ia32_prorq512:
3907   case X86::BI__builtin_ia32_prord128:
3908   case X86::BI__builtin_ia32_prord256:
3909   case X86::BI__builtin_ia32_prorq128:
3910   case X86::BI__builtin_ia32_prorq256:
3911   case X86::BI__builtin_ia32_fpclasspd128_mask:
3912   case X86::BI__builtin_ia32_fpclasspd256_mask:
3913   case X86::BI__builtin_ia32_fpclassps128_mask:
3914   case X86::BI__builtin_ia32_fpclassps256_mask:
3915   case X86::BI__builtin_ia32_fpclassps512_mask:
3916   case X86::BI__builtin_ia32_fpclasspd512_mask:
3917   case X86::BI__builtin_ia32_fpclasssd_mask:
3918   case X86::BI__builtin_ia32_fpclassss_mask:
3919   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3920   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3921   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3922   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3923   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3924   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3925   case X86::BI__builtin_ia32_kshiftliqi:
3926   case X86::BI__builtin_ia32_kshiftlihi:
3927   case X86::BI__builtin_ia32_kshiftlisi:
3928   case X86::BI__builtin_ia32_kshiftlidi:
3929   case X86::BI__builtin_ia32_kshiftriqi:
3930   case X86::BI__builtin_ia32_kshiftrihi:
3931   case X86::BI__builtin_ia32_kshiftrisi:
3932   case X86::BI__builtin_ia32_kshiftridi:
3933     i = 1; l = 0; u = 255;
3934     break;
3935   case X86::BI__builtin_ia32_vperm2f128_pd256:
3936   case X86::BI__builtin_ia32_vperm2f128_ps256:
3937   case X86::BI__builtin_ia32_vperm2f128_si256:
3938   case X86::BI__builtin_ia32_permti256:
3939   case X86::BI__builtin_ia32_pblendw128:
3940   case X86::BI__builtin_ia32_pblendw256:
3941   case X86::BI__builtin_ia32_blendps256:
3942   case X86::BI__builtin_ia32_pblendd256:
3943   case X86::BI__builtin_ia32_palignr128:
3944   case X86::BI__builtin_ia32_palignr256:
3945   case X86::BI__builtin_ia32_palignr512:
3946   case X86::BI__builtin_ia32_alignq512:
3947   case X86::BI__builtin_ia32_alignd512:
3948   case X86::BI__builtin_ia32_alignd128:
3949   case X86::BI__builtin_ia32_alignd256:
3950   case X86::BI__builtin_ia32_alignq128:
3951   case X86::BI__builtin_ia32_alignq256:
3952   case X86::BI__builtin_ia32_vcomisd:
3953   case X86::BI__builtin_ia32_vcomiss:
3954   case X86::BI__builtin_ia32_shuf_f32x4:
3955   case X86::BI__builtin_ia32_shuf_f64x2:
3956   case X86::BI__builtin_ia32_shuf_i32x4:
3957   case X86::BI__builtin_ia32_shuf_i64x2:
3958   case X86::BI__builtin_ia32_shufpd512:
3959   case X86::BI__builtin_ia32_shufps:
3960   case X86::BI__builtin_ia32_shufps256:
3961   case X86::BI__builtin_ia32_shufps512:
3962   case X86::BI__builtin_ia32_dbpsadbw128:
3963   case X86::BI__builtin_ia32_dbpsadbw256:
3964   case X86::BI__builtin_ia32_dbpsadbw512:
3965   case X86::BI__builtin_ia32_vpshldd128:
3966   case X86::BI__builtin_ia32_vpshldd256:
3967   case X86::BI__builtin_ia32_vpshldd512:
3968   case X86::BI__builtin_ia32_vpshldq128:
3969   case X86::BI__builtin_ia32_vpshldq256:
3970   case X86::BI__builtin_ia32_vpshldq512:
3971   case X86::BI__builtin_ia32_vpshldw128:
3972   case X86::BI__builtin_ia32_vpshldw256:
3973   case X86::BI__builtin_ia32_vpshldw512:
3974   case X86::BI__builtin_ia32_vpshrdd128:
3975   case X86::BI__builtin_ia32_vpshrdd256:
3976   case X86::BI__builtin_ia32_vpshrdd512:
3977   case X86::BI__builtin_ia32_vpshrdq128:
3978   case X86::BI__builtin_ia32_vpshrdq256:
3979   case X86::BI__builtin_ia32_vpshrdq512:
3980   case X86::BI__builtin_ia32_vpshrdw128:
3981   case X86::BI__builtin_ia32_vpshrdw256:
3982   case X86::BI__builtin_ia32_vpshrdw512:
3983     i = 2; l = 0; u = 255;
3984     break;
3985   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3986   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3987   case X86::BI__builtin_ia32_fixupimmps512_mask:
3988   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3989   case X86::BI__builtin_ia32_fixupimmsd_mask:
3990   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3991   case X86::BI__builtin_ia32_fixupimmss_mask:
3992   case X86::BI__builtin_ia32_fixupimmss_maskz:
3993   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3994   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3995   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3996   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3997   case X86::BI__builtin_ia32_fixupimmps128_mask:
3998   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3999   case X86::BI__builtin_ia32_fixupimmps256_mask:
4000   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4001   case X86::BI__builtin_ia32_pternlogd512_mask:
4002   case X86::BI__builtin_ia32_pternlogd512_maskz:
4003   case X86::BI__builtin_ia32_pternlogq512_mask:
4004   case X86::BI__builtin_ia32_pternlogq512_maskz:
4005   case X86::BI__builtin_ia32_pternlogd128_mask:
4006   case X86::BI__builtin_ia32_pternlogd128_maskz:
4007   case X86::BI__builtin_ia32_pternlogd256_mask:
4008   case X86::BI__builtin_ia32_pternlogd256_maskz:
4009   case X86::BI__builtin_ia32_pternlogq128_mask:
4010   case X86::BI__builtin_ia32_pternlogq128_maskz:
4011   case X86::BI__builtin_ia32_pternlogq256_mask:
4012   case X86::BI__builtin_ia32_pternlogq256_maskz:
4013     i = 3; l = 0; u = 255;
4014     break;
4015   case X86::BI__builtin_ia32_gatherpfdpd:
4016   case X86::BI__builtin_ia32_gatherpfdps:
4017   case X86::BI__builtin_ia32_gatherpfqpd:
4018   case X86::BI__builtin_ia32_gatherpfqps:
4019   case X86::BI__builtin_ia32_scatterpfdpd:
4020   case X86::BI__builtin_ia32_scatterpfdps:
4021   case X86::BI__builtin_ia32_scatterpfqpd:
4022   case X86::BI__builtin_ia32_scatterpfqps:
4023     i = 4; l = 2; u = 3;
4024     break;
4025   case X86::BI__builtin_ia32_reducesd_mask:
4026   case X86::BI__builtin_ia32_reducess_mask:
4027   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4028   case X86::BI__builtin_ia32_rndscaless_round_mask:
4029     i = 4; l = 0; u = 255;
4030     break;
4031   }
4032 
4033   // Note that we don't force a hard error on the range check here, allowing
4034   // template-generated or macro-generated dead code to potentially have out-of-
4035   // range values. These need to code generate, but don't need to necessarily
4036   // make any sense. We use a warning that defaults to an error.
4037   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4038 }
4039 
4040 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4041 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4042 /// Returns true when the format fits the function and the FormatStringInfo has
4043 /// been populated.
4044 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4045                                FormatStringInfo *FSI) {
4046   FSI->HasVAListArg = Format->getFirstArg() == 0;
4047   FSI->FormatIdx = Format->getFormatIdx() - 1;
4048   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4049 
4050   // The way the format attribute works in GCC, the implicit this argument
4051   // of member functions is counted. However, it doesn't appear in our own
4052   // lists, so decrement format_idx in that case.
4053   if (IsCXXMember) {
4054     if(FSI->FormatIdx == 0)
4055       return false;
4056     --FSI->FormatIdx;
4057     if (FSI->FirstDataArg != 0)
4058       --FSI->FirstDataArg;
4059   }
4060   return true;
4061 }
4062 
4063 /// Checks if a the given expression evaluates to null.
4064 ///
4065 /// Returns true if the value evaluates to null.
4066 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4067   // If the expression has non-null type, it doesn't evaluate to null.
4068   if (auto nullability
4069         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4070     if (*nullability == NullabilityKind::NonNull)
4071       return false;
4072   }
4073 
4074   // As a special case, transparent unions initialized with zero are
4075   // considered null for the purposes of the nonnull attribute.
4076   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4077     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4078       if (const CompoundLiteralExpr *CLE =
4079           dyn_cast<CompoundLiteralExpr>(Expr))
4080         if (const InitListExpr *ILE =
4081             dyn_cast<InitListExpr>(CLE->getInitializer()))
4082           Expr = ILE->getInit(0);
4083   }
4084 
4085   bool Result;
4086   return (!Expr->isValueDependent() &&
4087           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4088           !Result);
4089 }
4090 
4091 static void CheckNonNullArgument(Sema &S,
4092                                  const Expr *ArgExpr,
4093                                  SourceLocation CallSiteLoc) {
4094   if (CheckNonNullExpr(S, ArgExpr))
4095     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4096                           S.PDiag(diag::warn_null_arg)
4097                               << ArgExpr->getSourceRange());
4098 }
4099 
4100 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4101   FormatStringInfo FSI;
4102   if ((GetFormatStringType(Format) == FST_NSString) &&
4103       getFormatStringInfo(Format, false, &FSI)) {
4104     Idx = FSI.FormatIdx;
4105     return true;
4106   }
4107   return false;
4108 }
4109 
4110 /// Diagnose use of %s directive in an NSString which is being passed
4111 /// as formatting string to formatting method.
4112 static void
4113 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4114                                         const NamedDecl *FDecl,
4115                                         Expr **Args,
4116                                         unsigned NumArgs) {
4117   unsigned Idx = 0;
4118   bool Format = false;
4119   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4120   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4121     Idx = 2;
4122     Format = true;
4123   }
4124   else
4125     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4126       if (S.GetFormatNSStringIdx(I, Idx)) {
4127         Format = true;
4128         break;
4129       }
4130     }
4131   if (!Format || NumArgs <= Idx)
4132     return;
4133   const Expr *FormatExpr = Args[Idx];
4134   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4135     FormatExpr = CSCE->getSubExpr();
4136   const StringLiteral *FormatString;
4137   if (const ObjCStringLiteral *OSL =
4138       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4139     FormatString = OSL->getString();
4140   else
4141     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4142   if (!FormatString)
4143     return;
4144   if (S.FormatStringHasSArg(FormatString)) {
4145     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4146       << "%s" << 1 << 1;
4147     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4148       << FDecl->getDeclName();
4149   }
4150 }
4151 
4152 /// Determine whether the given type has a non-null nullability annotation.
4153 static bool isNonNullType(ASTContext &ctx, QualType type) {
4154   if (auto nullability = type->getNullability(ctx))
4155     return *nullability == NullabilityKind::NonNull;
4156 
4157   return false;
4158 }
4159 
4160 static void CheckNonNullArguments(Sema &S,
4161                                   const NamedDecl *FDecl,
4162                                   const FunctionProtoType *Proto,
4163                                   ArrayRef<const Expr *> Args,
4164                                   SourceLocation CallSiteLoc) {
4165   assert((FDecl || Proto) && "Need a function declaration or prototype");
4166 
4167   // Already checked by by constant evaluator.
4168   if (S.isConstantEvaluated())
4169     return;
4170   // Check the attributes attached to the method/function itself.
4171   llvm::SmallBitVector NonNullArgs;
4172   if (FDecl) {
4173     // Handle the nonnull attribute on the function/method declaration itself.
4174     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4175       if (!NonNull->args_size()) {
4176         // Easy case: all pointer arguments are nonnull.
4177         for (const auto *Arg : Args)
4178           if (S.isValidPointerAttrType(Arg->getType()))
4179             CheckNonNullArgument(S, Arg, CallSiteLoc);
4180         return;
4181       }
4182 
4183       for (const ParamIdx &Idx : NonNull->args()) {
4184         unsigned IdxAST = Idx.getASTIndex();
4185         if (IdxAST >= Args.size())
4186           continue;
4187         if (NonNullArgs.empty())
4188           NonNullArgs.resize(Args.size());
4189         NonNullArgs.set(IdxAST);
4190       }
4191     }
4192   }
4193 
4194   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4195     // Handle the nonnull attribute on the parameters of the
4196     // function/method.
4197     ArrayRef<ParmVarDecl*> parms;
4198     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4199       parms = FD->parameters();
4200     else
4201       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4202 
4203     unsigned ParamIndex = 0;
4204     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4205          I != E; ++I, ++ParamIndex) {
4206       const ParmVarDecl *PVD = *I;
4207       if (PVD->hasAttr<NonNullAttr>() ||
4208           isNonNullType(S.Context, PVD->getType())) {
4209         if (NonNullArgs.empty())
4210           NonNullArgs.resize(Args.size());
4211 
4212         NonNullArgs.set(ParamIndex);
4213       }
4214     }
4215   } else {
4216     // If we have a non-function, non-method declaration but no
4217     // function prototype, try to dig out the function prototype.
4218     if (!Proto) {
4219       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4220         QualType type = VD->getType().getNonReferenceType();
4221         if (auto pointerType = type->getAs<PointerType>())
4222           type = pointerType->getPointeeType();
4223         else if (auto blockType = type->getAs<BlockPointerType>())
4224           type = blockType->getPointeeType();
4225         // FIXME: data member pointers?
4226 
4227         // Dig out the function prototype, if there is one.
4228         Proto = type->getAs<FunctionProtoType>();
4229       }
4230     }
4231 
4232     // Fill in non-null argument information from the nullability
4233     // information on the parameter types (if we have them).
4234     if (Proto) {
4235       unsigned Index = 0;
4236       for (auto paramType : Proto->getParamTypes()) {
4237         if (isNonNullType(S.Context, paramType)) {
4238           if (NonNullArgs.empty())
4239             NonNullArgs.resize(Args.size());
4240 
4241           NonNullArgs.set(Index);
4242         }
4243 
4244         ++Index;
4245       }
4246     }
4247   }
4248 
4249   // Check for non-null arguments.
4250   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4251        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4252     if (NonNullArgs[ArgIndex])
4253       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4254   }
4255 }
4256 
4257 /// Handles the checks for format strings, non-POD arguments to vararg
4258 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4259 /// attributes.
4260 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4261                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4262                      bool IsMemberFunction, SourceLocation Loc,
4263                      SourceRange Range, VariadicCallType CallType) {
4264   // FIXME: We should check as much as we can in the template definition.
4265   if (CurContext->isDependentContext())
4266     return;
4267 
4268   // Printf and scanf checking.
4269   llvm::SmallBitVector CheckedVarArgs;
4270   if (FDecl) {
4271     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4272       // Only create vector if there are format attributes.
4273       CheckedVarArgs.resize(Args.size());
4274 
4275       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4276                            CheckedVarArgs);
4277     }
4278   }
4279 
4280   // Refuse POD arguments that weren't caught by the format string
4281   // checks above.
4282   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4283   if (CallType != VariadicDoesNotApply &&
4284       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4285     unsigned NumParams = Proto ? Proto->getNumParams()
4286                        : FDecl && isa<FunctionDecl>(FDecl)
4287                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4288                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4289                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4290                        : 0;
4291 
4292     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4293       // Args[ArgIdx] can be null in malformed code.
4294       if (const Expr *Arg = Args[ArgIdx]) {
4295         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4296           checkVariadicArgument(Arg, CallType);
4297       }
4298     }
4299   }
4300 
4301   if (FDecl || Proto) {
4302     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4303 
4304     // Type safety checking.
4305     if (FDecl) {
4306       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4307         CheckArgumentWithTypeTag(I, Args, Loc);
4308     }
4309   }
4310 
4311   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4312     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4313     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4314     if (!Arg->isValueDependent()) {
4315       Expr::EvalResult Align;
4316       if (Arg->EvaluateAsInt(Align, Context)) {
4317         const llvm::APSInt &I = Align.Val.getInt();
4318         if (!I.isPowerOf2())
4319           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4320               << Arg->getSourceRange();
4321 
4322         if (I > Sema::MaximumAlignment)
4323           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4324               << Arg->getSourceRange() << Sema::MaximumAlignment;
4325       }
4326     }
4327   }
4328 
4329   if (FD)
4330     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4331 }
4332 
4333 /// CheckConstructorCall - Check a constructor call for correctness and safety
4334 /// properties not enforced by the C type system.
4335 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4336                                 ArrayRef<const Expr *> Args,
4337                                 const FunctionProtoType *Proto,
4338                                 SourceLocation Loc) {
4339   VariadicCallType CallType =
4340     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4341   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4342             Loc, SourceRange(), CallType);
4343 }
4344 
4345 /// CheckFunctionCall - Check a direct function call for various correctness
4346 /// and safety properties not strictly enforced by the C type system.
4347 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4348                              const FunctionProtoType *Proto) {
4349   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4350                               isa<CXXMethodDecl>(FDecl);
4351   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4352                           IsMemberOperatorCall;
4353   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4354                                                   TheCall->getCallee());
4355   Expr** Args = TheCall->getArgs();
4356   unsigned NumArgs = TheCall->getNumArgs();
4357 
4358   Expr *ImplicitThis = nullptr;
4359   if (IsMemberOperatorCall) {
4360     // If this is a call to a member operator, hide the first argument
4361     // from checkCall.
4362     // FIXME: Our choice of AST representation here is less than ideal.
4363     ImplicitThis = Args[0];
4364     ++Args;
4365     --NumArgs;
4366   } else if (IsMemberFunction)
4367     ImplicitThis =
4368         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4369 
4370   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4371             IsMemberFunction, TheCall->getRParenLoc(),
4372             TheCall->getCallee()->getSourceRange(), CallType);
4373 
4374   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4375   // None of the checks below are needed for functions that don't have
4376   // simple names (e.g., C++ conversion functions).
4377   if (!FnInfo)
4378     return false;
4379 
4380   CheckAbsoluteValueFunction(TheCall, FDecl);
4381   CheckMaxUnsignedZero(TheCall, FDecl);
4382 
4383   if (getLangOpts().ObjC)
4384     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4385 
4386   unsigned CMId = FDecl->getMemoryFunctionKind();
4387   if (CMId == 0)
4388     return false;
4389 
4390   // Handle memory setting and copying functions.
4391   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4392     CheckStrlcpycatArguments(TheCall, FnInfo);
4393   else if (CMId == Builtin::BIstrncat)
4394     CheckStrncatArguments(TheCall, FnInfo);
4395   else
4396     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4397 
4398   return false;
4399 }
4400 
4401 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4402                                ArrayRef<const Expr *> Args) {
4403   VariadicCallType CallType =
4404       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4405 
4406   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4407             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4408             CallType);
4409 
4410   return false;
4411 }
4412 
4413 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4414                             const FunctionProtoType *Proto) {
4415   QualType Ty;
4416   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4417     Ty = V->getType().getNonReferenceType();
4418   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4419     Ty = F->getType().getNonReferenceType();
4420   else
4421     return false;
4422 
4423   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4424       !Ty->isFunctionProtoType())
4425     return false;
4426 
4427   VariadicCallType CallType;
4428   if (!Proto || !Proto->isVariadic()) {
4429     CallType = VariadicDoesNotApply;
4430   } else if (Ty->isBlockPointerType()) {
4431     CallType = VariadicBlock;
4432   } else { // Ty->isFunctionPointerType()
4433     CallType = VariadicFunction;
4434   }
4435 
4436   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4437             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4438             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4439             TheCall->getCallee()->getSourceRange(), CallType);
4440 
4441   return false;
4442 }
4443 
4444 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4445 /// such as function pointers returned from functions.
4446 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4447   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4448                                                   TheCall->getCallee());
4449   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4450             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4451             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4452             TheCall->getCallee()->getSourceRange(), CallType);
4453 
4454   return false;
4455 }
4456 
4457 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4458   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4459     return false;
4460 
4461   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4462   switch (Op) {
4463   case AtomicExpr::AO__c11_atomic_init:
4464   case AtomicExpr::AO__opencl_atomic_init:
4465     llvm_unreachable("There is no ordering argument for an init");
4466 
4467   case AtomicExpr::AO__c11_atomic_load:
4468   case AtomicExpr::AO__opencl_atomic_load:
4469   case AtomicExpr::AO__atomic_load_n:
4470   case AtomicExpr::AO__atomic_load:
4471     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4472            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4473 
4474   case AtomicExpr::AO__c11_atomic_store:
4475   case AtomicExpr::AO__opencl_atomic_store:
4476   case AtomicExpr::AO__atomic_store:
4477   case AtomicExpr::AO__atomic_store_n:
4478     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4479            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4480            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4481 
4482   default:
4483     return true;
4484   }
4485 }
4486 
4487 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4488                                          AtomicExpr::AtomicOp Op) {
4489   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4490   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4491   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4492   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4493                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4494                          Op);
4495 }
4496 
4497 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4498                                  SourceLocation RParenLoc, MultiExprArg Args,
4499                                  AtomicExpr::AtomicOp Op,
4500                                  AtomicArgumentOrder ArgOrder) {
4501   // All the non-OpenCL operations take one of the following forms.
4502   // The OpenCL operations take the __c11 forms with one extra argument for
4503   // synchronization scope.
4504   enum {
4505     // C    __c11_atomic_init(A *, C)
4506     Init,
4507 
4508     // C    __c11_atomic_load(A *, int)
4509     Load,
4510 
4511     // void __atomic_load(A *, CP, int)
4512     LoadCopy,
4513 
4514     // void __atomic_store(A *, CP, int)
4515     Copy,
4516 
4517     // C    __c11_atomic_add(A *, M, int)
4518     Arithmetic,
4519 
4520     // C    __atomic_exchange_n(A *, CP, int)
4521     Xchg,
4522 
4523     // void __atomic_exchange(A *, C *, CP, int)
4524     GNUXchg,
4525 
4526     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4527     C11CmpXchg,
4528 
4529     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4530     GNUCmpXchg
4531   } Form = Init;
4532 
4533   const unsigned NumForm = GNUCmpXchg + 1;
4534   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4535   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4536   // where:
4537   //   C is an appropriate type,
4538   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4539   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4540   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4541   //   the int parameters are for orderings.
4542 
4543   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4544       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4545       "need to update code for modified forms");
4546   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4547                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4548                         AtomicExpr::AO__atomic_load,
4549                 "need to update code for modified C11 atomics");
4550   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4551                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4552   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4553                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4554                IsOpenCL;
4555   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4556              Op == AtomicExpr::AO__atomic_store_n ||
4557              Op == AtomicExpr::AO__atomic_exchange_n ||
4558              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4559   bool IsAddSub = false;
4560 
4561   switch (Op) {
4562   case AtomicExpr::AO__c11_atomic_init:
4563   case AtomicExpr::AO__opencl_atomic_init:
4564     Form = Init;
4565     break;
4566 
4567   case AtomicExpr::AO__c11_atomic_load:
4568   case AtomicExpr::AO__opencl_atomic_load:
4569   case AtomicExpr::AO__atomic_load_n:
4570     Form = Load;
4571     break;
4572 
4573   case AtomicExpr::AO__atomic_load:
4574     Form = LoadCopy;
4575     break;
4576 
4577   case AtomicExpr::AO__c11_atomic_store:
4578   case AtomicExpr::AO__opencl_atomic_store:
4579   case AtomicExpr::AO__atomic_store:
4580   case AtomicExpr::AO__atomic_store_n:
4581     Form = Copy;
4582     break;
4583 
4584   case AtomicExpr::AO__c11_atomic_fetch_add:
4585   case AtomicExpr::AO__c11_atomic_fetch_sub:
4586   case AtomicExpr::AO__opencl_atomic_fetch_add:
4587   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4588   case AtomicExpr::AO__atomic_fetch_add:
4589   case AtomicExpr::AO__atomic_fetch_sub:
4590   case AtomicExpr::AO__atomic_add_fetch:
4591   case AtomicExpr::AO__atomic_sub_fetch:
4592     IsAddSub = true;
4593     LLVM_FALLTHROUGH;
4594   case AtomicExpr::AO__c11_atomic_fetch_and:
4595   case AtomicExpr::AO__c11_atomic_fetch_or:
4596   case AtomicExpr::AO__c11_atomic_fetch_xor:
4597   case AtomicExpr::AO__opencl_atomic_fetch_and:
4598   case AtomicExpr::AO__opencl_atomic_fetch_or:
4599   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4600   case AtomicExpr::AO__atomic_fetch_and:
4601   case AtomicExpr::AO__atomic_fetch_or:
4602   case AtomicExpr::AO__atomic_fetch_xor:
4603   case AtomicExpr::AO__atomic_fetch_nand:
4604   case AtomicExpr::AO__atomic_and_fetch:
4605   case AtomicExpr::AO__atomic_or_fetch:
4606   case AtomicExpr::AO__atomic_xor_fetch:
4607   case AtomicExpr::AO__atomic_nand_fetch:
4608   case AtomicExpr::AO__c11_atomic_fetch_min:
4609   case AtomicExpr::AO__c11_atomic_fetch_max:
4610   case AtomicExpr::AO__opencl_atomic_fetch_min:
4611   case AtomicExpr::AO__opencl_atomic_fetch_max:
4612   case AtomicExpr::AO__atomic_min_fetch:
4613   case AtomicExpr::AO__atomic_max_fetch:
4614   case AtomicExpr::AO__atomic_fetch_min:
4615   case AtomicExpr::AO__atomic_fetch_max:
4616     Form = Arithmetic;
4617     break;
4618 
4619   case AtomicExpr::AO__c11_atomic_exchange:
4620   case AtomicExpr::AO__opencl_atomic_exchange:
4621   case AtomicExpr::AO__atomic_exchange_n:
4622     Form = Xchg;
4623     break;
4624 
4625   case AtomicExpr::AO__atomic_exchange:
4626     Form = GNUXchg;
4627     break;
4628 
4629   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4630   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4631   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4632   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4633     Form = C11CmpXchg;
4634     break;
4635 
4636   case AtomicExpr::AO__atomic_compare_exchange:
4637   case AtomicExpr::AO__atomic_compare_exchange_n:
4638     Form = GNUCmpXchg;
4639     break;
4640   }
4641 
4642   unsigned AdjustedNumArgs = NumArgs[Form];
4643   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4644     ++AdjustedNumArgs;
4645   // Check we have the right number of arguments.
4646   if (Args.size() < AdjustedNumArgs) {
4647     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4648         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4649         << ExprRange;
4650     return ExprError();
4651   } else if (Args.size() > AdjustedNumArgs) {
4652     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4653          diag::err_typecheck_call_too_many_args)
4654         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4655         << ExprRange;
4656     return ExprError();
4657   }
4658 
4659   // Inspect the first argument of the atomic operation.
4660   Expr *Ptr = Args[0];
4661   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4662   if (ConvertedPtr.isInvalid())
4663     return ExprError();
4664 
4665   Ptr = ConvertedPtr.get();
4666   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4667   if (!pointerType) {
4668     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4669         << Ptr->getType() << Ptr->getSourceRange();
4670     return ExprError();
4671   }
4672 
4673   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4674   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4675   QualType ValType = AtomTy; // 'C'
4676   if (IsC11) {
4677     if (!AtomTy->isAtomicType()) {
4678       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4679           << Ptr->getType() << Ptr->getSourceRange();
4680       return ExprError();
4681     }
4682     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4683         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4684       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4685           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4686           << Ptr->getSourceRange();
4687       return ExprError();
4688     }
4689     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4690   } else if (Form != Load && Form != LoadCopy) {
4691     if (ValType.isConstQualified()) {
4692       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4693           << Ptr->getType() << Ptr->getSourceRange();
4694       return ExprError();
4695     }
4696   }
4697 
4698   // For an arithmetic operation, the implied arithmetic must be well-formed.
4699   if (Form == Arithmetic) {
4700     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4701     if (IsAddSub && !ValType->isIntegerType()
4702         && !ValType->isPointerType()) {
4703       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4704           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4705       return ExprError();
4706     }
4707     if (!IsAddSub && !ValType->isIntegerType()) {
4708       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4709           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4710       return ExprError();
4711     }
4712     if (IsC11 && ValType->isPointerType() &&
4713         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4714                             diag::err_incomplete_type)) {
4715       return ExprError();
4716     }
4717   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4718     // For __atomic_*_n operations, the value type must be a scalar integral or
4719     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4720     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4721         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4722     return ExprError();
4723   }
4724 
4725   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4726       !AtomTy->isScalarType()) {
4727     // For GNU atomics, require a trivially-copyable type. This is not part of
4728     // the GNU atomics specification, but we enforce it for sanity.
4729     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4730         << Ptr->getType() << Ptr->getSourceRange();
4731     return ExprError();
4732   }
4733 
4734   switch (ValType.getObjCLifetime()) {
4735   case Qualifiers::OCL_None:
4736   case Qualifiers::OCL_ExplicitNone:
4737     // okay
4738     break;
4739 
4740   case Qualifiers::OCL_Weak:
4741   case Qualifiers::OCL_Strong:
4742   case Qualifiers::OCL_Autoreleasing:
4743     // FIXME: Can this happen? By this point, ValType should be known
4744     // to be trivially copyable.
4745     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4746         << ValType << Ptr->getSourceRange();
4747     return ExprError();
4748   }
4749 
4750   // All atomic operations have an overload which takes a pointer to a volatile
4751   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4752   // into the result or the other operands. Similarly atomic_load takes a
4753   // pointer to a const 'A'.
4754   ValType.removeLocalVolatile();
4755   ValType.removeLocalConst();
4756   QualType ResultType = ValType;
4757   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4758       Form == Init)
4759     ResultType = Context.VoidTy;
4760   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4761     ResultType = Context.BoolTy;
4762 
4763   // The type of a parameter passed 'by value'. In the GNU atomics, such
4764   // arguments are actually passed as pointers.
4765   QualType ByValType = ValType; // 'CP'
4766   bool IsPassedByAddress = false;
4767   if (!IsC11 && !IsN) {
4768     ByValType = Ptr->getType();
4769     IsPassedByAddress = true;
4770   }
4771 
4772   SmallVector<Expr *, 5> APIOrderedArgs;
4773   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4774     APIOrderedArgs.push_back(Args[0]);
4775     switch (Form) {
4776     case Init:
4777     case Load:
4778       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4779       break;
4780     case LoadCopy:
4781     case Copy:
4782     case Arithmetic:
4783     case Xchg:
4784       APIOrderedArgs.push_back(Args[2]); // Val1
4785       APIOrderedArgs.push_back(Args[1]); // Order
4786       break;
4787     case GNUXchg:
4788       APIOrderedArgs.push_back(Args[2]); // Val1
4789       APIOrderedArgs.push_back(Args[3]); // Val2
4790       APIOrderedArgs.push_back(Args[1]); // Order
4791       break;
4792     case C11CmpXchg:
4793       APIOrderedArgs.push_back(Args[2]); // Val1
4794       APIOrderedArgs.push_back(Args[4]); // Val2
4795       APIOrderedArgs.push_back(Args[1]); // Order
4796       APIOrderedArgs.push_back(Args[3]); // OrderFail
4797       break;
4798     case GNUCmpXchg:
4799       APIOrderedArgs.push_back(Args[2]); // Val1
4800       APIOrderedArgs.push_back(Args[4]); // Val2
4801       APIOrderedArgs.push_back(Args[5]); // Weak
4802       APIOrderedArgs.push_back(Args[1]); // Order
4803       APIOrderedArgs.push_back(Args[3]); // OrderFail
4804       break;
4805     }
4806   } else
4807     APIOrderedArgs.append(Args.begin(), Args.end());
4808 
4809   // The first argument's non-CV pointer type is used to deduce the type of
4810   // subsequent arguments, except for:
4811   //  - weak flag (always converted to bool)
4812   //  - memory order (always converted to int)
4813   //  - scope  (always converted to int)
4814   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4815     QualType Ty;
4816     if (i < NumVals[Form] + 1) {
4817       switch (i) {
4818       case 0:
4819         // The first argument is always a pointer. It has a fixed type.
4820         // It is always dereferenced, a nullptr is undefined.
4821         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4822         // Nothing else to do: we already know all we want about this pointer.
4823         continue;
4824       case 1:
4825         // The second argument is the non-atomic operand. For arithmetic, this
4826         // is always passed by value, and for a compare_exchange it is always
4827         // passed by address. For the rest, GNU uses by-address and C11 uses
4828         // by-value.
4829         assert(Form != Load);
4830         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4831           Ty = ValType;
4832         else if (Form == Copy || Form == Xchg) {
4833           if (IsPassedByAddress) {
4834             // The value pointer is always dereferenced, a nullptr is undefined.
4835             CheckNonNullArgument(*this, APIOrderedArgs[i],
4836                                  ExprRange.getBegin());
4837           }
4838           Ty = ByValType;
4839         } else if (Form == Arithmetic)
4840           Ty = Context.getPointerDiffType();
4841         else {
4842           Expr *ValArg = APIOrderedArgs[i];
4843           // The value pointer is always dereferenced, a nullptr is undefined.
4844           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4845           LangAS AS = LangAS::Default;
4846           // Keep address space of non-atomic pointer type.
4847           if (const PointerType *PtrTy =
4848                   ValArg->getType()->getAs<PointerType>()) {
4849             AS = PtrTy->getPointeeType().getAddressSpace();
4850           }
4851           Ty = Context.getPointerType(
4852               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4853         }
4854         break;
4855       case 2:
4856         // The third argument to compare_exchange / GNU exchange is the desired
4857         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4858         if (IsPassedByAddress)
4859           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4860         Ty = ByValType;
4861         break;
4862       case 3:
4863         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4864         Ty = Context.BoolTy;
4865         break;
4866       }
4867     } else {
4868       // The order(s) and scope are always converted to int.
4869       Ty = Context.IntTy;
4870     }
4871 
4872     InitializedEntity Entity =
4873         InitializedEntity::InitializeParameter(Context, Ty, false);
4874     ExprResult Arg = APIOrderedArgs[i];
4875     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4876     if (Arg.isInvalid())
4877       return true;
4878     APIOrderedArgs[i] = Arg.get();
4879   }
4880 
4881   // Permute the arguments into a 'consistent' order.
4882   SmallVector<Expr*, 5> SubExprs;
4883   SubExprs.push_back(Ptr);
4884   switch (Form) {
4885   case Init:
4886     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4887     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4888     break;
4889   case Load:
4890     SubExprs.push_back(APIOrderedArgs[1]); // Order
4891     break;
4892   case LoadCopy:
4893   case Copy:
4894   case Arithmetic:
4895   case Xchg:
4896     SubExprs.push_back(APIOrderedArgs[2]); // Order
4897     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4898     break;
4899   case GNUXchg:
4900     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4901     SubExprs.push_back(APIOrderedArgs[3]); // Order
4902     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4903     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4904     break;
4905   case C11CmpXchg:
4906     SubExprs.push_back(APIOrderedArgs[3]); // Order
4907     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4908     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4909     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4910     break;
4911   case GNUCmpXchg:
4912     SubExprs.push_back(APIOrderedArgs[4]); // Order
4913     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4914     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4915     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4916     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4917     break;
4918   }
4919 
4920   if (SubExprs.size() >= 2 && Form != Init) {
4921     llvm::APSInt Result(32);
4922     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4923         !isValidOrderingForOp(Result.getSExtValue(), Op))
4924       Diag(SubExprs[1]->getBeginLoc(),
4925            diag::warn_atomic_op_has_invalid_memory_order)
4926           << SubExprs[1]->getSourceRange();
4927   }
4928 
4929   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4930     auto *Scope = Args[Args.size() - 1];
4931     llvm::APSInt Result(32);
4932     if (Scope->isIntegerConstantExpr(Result, Context) &&
4933         !ScopeModel->isValid(Result.getZExtValue())) {
4934       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4935           << Scope->getSourceRange();
4936     }
4937     SubExprs.push_back(Scope);
4938   }
4939 
4940   AtomicExpr *AE = new (Context)
4941       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4942 
4943   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4944        Op == AtomicExpr::AO__c11_atomic_store ||
4945        Op == AtomicExpr::AO__opencl_atomic_load ||
4946        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4947       Context.AtomicUsesUnsupportedLibcall(AE))
4948     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4949         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4950              Op == AtomicExpr::AO__opencl_atomic_load)
4951                 ? 0
4952                 : 1);
4953 
4954   if (ValType->isExtIntType()) {
4955     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
4956     return ExprError();
4957   }
4958 
4959   return AE;
4960 }
4961 
4962 /// checkBuiltinArgument - Given a call to a builtin function, perform
4963 /// normal type-checking on the given argument, updating the call in
4964 /// place.  This is useful when a builtin function requires custom
4965 /// type-checking for some of its arguments but not necessarily all of
4966 /// them.
4967 ///
4968 /// Returns true on error.
4969 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4970   FunctionDecl *Fn = E->getDirectCallee();
4971   assert(Fn && "builtin call without direct callee!");
4972 
4973   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4974   InitializedEntity Entity =
4975     InitializedEntity::InitializeParameter(S.Context, Param);
4976 
4977   ExprResult Arg = E->getArg(0);
4978   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4979   if (Arg.isInvalid())
4980     return true;
4981 
4982   E->setArg(ArgIndex, Arg.get());
4983   return false;
4984 }
4985 
4986 /// We have a call to a function like __sync_fetch_and_add, which is an
4987 /// overloaded function based on the pointer type of its first argument.
4988 /// The main BuildCallExpr routines have already promoted the types of
4989 /// arguments because all of these calls are prototyped as void(...).
4990 ///
4991 /// This function goes through and does final semantic checking for these
4992 /// builtins, as well as generating any warnings.
4993 ExprResult
4994 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4995   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4996   Expr *Callee = TheCall->getCallee();
4997   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4998   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4999 
5000   // Ensure that we have at least one argument to do type inference from.
5001   if (TheCall->getNumArgs() < 1) {
5002     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5003         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5004     return ExprError();
5005   }
5006 
5007   // Inspect the first argument of the atomic builtin.  This should always be
5008   // a pointer type, whose element is an integral scalar or pointer type.
5009   // Because it is a pointer type, we don't have to worry about any implicit
5010   // casts here.
5011   // FIXME: We don't allow floating point scalars as input.
5012   Expr *FirstArg = TheCall->getArg(0);
5013   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5014   if (FirstArgResult.isInvalid())
5015     return ExprError();
5016   FirstArg = FirstArgResult.get();
5017   TheCall->setArg(0, FirstArg);
5018 
5019   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5020   if (!pointerType) {
5021     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5022         << FirstArg->getType() << FirstArg->getSourceRange();
5023     return ExprError();
5024   }
5025 
5026   QualType ValType = pointerType->getPointeeType();
5027   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5028       !ValType->isBlockPointerType()) {
5029     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5030         << FirstArg->getType() << FirstArg->getSourceRange();
5031     return ExprError();
5032   }
5033 
5034   if (ValType.isConstQualified()) {
5035     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5036         << FirstArg->getType() << FirstArg->getSourceRange();
5037     return ExprError();
5038   }
5039 
5040   switch (ValType.getObjCLifetime()) {
5041   case Qualifiers::OCL_None:
5042   case Qualifiers::OCL_ExplicitNone:
5043     // okay
5044     break;
5045 
5046   case Qualifiers::OCL_Weak:
5047   case Qualifiers::OCL_Strong:
5048   case Qualifiers::OCL_Autoreleasing:
5049     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5050         << ValType << FirstArg->getSourceRange();
5051     return ExprError();
5052   }
5053 
5054   // Strip any qualifiers off ValType.
5055   ValType = ValType.getUnqualifiedType();
5056 
5057   // The majority of builtins return a value, but a few have special return
5058   // types, so allow them to override appropriately below.
5059   QualType ResultType = ValType;
5060 
5061   // We need to figure out which concrete builtin this maps onto.  For example,
5062   // __sync_fetch_and_add with a 2 byte object turns into
5063   // __sync_fetch_and_add_2.
5064 #define BUILTIN_ROW(x) \
5065   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5066     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5067 
5068   static const unsigned BuiltinIndices[][5] = {
5069     BUILTIN_ROW(__sync_fetch_and_add),
5070     BUILTIN_ROW(__sync_fetch_and_sub),
5071     BUILTIN_ROW(__sync_fetch_and_or),
5072     BUILTIN_ROW(__sync_fetch_and_and),
5073     BUILTIN_ROW(__sync_fetch_and_xor),
5074     BUILTIN_ROW(__sync_fetch_and_nand),
5075 
5076     BUILTIN_ROW(__sync_add_and_fetch),
5077     BUILTIN_ROW(__sync_sub_and_fetch),
5078     BUILTIN_ROW(__sync_and_and_fetch),
5079     BUILTIN_ROW(__sync_or_and_fetch),
5080     BUILTIN_ROW(__sync_xor_and_fetch),
5081     BUILTIN_ROW(__sync_nand_and_fetch),
5082 
5083     BUILTIN_ROW(__sync_val_compare_and_swap),
5084     BUILTIN_ROW(__sync_bool_compare_and_swap),
5085     BUILTIN_ROW(__sync_lock_test_and_set),
5086     BUILTIN_ROW(__sync_lock_release),
5087     BUILTIN_ROW(__sync_swap)
5088   };
5089 #undef BUILTIN_ROW
5090 
5091   // Determine the index of the size.
5092   unsigned SizeIndex;
5093   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5094   case 1: SizeIndex = 0; break;
5095   case 2: SizeIndex = 1; break;
5096   case 4: SizeIndex = 2; break;
5097   case 8: SizeIndex = 3; break;
5098   case 16: SizeIndex = 4; break;
5099   default:
5100     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5101         << FirstArg->getType() << FirstArg->getSourceRange();
5102     return ExprError();
5103   }
5104 
5105   // Each of these builtins has one pointer argument, followed by some number of
5106   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5107   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5108   // as the number of fixed args.
5109   unsigned BuiltinID = FDecl->getBuiltinID();
5110   unsigned BuiltinIndex, NumFixed = 1;
5111   bool WarnAboutSemanticsChange = false;
5112   switch (BuiltinID) {
5113   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5114   case Builtin::BI__sync_fetch_and_add:
5115   case Builtin::BI__sync_fetch_and_add_1:
5116   case Builtin::BI__sync_fetch_and_add_2:
5117   case Builtin::BI__sync_fetch_and_add_4:
5118   case Builtin::BI__sync_fetch_and_add_8:
5119   case Builtin::BI__sync_fetch_and_add_16:
5120     BuiltinIndex = 0;
5121     break;
5122 
5123   case Builtin::BI__sync_fetch_and_sub:
5124   case Builtin::BI__sync_fetch_and_sub_1:
5125   case Builtin::BI__sync_fetch_and_sub_2:
5126   case Builtin::BI__sync_fetch_and_sub_4:
5127   case Builtin::BI__sync_fetch_and_sub_8:
5128   case Builtin::BI__sync_fetch_and_sub_16:
5129     BuiltinIndex = 1;
5130     break;
5131 
5132   case Builtin::BI__sync_fetch_and_or:
5133   case Builtin::BI__sync_fetch_and_or_1:
5134   case Builtin::BI__sync_fetch_and_or_2:
5135   case Builtin::BI__sync_fetch_and_or_4:
5136   case Builtin::BI__sync_fetch_and_or_8:
5137   case Builtin::BI__sync_fetch_and_or_16:
5138     BuiltinIndex = 2;
5139     break;
5140 
5141   case Builtin::BI__sync_fetch_and_and:
5142   case Builtin::BI__sync_fetch_and_and_1:
5143   case Builtin::BI__sync_fetch_and_and_2:
5144   case Builtin::BI__sync_fetch_and_and_4:
5145   case Builtin::BI__sync_fetch_and_and_8:
5146   case Builtin::BI__sync_fetch_and_and_16:
5147     BuiltinIndex = 3;
5148     break;
5149 
5150   case Builtin::BI__sync_fetch_and_xor:
5151   case Builtin::BI__sync_fetch_and_xor_1:
5152   case Builtin::BI__sync_fetch_and_xor_2:
5153   case Builtin::BI__sync_fetch_and_xor_4:
5154   case Builtin::BI__sync_fetch_and_xor_8:
5155   case Builtin::BI__sync_fetch_and_xor_16:
5156     BuiltinIndex = 4;
5157     break;
5158 
5159   case Builtin::BI__sync_fetch_and_nand:
5160   case Builtin::BI__sync_fetch_and_nand_1:
5161   case Builtin::BI__sync_fetch_and_nand_2:
5162   case Builtin::BI__sync_fetch_and_nand_4:
5163   case Builtin::BI__sync_fetch_and_nand_8:
5164   case Builtin::BI__sync_fetch_and_nand_16:
5165     BuiltinIndex = 5;
5166     WarnAboutSemanticsChange = true;
5167     break;
5168 
5169   case Builtin::BI__sync_add_and_fetch:
5170   case Builtin::BI__sync_add_and_fetch_1:
5171   case Builtin::BI__sync_add_and_fetch_2:
5172   case Builtin::BI__sync_add_and_fetch_4:
5173   case Builtin::BI__sync_add_and_fetch_8:
5174   case Builtin::BI__sync_add_and_fetch_16:
5175     BuiltinIndex = 6;
5176     break;
5177 
5178   case Builtin::BI__sync_sub_and_fetch:
5179   case Builtin::BI__sync_sub_and_fetch_1:
5180   case Builtin::BI__sync_sub_and_fetch_2:
5181   case Builtin::BI__sync_sub_and_fetch_4:
5182   case Builtin::BI__sync_sub_and_fetch_8:
5183   case Builtin::BI__sync_sub_and_fetch_16:
5184     BuiltinIndex = 7;
5185     break;
5186 
5187   case Builtin::BI__sync_and_and_fetch:
5188   case Builtin::BI__sync_and_and_fetch_1:
5189   case Builtin::BI__sync_and_and_fetch_2:
5190   case Builtin::BI__sync_and_and_fetch_4:
5191   case Builtin::BI__sync_and_and_fetch_8:
5192   case Builtin::BI__sync_and_and_fetch_16:
5193     BuiltinIndex = 8;
5194     break;
5195 
5196   case Builtin::BI__sync_or_and_fetch:
5197   case Builtin::BI__sync_or_and_fetch_1:
5198   case Builtin::BI__sync_or_and_fetch_2:
5199   case Builtin::BI__sync_or_and_fetch_4:
5200   case Builtin::BI__sync_or_and_fetch_8:
5201   case Builtin::BI__sync_or_and_fetch_16:
5202     BuiltinIndex = 9;
5203     break;
5204 
5205   case Builtin::BI__sync_xor_and_fetch:
5206   case Builtin::BI__sync_xor_and_fetch_1:
5207   case Builtin::BI__sync_xor_and_fetch_2:
5208   case Builtin::BI__sync_xor_and_fetch_4:
5209   case Builtin::BI__sync_xor_and_fetch_8:
5210   case Builtin::BI__sync_xor_and_fetch_16:
5211     BuiltinIndex = 10;
5212     break;
5213 
5214   case Builtin::BI__sync_nand_and_fetch:
5215   case Builtin::BI__sync_nand_and_fetch_1:
5216   case Builtin::BI__sync_nand_and_fetch_2:
5217   case Builtin::BI__sync_nand_and_fetch_4:
5218   case Builtin::BI__sync_nand_and_fetch_8:
5219   case Builtin::BI__sync_nand_and_fetch_16:
5220     BuiltinIndex = 11;
5221     WarnAboutSemanticsChange = true;
5222     break;
5223 
5224   case Builtin::BI__sync_val_compare_and_swap:
5225   case Builtin::BI__sync_val_compare_and_swap_1:
5226   case Builtin::BI__sync_val_compare_and_swap_2:
5227   case Builtin::BI__sync_val_compare_and_swap_4:
5228   case Builtin::BI__sync_val_compare_and_swap_8:
5229   case Builtin::BI__sync_val_compare_and_swap_16:
5230     BuiltinIndex = 12;
5231     NumFixed = 2;
5232     break;
5233 
5234   case Builtin::BI__sync_bool_compare_and_swap:
5235   case Builtin::BI__sync_bool_compare_and_swap_1:
5236   case Builtin::BI__sync_bool_compare_and_swap_2:
5237   case Builtin::BI__sync_bool_compare_and_swap_4:
5238   case Builtin::BI__sync_bool_compare_and_swap_8:
5239   case Builtin::BI__sync_bool_compare_and_swap_16:
5240     BuiltinIndex = 13;
5241     NumFixed = 2;
5242     ResultType = Context.BoolTy;
5243     break;
5244 
5245   case Builtin::BI__sync_lock_test_and_set:
5246   case Builtin::BI__sync_lock_test_and_set_1:
5247   case Builtin::BI__sync_lock_test_and_set_2:
5248   case Builtin::BI__sync_lock_test_and_set_4:
5249   case Builtin::BI__sync_lock_test_and_set_8:
5250   case Builtin::BI__sync_lock_test_and_set_16:
5251     BuiltinIndex = 14;
5252     break;
5253 
5254   case Builtin::BI__sync_lock_release:
5255   case Builtin::BI__sync_lock_release_1:
5256   case Builtin::BI__sync_lock_release_2:
5257   case Builtin::BI__sync_lock_release_4:
5258   case Builtin::BI__sync_lock_release_8:
5259   case Builtin::BI__sync_lock_release_16:
5260     BuiltinIndex = 15;
5261     NumFixed = 0;
5262     ResultType = Context.VoidTy;
5263     break;
5264 
5265   case Builtin::BI__sync_swap:
5266   case Builtin::BI__sync_swap_1:
5267   case Builtin::BI__sync_swap_2:
5268   case Builtin::BI__sync_swap_4:
5269   case Builtin::BI__sync_swap_8:
5270   case Builtin::BI__sync_swap_16:
5271     BuiltinIndex = 16;
5272     break;
5273   }
5274 
5275   // Now that we know how many fixed arguments we expect, first check that we
5276   // have at least that many.
5277   if (TheCall->getNumArgs() < 1+NumFixed) {
5278     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5279         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5280         << Callee->getSourceRange();
5281     return ExprError();
5282   }
5283 
5284   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5285       << Callee->getSourceRange();
5286 
5287   if (WarnAboutSemanticsChange) {
5288     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5289         << Callee->getSourceRange();
5290   }
5291 
5292   // Get the decl for the concrete builtin from this, we can tell what the
5293   // concrete integer type we should convert to is.
5294   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5295   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5296   FunctionDecl *NewBuiltinDecl;
5297   if (NewBuiltinID == BuiltinID)
5298     NewBuiltinDecl = FDecl;
5299   else {
5300     // Perform builtin lookup to avoid redeclaring it.
5301     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5302     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5303     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5304     assert(Res.getFoundDecl());
5305     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5306     if (!NewBuiltinDecl)
5307       return ExprError();
5308   }
5309 
5310   // The first argument --- the pointer --- has a fixed type; we
5311   // deduce the types of the rest of the arguments accordingly.  Walk
5312   // the remaining arguments, converting them to the deduced value type.
5313   for (unsigned i = 0; i != NumFixed; ++i) {
5314     ExprResult Arg = TheCall->getArg(i+1);
5315 
5316     // GCC does an implicit conversion to the pointer or integer ValType.  This
5317     // can fail in some cases (1i -> int**), check for this error case now.
5318     // Initialize the argument.
5319     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5320                                                    ValType, /*consume*/ false);
5321     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5322     if (Arg.isInvalid())
5323       return ExprError();
5324 
5325     // Okay, we have something that *can* be converted to the right type.  Check
5326     // to see if there is a potentially weird extension going on here.  This can
5327     // happen when you do an atomic operation on something like an char* and
5328     // pass in 42.  The 42 gets converted to char.  This is even more strange
5329     // for things like 45.123 -> char, etc.
5330     // FIXME: Do this check.
5331     TheCall->setArg(i+1, Arg.get());
5332   }
5333 
5334   // Create a new DeclRefExpr to refer to the new decl.
5335   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5336       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5337       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5338       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5339 
5340   // Set the callee in the CallExpr.
5341   // FIXME: This loses syntactic information.
5342   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5343   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5344                                               CK_BuiltinFnToFnPtr);
5345   TheCall->setCallee(PromotedCall.get());
5346 
5347   // Change the result type of the call to match the original value type. This
5348   // is arbitrary, but the codegen for these builtins ins design to handle it
5349   // gracefully.
5350   TheCall->setType(ResultType);
5351 
5352   // Prohibit use of _ExtInt with atomic builtins.
5353   // The arguments would have already been converted to the first argument's
5354   // type, so only need to check the first argument.
5355   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5356   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5357     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5358     return ExprError();
5359   }
5360 
5361   return TheCallResult;
5362 }
5363 
5364 /// SemaBuiltinNontemporalOverloaded - We have a call to
5365 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5366 /// overloaded function based on the pointer type of its last argument.
5367 ///
5368 /// This function goes through and does final semantic checking for these
5369 /// builtins.
5370 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5371   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5372   DeclRefExpr *DRE =
5373       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5374   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5375   unsigned BuiltinID = FDecl->getBuiltinID();
5376   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5377           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5378          "Unexpected nontemporal load/store builtin!");
5379   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5380   unsigned numArgs = isStore ? 2 : 1;
5381 
5382   // Ensure that we have the proper number of arguments.
5383   if (checkArgCount(*this, TheCall, numArgs))
5384     return ExprError();
5385 
5386   // Inspect the last argument of the nontemporal builtin.  This should always
5387   // be a pointer type, from which we imply the type of the memory access.
5388   // Because it is a pointer type, we don't have to worry about any implicit
5389   // casts here.
5390   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5391   ExprResult PointerArgResult =
5392       DefaultFunctionArrayLvalueConversion(PointerArg);
5393 
5394   if (PointerArgResult.isInvalid())
5395     return ExprError();
5396   PointerArg = PointerArgResult.get();
5397   TheCall->setArg(numArgs - 1, PointerArg);
5398 
5399   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5400   if (!pointerType) {
5401     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5402         << PointerArg->getType() << PointerArg->getSourceRange();
5403     return ExprError();
5404   }
5405 
5406   QualType ValType = pointerType->getPointeeType();
5407 
5408   // Strip any qualifiers off ValType.
5409   ValType = ValType.getUnqualifiedType();
5410   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5411       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5412       !ValType->isVectorType()) {
5413     Diag(DRE->getBeginLoc(),
5414          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5415         << PointerArg->getType() << PointerArg->getSourceRange();
5416     return ExprError();
5417   }
5418 
5419   if (!isStore) {
5420     TheCall->setType(ValType);
5421     return TheCallResult;
5422   }
5423 
5424   ExprResult ValArg = TheCall->getArg(0);
5425   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5426       Context, ValType, /*consume*/ false);
5427   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5428   if (ValArg.isInvalid())
5429     return ExprError();
5430 
5431   TheCall->setArg(0, ValArg.get());
5432   TheCall->setType(Context.VoidTy);
5433   return TheCallResult;
5434 }
5435 
5436 /// CheckObjCString - Checks that the argument to the builtin
5437 /// CFString constructor is correct
5438 /// Note: It might also make sense to do the UTF-16 conversion here (would
5439 /// simplify the backend).
5440 bool Sema::CheckObjCString(Expr *Arg) {
5441   Arg = Arg->IgnoreParenCasts();
5442   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5443 
5444   if (!Literal || !Literal->isAscii()) {
5445     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5446         << Arg->getSourceRange();
5447     return true;
5448   }
5449 
5450   if (Literal->containsNonAsciiOrNull()) {
5451     StringRef String = Literal->getString();
5452     unsigned NumBytes = String.size();
5453     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5454     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5455     llvm::UTF16 *ToPtr = &ToBuf[0];
5456 
5457     llvm::ConversionResult Result =
5458         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5459                                  ToPtr + NumBytes, llvm::strictConversion);
5460     // Check for conversion failure.
5461     if (Result != llvm::conversionOK)
5462       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5463           << Arg->getSourceRange();
5464   }
5465   return false;
5466 }
5467 
5468 /// CheckObjCString - Checks that the format string argument to the os_log()
5469 /// and os_trace() functions is correct, and converts it to const char *.
5470 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5471   Arg = Arg->IgnoreParenCasts();
5472   auto *Literal = dyn_cast<StringLiteral>(Arg);
5473   if (!Literal) {
5474     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5475       Literal = ObjcLiteral->getString();
5476     }
5477   }
5478 
5479   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5480     return ExprError(
5481         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5482         << Arg->getSourceRange());
5483   }
5484 
5485   ExprResult Result(Literal);
5486   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5487   InitializedEntity Entity =
5488       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5489   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5490   return Result;
5491 }
5492 
5493 /// Check that the user is calling the appropriate va_start builtin for the
5494 /// target and calling convention.
5495 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5496   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5497   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5498   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5499                     TT.getArch() == llvm::Triple::aarch64_32);
5500   bool IsWindows = TT.isOSWindows();
5501   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5502   if (IsX64 || IsAArch64) {
5503     CallingConv CC = CC_C;
5504     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5505       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5506     if (IsMSVAStart) {
5507       // Don't allow this in System V ABI functions.
5508       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5509         return S.Diag(Fn->getBeginLoc(),
5510                       diag::err_ms_va_start_used_in_sysv_function);
5511     } else {
5512       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5513       // On x64 Windows, don't allow this in System V ABI functions.
5514       // (Yes, that means there's no corresponding way to support variadic
5515       // System V ABI functions on Windows.)
5516       if ((IsWindows && CC == CC_X86_64SysV) ||
5517           (!IsWindows && CC == CC_Win64))
5518         return S.Diag(Fn->getBeginLoc(),
5519                       diag::err_va_start_used_in_wrong_abi_function)
5520                << !IsWindows;
5521     }
5522     return false;
5523   }
5524 
5525   if (IsMSVAStart)
5526     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5527   return false;
5528 }
5529 
5530 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5531                                              ParmVarDecl **LastParam = nullptr) {
5532   // Determine whether the current function, block, or obj-c method is variadic
5533   // and get its parameter list.
5534   bool IsVariadic = false;
5535   ArrayRef<ParmVarDecl *> Params;
5536   DeclContext *Caller = S.CurContext;
5537   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5538     IsVariadic = Block->isVariadic();
5539     Params = Block->parameters();
5540   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5541     IsVariadic = FD->isVariadic();
5542     Params = FD->parameters();
5543   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5544     IsVariadic = MD->isVariadic();
5545     // FIXME: This isn't correct for methods (results in bogus warning).
5546     Params = MD->parameters();
5547   } else if (isa<CapturedDecl>(Caller)) {
5548     // We don't support va_start in a CapturedDecl.
5549     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5550     return true;
5551   } else {
5552     // This must be some other declcontext that parses exprs.
5553     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5554     return true;
5555   }
5556 
5557   if (!IsVariadic) {
5558     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5559     return true;
5560   }
5561 
5562   if (LastParam)
5563     *LastParam = Params.empty() ? nullptr : Params.back();
5564 
5565   return false;
5566 }
5567 
5568 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5569 /// for validity.  Emit an error and return true on failure; return false
5570 /// on success.
5571 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5572   Expr *Fn = TheCall->getCallee();
5573 
5574   if (checkVAStartABI(*this, BuiltinID, Fn))
5575     return true;
5576 
5577   if (TheCall->getNumArgs() > 2) {
5578     Diag(TheCall->getArg(2)->getBeginLoc(),
5579          diag::err_typecheck_call_too_many_args)
5580         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5581         << Fn->getSourceRange()
5582         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5583                        (*(TheCall->arg_end() - 1))->getEndLoc());
5584     return true;
5585   }
5586 
5587   if (TheCall->getNumArgs() < 2) {
5588     return Diag(TheCall->getEndLoc(),
5589                 diag::err_typecheck_call_too_few_args_at_least)
5590            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5591   }
5592 
5593   // Type-check the first argument normally.
5594   if (checkBuiltinArgument(*this, TheCall, 0))
5595     return true;
5596 
5597   // Check that the current function is variadic, and get its last parameter.
5598   ParmVarDecl *LastParam;
5599   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5600     return true;
5601 
5602   // Verify that the second argument to the builtin is the last argument of the
5603   // current function or method.
5604   bool SecondArgIsLastNamedArgument = false;
5605   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5606 
5607   // These are valid if SecondArgIsLastNamedArgument is false after the next
5608   // block.
5609   QualType Type;
5610   SourceLocation ParamLoc;
5611   bool IsCRegister = false;
5612 
5613   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5614     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5615       SecondArgIsLastNamedArgument = PV == LastParam;
5616 
5617       Type = PV->getType();
5618       ParamLoc = PV->getLocation();
5619       IsCRegister =
5620           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5621     }
5622   }
5623 
5624   if (!SecondArgIsLastNamedArgument)
5625     Diag(TheCall->getArg(1)->getBeginLoc(),
5626          diag::warn_second_arg_of_va_start_not_last_named_param);
5627   else if (IsCRegister || Type->isReferenceType() ||
5628            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5629              // Promotable integers are UB, but enumerations need a bit of
5630              // extra checking to see what their promotable type actually is.
5631              if (!Type->isPromotableIntegerType())
5632                return false;
5633              if (!Type->isEnumeralType())
5634                return true;
5635              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5636              return !(ED &&
5637                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5638            }()) {
5639     unsigned Reason = 0;
5640     if (Type->isReferenceType())  Reason = 1;
5641     else if (IsCRegister)         Reason = 2;
5642     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5643     Diag(ParamLoc, diag::note_parameter_type) << Type;
5644   }
5645 
5646   TheCall->setType(Context.VoidTy);
5647   return false;
5648 }
5649 
5650 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5651   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5652   //                 const char *named_addr);
5653 
5654   Expr *Func = Call->getCallee();
5655 
5656   if (Call->getNumArgs() < 3)
5657     return Diag(Call->getEndLoc(),
5658                 diag::err_typecheck_call_too_few_args_at_least)
5659            << 0 /*function call*/ << 3 << Call->getNumArgs();
5660 
5661   // Type-check the first argument normally.
5662   if (checkBuiltinArgument(*this, Call, 0))
5663     return true;
5664 
5665   // Check that the current function is variadic.
5666   if (checkVAStartIsInVariadicFunction(*this, Func))
5667     return true;
5668 
5669   // __va_start on Windows does not validate the parameter qualifiers
5670 
5671   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5672   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5673 
5674   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5675   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5676 
5677   const QualType &ConstCharPtrTy =
5678       Context.getPointerType(Context.CharTy.withConst());
5679   if (!Arg1Ty->isPointerType() ||
5680       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5681     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5682         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5683         << 0                                      /* qualifier difference */
5684         << 3                                      /* parameter mismatch */
5685         << 2 << Arg1->getType() << ConstCharPtrTy;
5686 
5687   const QualType SizeTy = Context.getSizeType();
5688   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5689     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5690         << Arg2->getType() << SizeTy << 1 /* different class */
5691         << 0                              /* qualifier difference */
5692         << 3                              /* parameter mismatch */
5693         << 3 << Arg2->getType() << SizeTy;
5694 
5695   return false;
5696 }
5697 
5698 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5699 /// friends.  This is declared to take (...), so we have to check everything.
5700 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5701   if (TheCall->getNumArgs() < 2)
5702     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5703            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5704   if (TheCall->getNumArgs() > 2)
5705     return Diag(TheCall->getArg(2)->getBeginLoc(),
5706                 diag::err_typecheck_call_too_many_args)
5707            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5708            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5709                           (*(TheCall->arg_end() - 1))->getEndLoc());
5710 
5711   ExprResult OrigArg0 = TheCall->getArg(0);
5712   ExprResult OrigArg1 = TheCall->getArg(1);
5713 
5714   // Do standard promotions between the two arguments, returning their common
5715   // type.
5716   QualType Res = UsualArithmeticConversions(
5717       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5718   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5719     return true;
5720 
5721   // Make sure any conversions are pushed back into the call; this is
5722   // type safe since unordered compare builtins are declared as "_Bool
5723   // foo(...)".
5724   TheCall->setArg(0, OrigArg0.get());
5725   TheCall->setArg(1, OrigArg1.get());
5726 
5727   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5728     return false;
5729 
5730   // If the common type isn't a real floating type, then the arguments were
5731   // invalid for this operation.
5732   if (Res.isNull() || !Res->isRealFloatingType())
5733     return Diag(OrigArg0.get()->getBeginLoc(),
5734                 diag::err_typecheck_call_invalid_ordered_compare)
5735            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5736            << SourceRange(OrigArg0.get()->getBeginLoc(),
5737                           OrigArg1.get()->getEndLoc());
5738 
5739   return false;
5740 }
5741 
5742 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5743 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5744 /// to check everything. We expect the last argument to be a floating point
5745 /// value.
5746 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5747   if (TheCall->getNumArgs() < NumArgs)
5748     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5749            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5750   if (TheCall->getNumArgs() > NumArgs)
5751     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5752                 diag::err_typecheck_call_too_many_args)
5753            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5754            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5755                           (*(TheCall->arg_end() - 1))->getEndLoc());
5756 
5757   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5758   // on all preceding parameters just being int.  Try all of those.
5759   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5760     Expr *Arg = TheCall->getArg(i);
5761 
5762     if (Arg->isTypeDependent())
5763       return false;
5764 
5765     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5766 
5767     if (Res.isInvalid())
5768       return true;
5769     TheCall->setArg(i, Res.get());
5770   }
5771 
5772   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5773 
5774   if (OrigArg->isTypeDependent())
5775     return false;
5776 
5777   // Usual Unary Conversions will convert half to float, which we want for
5778   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5779   // type how it is, but do normal L->Rvalue conversions.
5780   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5781     OrigArg = UsualUnaryConversions(OrigArg).get();
5782   else
5783     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5784   TheCall->setArg(NumArgs - 1, OrigArg);
5785 
5786   // This operation requires a non-_Complex floating-point number.
5787   if (!OrigArg->getType()->isRealFloatingType())
5788     return Diag(OrigArg->getBeginLoc(),
5789                 diag::err_typecheck_call_invalid_unary_fp)
5790            << OrigArg->getType() << OrigArg->getSourceRange();
5791 
5792   return false;
5793 }
5794 
5795 // Customized Sema Checking for VSX builtins that have the following signature:
5796 // vector [...] builtinName(vector [...], vector [...], const int);
5797 // Which takes the same type of vectors (any legal vector type) for the first
5798 // two arguments and takes compile time constant for the third argument.
5799 // Example builtins are :
5800 // vector double vec_xxpermdi(vector double, vector double, int);
5801 // vector short vec_xxsldwi(vector short, vector short, int);
5802 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5803   unsigned ExpectedNumArgs = 3;
5804   if (TheCall->getNumArgs() < ExpectedNumArgs)
5805     return Diag(TheCall->getEndLoc(),
5806                 diag::err_typecheck_call_too_few_args_at_least)
5807            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5808            << TheCall->getSourceRange();
5809 
5810   if (TheCall->getNumArgs() > ExpectedNumArgs)
5811     return Diag(TheCall->getEndLoc(),
5812                 diag::err_typecheck_call_too_many_args_at_most)
5813            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5814            << TheCall->getSourceRange();
5815 
5816   // Check the third argument is a compile time constant
5817   llvm::APSInt Value;
5818   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5819     return Diag(TheCall->getBeginLoc(),
5820                 diag::err_vsx_builtin_nonconstant_argument)
5821            << 3 /* argument index */ << TheCall->getDirectCallee()
5822            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5823                           TheCall->getArg(2)->getEndLoc());
5824 
5825   QualType Arg1Ty = TheCall->getArg(0)->getType();
5826   QualType Arg2Ty = TheCall->getArg(1)->getType();
5827 
5828   // Check the type of argument 1 and argument 2 are vectors.
5829   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5830   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5831       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5832     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5833            << TheCall->getDirectCallee()
5834            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5835                           TheCall->getArg(1)->getEndLoc());
5836   }
5837 
5838   // Check the first two arguments are the same type.
5839   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5840     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5841            << TheCall->getDirectCallee()
5842            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5843                           TheCall->getArg(1)->getEndLoc());
5844   }
5845 
5846   // When default clang type checking is turned off and the customized type
5847   // checking is used, the returning type of the function must be explicitly
5848   // set. Otherwise it is _Bool by default.
5849   TheCall->setType(Arg1Ty);
5850 
5851   return false;
5852 }
5853 
5854 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5855 // This is declared to take (...), so we have to check everything.
5856 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5857   if (TheCall->getNumArgs() < 2)
5858     return ExprError(Diag(TheCall->getEndLoc(),
5859                           diag::err_typecheck_call_too_few_args_at_least)
5860                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5861                      << TheCall->getSourceRange());
5862 
5863   // Determine which of the following types of shufflevector we're checking:
5864   // 1) unary, vector mask: (lhs, mask)
5865   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5866   QualType resType = TheCall->getArg(0)->getType();
5867   unsigned numElements = 0;
5868 
5869   if (!TheCall->getArg(0)->isTypeDependent() &&
5870       !TheCall->getArg(1)->isTypeDependent()) {
5871     QualType LHSType = TheCall->getArg(0)->getType();
5872     QualType RHSType = TheCall->getArg(1)->getType();
5873 
5874     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5875       return ExprError(
5876           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5877           << TheCall->getDirectCallee()
5878           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5879                          TheCall->getArg(1)->getEndLoc()));
5880 
5881     numElements = LHSType->castAs<VectorType>()->getNumElements();
5882     unsigned numResElements = TheCall->getNumArgs() - 2;
5883 
5884     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5885     // with mask.  If so, verify that RHS is an integer vector type with the
5886     // same number of elts as lhs.
5887     if (TheCall->getNumArgs() == 2) {
5888       if (!RHSType->hasIntegerRepresentation() ||
5889           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5890         return ExprError(Diag(TheCall->getBeginLoc(),
5891                               diag::err_vec_builtin_incompatible_vector)
5892                          << TheCall->getDirectCallee()
5893                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5894                                         TheCall->getArg(1)->getEndLoc()));
5895     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5896       return ExprError(Diag(TheCall->getBeginLoc(),
5897                             diag::err_vec_builtin_incompatible_vector)
5898                        << TheCall->getDirectCallee()
5899                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5900                                       TheCall->getArg(1)->getEndLoc()));
5901     } else if (numElements != numResElements) {
5902       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5903       resType = Context.getVectorType(eltType, numResElements,
5904                                       VectorType::GenericVector);
5905     }
5906   }
5907 
5908   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5909     if (TheCall->getArg(i)->isTypeDependent() ||
5910         TheCall->getArg(i)->isValueDependent())
5911       continue;
5912 
5913     llvm::APSInt Result(32);
5914     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5915       return ExprError(Diag(TheCall->getBeginLoc(),
5916                             diag::err_shufflevector_nonconstant_argument)
5917                        << TheCall->getArg(i)->getSourceRange());
5918 
5919     // Allow -1 which will be translated to undef in the IR.
5920     if (Result.isSigned() && Result.isAllOnesValue())
5921       continue;
5922 
5923     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5924       return ExprError(Diag(TheCall->getBeginLoc(),
5925                             diag::err_shufflevector_argument_too_large)
5926                        << TheCall->getArg(i)->getSourceRange());
5927   }
5928 
5929   SmallVector<Expr*, 32> exprs;
5930 
5931   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5932     exprs.push_back(TheCall->getArg(i));
5933     TheCall->setArg(i, nullptr);
5934   }
5935 
5936   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5937                                          TheCall->getCallee()->getBeginLoc(),
5938                                          TheCall->getRParenLoc());
5939 }
5940 
5941 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5942 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5943                                        SourceLocation BuiltinLoc,
5944                                        SourceLocation RParenLoc) {
5945   ExprValueKind VK = VK_RValue;
5946   ExprObjectKind OK = OK_Ordinary;
5947   QualType DstTy = TInfo->getType();
5948   QualType SrcTy = E->getType();
5949 
5950   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5951     return ExprError(Diag(BuiltinLoc,
5952                           diag::err_convertvector_non_vector)
5953                      << E->getSourceRange());
5954   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5955     return ExprError(Diag(BuiltinLoc,
5956                           diag::err_convertvector_non_vector_type));
5957 
5958   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5959     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5960     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5961     if (SrcElts != DstElts)
5962       return ExprError(Diag(BuiltinLoc,
5963                             diag::err_convertvector_incompatible_vector)
5964                        << E->getSourceRange());
5965   }
5966 
5967   return new (Context)
5968       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5969 }
5970 
5971 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5972 // This is declared to take (const void*, ...) and can take two
5973 // optional constant int args.
5974 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5975   unsigned NumArgs = TheCall->getNumArgs();
5976 
5977   if (NumArgs > 3)
5978     return Diag(TheCall->getEndLoc(),
5979                 diag::err_typecheck_call_too_many_args_at_most)
5980            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5981 
5982   // Argument 0 is checked for us and the remaining arguments must be
5983   // constant integers.
5984   for (unsigned i = 1; i != NumArgs; ++i)
5985     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5986       return true;
5987 
5988   return false;
5989 }
5990 
5991 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5992 // __assume does not evaluate its arguments, and should warn if its argument
5993 // has side effects.
5994 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5995   Expr *Arg = TheCall->getArg(0);
5996   if (Arg->isInstantiationDependent()) return false;
5997 
5998   if (Arg->HasSideEffects(Context))
5999     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6000         << Arg->getSourceRange()
6001         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6002 
6003   return false;
6004 }
6005 
6006 /// Handle __builtin_alloca_with_align. This is declared
6007 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6008 /// than 8.
6009 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6010   // The alignment must be a constant integer.
6011   Expr *Arg = TheCall->getArg(1);
6012 
6013   // We can't check the value of a dependent argument.
6014   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6015     if (const auto *UE =
6016             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6017       if (UE->getKind() == UETT_AlignOf ||
6018           UE->getKind() == UETT_PreferredAlignOf)
6019         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6020             << Arg->getSourceRange();
6021 
6022     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6023 
6024     if (!Result.isPowerOf2())
6025       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6026              << Arg->getSourceRange();
6027 
6028     if (Result < Context.getCharWidth())
6029       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6030              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6031 
6032     if (Result > std::numeric_limits<int32_t>::max())
6033       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6034              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6035   }
6036 
6037   return false;
6038 }
6039 
6040 /// Handle __builtin_assume_aligned. This is declared
6041 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6042 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6043   unsigned NumArgs = TheCall->getNumArgs();
6044 
6045   if (NumArgs > 3)
6046     return Diag(TheCall->getEndLoc(),
6047                 diag::err_typecheck_call_too_many_args_at_most)
6048            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6049 
6050   // The alignment must be a constant integer.
6051   Expr *Arg = TheCall->getArg(1);
6052 
6053   // We can't check the value of a dependent argument.
6054   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6055     llvm::APSInt Result;
6056     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6057       return true;
6058 
6059     if (!Result.isPowerOf2())
6060       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6061              << Arg->getSourceRange();
6062 
6063     if (Result > Sema::MaximumAlignment)
6064       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6065           << Arg->getSourceRange() << Sema::MaximumAlignment;
6066   }
6067 
6068   if (NumArgs > 2) {
6069     ExprResult Arg(TheCall->getArg(2));
6070     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6071       Context.getSizeType(), false);
6072     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6073     if (Arg.isInvalid()) return true;
6074     TheCall->setArg(2, Arg.get());
6075   }
6076 
6077   return false;
6078 }
6079 
6080 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6081   unsigned BuiltinID =
6082       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6083   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6084 
6085   unsigned NumArgs = TheCall->getNumArgs();
6086   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6087   if (NumArgs < NumRequiredArgs) {
6088     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6089            << 0 /* function call */ << NumRequiredArgs << NumArgs
6090            << TheCall->getSourceRange();
6091   }
6092   if (NumArgs >= NumRequiredArgs + 0x100) {
6093     return Diag(TheCall->getEndLoc(),
6094                 diag::err_typecheck_call_too_many_args_at_most)
6095            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6096            << TheCall->getSourceRange();
6097   }
6098   unsigned i = 0;
6099 
6100   // For formatting call, check buffer arg.
6101   if (!IsSizeCall) {
6102     ExprResult Arg(TheCall->getArg(i));
6103     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6104         Context, Context.VoidPtrTy, false);
6105     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6106     if (Arg.isInvalid())
6107       return true;
6108     TheCall->setArg(i, Arg.get());
6109     i++;
6110   }
6111 
6112   // Check string literal arg.
6113   unsigned FormatIdx = i;
6114   {
6115     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6116     if (Arg.isInvalid())
6117       return true;
6118     TheCall->setArg(i, Arg.get());
6119     i++;
6120   }
6121 
6122   // Make sure variadic args are scalar.
6123   unsigned FirstDataArg = i;
6124   while (i < NumArgs) {
6125     ExprResult Arg = DefaultVariadicArgumentPromotion(
6126         TheCall->getArg(i), VariadicFunction, nullptr);
6127     if (Arg.isInvalid())
6128       return true;
6129     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6130     if (ArgSize.getQuantity() >= 0x100) {
6131       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6132              << i << (int)ArgSize.getQuantity() << 0xff
6133              << TheCall->getSourceRange();
6134     }
6135     TheCall->setArg(i, Arg.get());
6136     i++;
6137   }
6138 
6139   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6140   // call to avoid duplicate diagnostics.
6141   if (!IsSizeCall) {
6142     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6143     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6144     bool Success = CheckFormatArguments(
6145         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6146         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6147         CheckedVarArgs);
6148     if (!Success)
6149       return true;
6150   }
6151 
6152   if (IsSizeCall) {
6153     TheCall->setType(Context.getSizeType());
6154   } else {
6155     TheCall->setType(Context.VoidPtrTy);
6156   }
6157   return false;
6158 }
6159 
6160 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6161 /// TheCall is a constant expression.
6162 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6163                                   llvm::APSInt &Result) {
6164   Expr *Arg = TheCall->getArg(ArgNum);
6165   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6166   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6167 
6168   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6169 
6170   if (!Arg->isIntegerConstantExpr(Result, Context))
6171     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6172            << FDecl->getDeclName() << Arg->getSourceRange();
6173 
6174   return false;
6175 }
6176 
6177 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6178 /// TheCall is a constant expression in the range [Low, High].
6179 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6180                                        int Low, int High, bool RangeIsError) {
6181   if (isConstantEvaluated())
6182     return false;
6183   llvm::APSInt Result;
6184 
6185   // We can't check the value of a dependent argument.
6186   Expr *Arg = TheCall->getArg(ArgNum);
6187   if (Arg->isTypeDependent() || Arg->isValueDependent())
6188     return false;
6189 
6190   // Check constant-ness first.
6191   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6192     return true;
6193 
6194   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6195     if (RangeIsError)
6196       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6197              << Result.toString(10) << Low << High << Arg->getSourceRange();
6198     else
6199       // Defer the warning until we know if the code will be emitted so that
6200       // dead code can ignore this.
6201       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6202                           PDiag(diag::warn_argument_invalid_range)
6203                               << Result.toString(10) << Low << High
6204                               << Arg->getSourceRange());
6205   }
6206 
6207   return false;
6208 }
6209 
6210 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6211 /// TheCall is a constant expression is a multiple of Num..
6212 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6213                                           unsigned Num) {
6214   llvm::APSInt Result;
6215 
6216   // We can't check the value of a dependent argument.
6217   Expr *Arg = TheCall->getArg(ArgNum);
6218   if (Arg->isTypeDependent() || Arg->isValueDependent())
6219     return false;
6220 
6221   // Check constant-ness first.
6222   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6223     return true;
6224 
6225   if (Result.getSExtValue() % Num != 0)
6226     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6227            << Num << Arg->getSourceRange();
6228 
6229   return false;
6230 }
6231 
6232 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6233 /// constant expression representing a power of 2.
6234 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6235   llvm::APSInt Result;
6236 
6237   // We can't check the value of a dependent argument.
6238   Expr *Arg = TheCall->getArg(ArgNum);
6239   if (Arg->isTypeDependent() || Arg->isValueDependent())
6240     return false;
6241 
6242   // Check constant-ness first.
6243   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6244     return true;
6245 
6246   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6247   // and only if x is a power of 2.
6248   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6249     return false;
6250 
6251   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6252          << Arg->getSourceRange();
6253 }
6254 
6255 static bool IsShiftedByte(llvm::APSInt Value) {
6256   if (Value.isNegative())
6257     return false;
6258 
6259   // Check if it's a shifted byte, by shifting it down
6260   while (true) {
6261     // If the value fits in the bottom byte, the check passes.
6262     if (Value < 0x100)
6263       return true;
6264 
6265     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6266     // fails.
6267     if ((Value & 0xFF) != 0)
6268       return false;
6269 
6270     // If the bottom 8 bits are all 0, but something above that is nonzero,
6271     // then shifting the value right by 8 bits won't affect whether it's a
6272     // shifted byte or not. So do that, and go round again.
6273     Value >>= 8;
6274   }
6275 }
6276 
6277 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6278 /// a constant expression representing an arbitrary byte value shifted left by
6279 /// a multiple of 8 bits.
6280 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6281                                              unsigned ArgBits) {
6282   llvm::APSInt Result;
6283 
6284   // We can't check the value of a dependent argument.
6285   Expr *Arg = TheCall->getArg(ArgNum);
6286   if (Arg->isTypeDependent() || Arg->isValueDependent())
6287     return false;
6288 
6289   // Check constant-ness first.
6290   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6291     return true;
6292 
6293   // Truncate to the given size.
6294   Result = Result.getLoBits(ArgBits);
6295   Result.setIsUnsigned(true);
6296 
6297   if (IsShiftedByte(Result))
6298     return false;
6299 
6300   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6301          << Arg->getSourceRange();
6302 }
6303 
6304 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6305 /// TheCall is a constant expression representing either a shifted byte value,
6306 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6307 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6308 /// Arm MVE intrinsics.
6309 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6310                                                    int ArgNum,
6311                                                    unsigned ArgBits) {
6312   llvm::APSInt Result;
6313 
6314   // We can't check the value of a dependent argument.
6315   Expr *Arg = TheCall->getArg(ArgNum);
6316   if (Arg->isTypeDependent() || Arg->isValueDependent())
6317     return false;
6318 
6319   // Check constant-ness first.
6320   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6321     return true;
6322 
6323   // Truncate to the given size.
6324   Result = Result.getLoBits(ArgBits);
6325   Result.setIsUnsigned(true);
6326 
6327   // Check to see if it's in either of the required forms.
6328   if (IsShiftedByte(Result) ||
6329       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6330     return false;
6331 
6332   return Diag(TheCall->getBeginLoc(),
6333               diag::err_argument_not_shifted_byte_or_xxff)
6334          << Arg->getSourceRange();
6335 }
6336 
6337 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6338 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6339   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6340     if (checkArgCount(*this, TheCall, 2))
6341       return true;
6342     Expr *Arg0 = TheCall->getArg(0);
6343     Expr *Arg1 = TheCall->getArg(1);
6344 
6345     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6346     if (FirstArg.isInvalid())
6347       return true;
6348     QualType FirstArgType = FirstArg.get()->getType();
6349     if (!FirstArgType->isAnyPointerType())
6350       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6351                << "first" << FirstArgType << Arg0->getSourceRange();
6352     TheCall->setArg(0, FirstArg.get());
6353 
6354     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6355     if (SecArg.isInvalid())
6356       return true;
6357     QualType SecArgType = SecArg.get()->getType();
6358     if (!SecArgType->isIntegerType())
6359       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6360                << "second" << SecArgType << Arg1->getSourceRange();
6361 
6362     // Derive the return type from the pointer argument.
6363     TheCall->setType(FirstArgType);
6364     return false;
6365   }
6366 
6367   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6368     if (checkArgCount(*this, TheCall, 2))
6369       return true;
6370 
6371     Expr *Arg0 = TheCall->getArg(0);
6372     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6373     if (FirstArg.isInvalid())
6374       return true;
6375     QualType FirstArgType = FirstArg.get()->getType();
6376     if (!FirstArgType->isAnyPointerType())
6377       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6378                << "first" << FirstArgType << Arg0->getSourceRange();
6379     TheCall->setArg(0, FirstArg.get());
6380 
6381     // Derive the return type from the pointer argument.
6382     TheCall->setType(FirstArgType);
6383 
6384     // Second arg must be an constant in range [0,15]
6385     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6386   }
6387 
6388   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6389     if (checkArgCount(*this, TheCall, 2))
6390       return true;
6391     Expr *Arg0 = TheCall->getArg(0);
6392     Expr *Arg1 = TheCall->getArg(1);
6393 
6394     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6395     if (FirstArg.isInvalid())
6396       return true;
6397     QualType FirstArgType = FirstArg.get()->getType();
6398     if (!FirstArgType->isAnyPointerType())
6399       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6400                << "first" << FirstArgType << Arg0->getSourceRange();
6401 
6402     QualType SecArgType = Arg1->getType();
6403     if (!SecArgType->isIntegerType())
6404       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6405                << "second" << SecArgType << Arg1->getSourceRange();
6406     TheCall->setType(Context.IntTy);
6407     return false;
6408   }
6409 
6410   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6411       BuiltinID == AArch64::BI__builtin_arm_stg) {
6412     if (checkArgCount(*this, TheCall, 1))
6413       return true;
6414     Expr *Arg0 = TheCall->getArg(0);
6415     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6416     if (FirstArg.isInvalid())
6417       return true;
6418 
6419     QualType FirstArgType = FirstArg.get()->getType();
6420     if (!FirstArgType->isAnyPointerType())
6421       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6422                << "first" << FirstArgType << Arg0->getSourceRange();
6423     TheCall->setArg(0, FirstArg.get());
6424 
6425     // Derive the return type from the pointer argument.
6426     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6427       TheCall->setType(FirstArgType);
6428     return false;
6429   }
6430 
6431   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6432     Expr *ArgA = TheCall->getArg(0);
6433     Expr *ArgB = TheCall->getArg(1);
6434 
6435     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6436     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6437 
6438     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6439       return true;
6440 
6441     QualType ArgTypeA = ArgExprA.get()->getType();
6442     QualType ArgTypeB = ArgExprB.get()->getType();
6443 
6444     auto isNull = [&] (Expr *E) -> bool {
6445       return E->isNullPointerConstant(
6446                         Context, Expr::NPC_ValueDependentIsNotNull); };
6447 
6448     // argument should be either a pointer or null
6449     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6450       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6451         << "first" << ArgTypeA << ArgA->getSourceRange();
6452 
6453     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6454       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6455         << "second" << ArgTypeB << ArgB->getSourceRange();
6456 
6457     // Ensure Pointee types are compatible
6458     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6459         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6460       QualType pointeeA = ArgTypeA->getPointeeType();
6461       QualType pointeeB = ArgTypeB->getPointeeType();
6462       if (!Context.typesAreCompatible(
6463              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6464              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6465         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6466           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6467           << ArgB->getSourceRange();
6468       }
6469     }
6470 
6471     // at least one argument should be pointer type
6472     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6473       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6474         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6475 
6476     if (isNull(ArgA)) // adopt type of the other pointer
6477       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6478 
6479     if (isNull(ArgB))
6480       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6481 
6482     TheCall->setArg(0, ArgExprA.get());
6483     TheCall->setArg(1, ArgExprB.get());
6484     TheCall->setType(Context.LongLongTy);
6485     return false;
6486   }
6487   assert(false && "Unhandled ARM MTE intrinsic");
6488   return true;
6489 }
6490 
6491 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6492 /// TheCall is an ARM/AArch64 special register string literal.
6493 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6494                                     int ArgNum, unsigned ExpectedFieldNum,
6495                                     bool AllowName) {
6496   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6497                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6498                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6499                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6500                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6501                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6502   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6503                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6504                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6505                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6506                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6507                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6508   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6509 
6510   // We can't check the value of a dependent argument.
6511   Expr *Arg = TheCall->getArg(ArgNum);
6512   if (Arg->isTypeDependent() || Arg->isValueDependent())
6513     return false;
6514 
6515   // Check if the argument is a string literal.
6516   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6517     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6518            << Arg->getSourceRange();
6519 
6520   // Check the type of special register given.
6521   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6522   SmallVector<StringRef, 6> Fields;
6523   Reg.split(Fields, ":");
6524 
6525   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6526     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6527            << Arg->getSourceRange();
6528 
6529   // If the string is the name of a register then we cannot check that it is
6530   // valid here but if the string is of one the forms described in ACLE then we
6531   // can check that the supplied fields are integers and within the valid
6532   // ranges.
6533   if (Fields.size() > 1) {
6534     bool FiveFields = Fields.size() == 5;
6535 
6536     bool ValidString = true;
6537     if (IsARMBuiltin) {
6538       ValidString &= Fields[0].startswith_lower("cp") ||
6539                      Fields[0].startswith_lower("p");
6540       if (ValidString)
6541         Fields[0] =
6542           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6543 
6544       ValidString &= Fields[2].startswith_lower("c");
6545       if (ValidString)
6546         Fields[2] = Fields[2].drop_front(1);
6547 
6548       if (FiveFields) {
6549         ValidString &= Fields[3].startswith_lower("c");
6550         if (ValidString)
6551           Fields[3] = Fields[3].drop_front(1);
6552       }
6553     }
6554 
6555     SmallVector<int, 5> Ranges;
6556     if (FiveFields)
6557       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6558     else
6559       Ranges.append({15, 7, 15});
6560 
6561     for (unsigned i=0; i<Fields.size(); ++i) {
6562       int IntField;
6563       ValidString &= !Fields[i].getAsInteger(10, IntField);
6564       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6565     }
6566 
6567     if (!ValidString)
6568       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6569              << Arg->getSourceRange();
6570   } else if (IsAArch64Builtin && Fields.size() == 1) {
6571     // If the register name is one of those that appear in the condition below
6572     // and the special register builtin being used is one of the write builtins,
6573     // then we require that the argument provided for writing to the register
6574     // is an integer constant expression. This is because it will be lowered to
6575     // an MSR (immediate) instruction, so we need to know the immediate at
6576     // compile time.
6577     if (TheCall->getNumArgs() != 2)
6578       return false;
6579 
6580     std::string RegLower = Reg.lower();
6581     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6582         RegLower != "pan" && RegLower != "uao")
6583       return false;
6584 
6585     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6586   }
6587 
6588   return false;
6589 }
6590 
6591 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6592 /// This checks that the target supports __builtin_longjmp and
6593 /// that val is a constant 1.
6594 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6595   if (!Context.getTargetInfo().hasSjLjLowering())
6596     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6597            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6598 
6599   Expr *Arg = TheCall->getArg(1);
6600   llvm::APSInt Result;
6601 
6602   // TODO: This is less than ideal. Overload this to take a value.
6603   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6604     return true;
6605 
6606   if (Result != 1)
6607     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6608            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6609 
6610   return false;
6611 }
6612 
6613 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6614 /// This checks that the target supports __builtin_setjmp.
6615 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6616   if (!Context.getTargetInfo().hasSjLjLowering())
6617     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6618            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6619   return false;
6620 }
6621 
6622 namespace {
6623 
6624 class UncoveredArgHandler {
6625   enum { Unknown = -1, AllCovered = -2 };
6626 
6627   signed FirstUncoveredArg = Unknown;
6628   SmallVector<const Expr *, 4> DiagnosticExprs;
6629 
6630 public:
6631   UncoveredArgHandler() = default;
6632 
6633   bool hasUncoveredArg() const {
6634     return (FirstUncoveredArg >= 0);
6635   }
6636 
6637   unsigned getUncoveredArg() const {
6638     assert(hasUncoveredArg() && "no uncovered argument");
6639     return FirstUncoveredArg;
6640   }
6641 
6642   void setAllCovered() {
6643     // A string has been found with all arguments covered, so clear out
6644     // the diagnostics.
6645     DiagnosticExprs.clear();
6646     FirstUncoveredArg = AllCovered;
6647   }
6648 
6649   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6650     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6651 
6652     // Don't update if a previous string covers all arguments.
6653     if (FirstUncoveredArg == AllCovered)
6654       return;
6655 
6656     // UncoveredArgHandler tracks the highest uncovered argument index
6657     // and with it all the strings that match this index.
6658     if (NewFirstUncoveredArg == FirstUncoveredArg)
6659       DiagnosticExprs.push_back(StrExpr);
6660     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6661       DiagnosticExprs.clear();
6662       DiagnosticExprs.push_back(StrExpr);
6663       FirstUncoveredArg = NewFirstUncoveredArg;
6664     }
6665   }
6666 
6667   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6668 };
6669 
6670 enum StringLiteralCheckType {
6671   SLCT_NotALiteral,
6672   SLCT_UncheckedLiteral,
6673   SLCT_CheckedLiteral
6674 };
6675 
6676 } // namespace
6677 
6678 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6679                                      BinaryOperatorKind BinOpKind,
6680                                      bool AddendIsRight) {
6681   unsigned BitWidth = Offset.getBitWidth();
6682   unsigned AddendBitWidth = Addend.getBitWidth();
6683   // There might be negative interim results.
6684   if (Addend.isUnsigned()) {
6685     Addend = Addend.zext(++AddendBitWidth);
6686     Addend.setIsSigned(true);
6687   }
6688   // Adjust the bit width of the APSInts.
6689   if (AddendBitWidth > BitWidth) {
6690     Offset = Offset.sext(AddendBitWidth);
6691     BitWidth = AddendBitWidth;
6692   } else if (BitWidth > AddendBitWidth) {
6693     Addend = Addend.sext(BitWidth);
6694   }
6695 
6696   bool Ov = false;
6697   llvm::APSInt ResOffset = Offset;
6698   if (BinOpKind == BO_Add)
6699     ResOffset = Offset.sadd_ov(Addend, Ov);
6700   else {
6701     assert(AddendIsRight && BinOpKind == BO_Sub &&
6702            "operator must be add or sub with addend on the right");
6703     ResOffset = Offset.ssub_ov(Addend, Ov);
6704   }
6705 
6706   // We add an offset to a pointer here so we should support an offset as big as
6707   // possible.
6708   if (Ov) {
6709     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6710            "index (intermediate) result too big");
6711     Offset = Offset.sext(2 * BitWidth);
6712     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6713     return;
6714   }
6715 
6716   Offset = ResOffset;
6717 }
6718 
6719 namespace {
6720 
6721 // This is a wrapper class around StringLiteral to support offsetted string
6722 // literals as format strings. It takes the offset into account when returning
6723 // the string and its length or the source locations to display notes correctly.
6724 class FormatStringLiteral {
6725   const StringLiteral *FExpr;
6726   int64_t Offset;
6727 
6728  public:
6729   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6730       : FExpr(fexpr), Offset(Offset) {}
6731 
6732   StringRef getString() const {
6733     return FExpr->getString().drop_front(Offset);
6734   }
6735 
6736   unsigned getByteLength() const {
6737     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6738   }
6739 
6740   unsigned getLength() const { return FExpr->getLength() - Offset; }
6741   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6742 
6743   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6744 
6745   QualType getType() const { return FExpr->getType(); }
6746 
6747   bool isAscii() const { return FExpr->isAscii(); }
6748   bool isWide() const { return FExpr->isWide(); }
6749   bool isUTF8() const { return FExpr->isUTF8(); }
6750   bool isUTF16() const { return FExpr->isUTF16(); }
6751   bool isUTF32() const { return FExpr->isUTF32(); }
6752   bool isPascal() const { return FExpr->isPascal(); }
6753 
6754   SourceLocation getLocationOfByte(
6755       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6756       const TargetInfo &Target, unsigned *StartToken = nullptr,
6757       unsigned *StartTokenByteOffset = nullptr) const {
6758     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6759                                     StartToken, StartTokenByteOffset);
6760   }
6761 
6762   SourceLocation getBeginLoc() const LLVM_READONLY {
6763     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6764   }
6765 
6766   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6767 };
6768 
6769 }  // namespace
6770 
6771 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6772                               const Expr *OrigFormatExpr,
6773                               ArrayRef<const Expr *> Args,
6774                               bool HasVAListArg, unsigned format_idx,
6775                               unsigned firstDataArg,
6776                               Sema::FormatStringType Type,
6777                               bool inFunctionCall,
6778                               Sema::VariadicCallType CallType,
6779                               llvm::SmallBitVector &CheckedVarArgs,
6780                               UncoveredArgHandler &UncoveredArg,
6781                               bool IgnoreStringsWithoutSpecifiers);
6782 
6783 // Determine if an expression is a string literal or constant string.
6784 // If this function returns false on the arguments to a function expecting a
6785 // format string, we will usually need to emit a warning.
6786 // True string literals are then checked by CheckFormatString.
6787 static StringLiteralCheckType
6788 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6789                       bool HasVAListArg, unsigned format_idx,
6790                       unsigned firstDataArg, Sema::FormatStringType Type,
6791                       Sema::VariadicCallType CallType, bool InFunctionCall,
6792                       llvm::SmallBitVector &CheckedVarArgs,
6793                       UncoveredArgHandler &UncoveredArg,
6794                       llvm::APSInt Offset,
6795                       bool IgnoreStringsWithoutSpecifiers = false) {
6796   if (S.isConstantEvaluated())
6797     return SLCT_NotALiteral;
6798  tryAgain:
6799   assert(Offset.isSigned() && "invalid offset");
6800 
6801   if (E->isTypeDependent() || E->isValueDependent())
6802     return SLCT_NotALiteral;
6803 
6804   E = E->IgnoreParenCasts();
6805 
6806   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6807     // Technically -Wformat-nonliteral does not warn about this case.
6808     // The behavior of printf and friends in this case is implementation
6809     // dependent.  Ideally if the format string cannot be null then
6810     // it should have a 'nonnull' attribute in the function prototype.
6811     return SLCT_UncheckedLiteral;
6812 
6813   switch (E->getStmtClass()) {
6814   case Stmt::BinaryConditionalOperatorClass:
6815   case Stmt::ConditionalOperatorClass: {
6816     // The expression is a literal if both sub-expressions were, and it was
6817     // completely checked only if both sub-expressions were checked.
6818     const AbstractConditionalOperator *C =
6819         cast<AbstractConditionalOperator>(E);
6820 
6821     // Determine whether it is necessary to check both sub-expressions, for
6822     // example, because the condition expression is a constant that can be
6823     // evaluated at compile time.
6824     bool CheckLeft = true, CheckRight = true;
6825 
6826     bool Cond;
6827     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6828                                                  S.isConstantEvaluated())) {
6829       if (Cond)
6830         CheckRight = false;
6831       else
6832         CheckLeft = false;
6833     }
6834 
6835     // We need to maintain the offsets for the right and the left hand side
6836     // separately to check if every possible indexed expression is a valid
6837     // string literal. They might have different offsets for different string
6838     // literals in the end.
6839     StringLiteralCheckType Left;
6840     if (!CheckLeft)
6841       Left = SLCT_UncheckedLiteral;
6842     else {
6843       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6844                                    HasVAListArg, format_idx, firstDataArg,
6845                                    Type, CallType, InFunctionCall,
6846                                    CheckedVarArgs, UncoveredArg, Offset,
6847                                    IgnoreStringsWithoutSpecifiers);
6848       if (Left == SLCT_NotALiteral || !CheckRight) {
6849         return Left;
6850       }
6851     }
6852 
6853     StringLiteralCheckType Right = checkFormatStringExpr(
6854         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6855         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6856         IgnoreStringsWithoutSpecifiers);
6857 
6858     return (CheckLeft && Left < Right) ? Left : Right;
6859   }
6860 
6861   case Stmt::ImplicitCastExprClass:
6862     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6863     goto tryAgain;
6864 
6865   case Stmt::OpaqueValueExprClass:
6866     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6867       E = src;
6868       goto tryAgain;
6869     }
6870     return SLCT_NotALiteral;
6871 
6872   case Stmt::PredefinedExprClass:
6873     // While __func__, etc., are technically not string literals, they
6874     // cannot contain format specifiers and thus are not a security
6875     // liability.
6876     return SLCT_UncheckedLiteral;
6877 
6878   case Stmt::DeclRefExprClass: {
6879     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6880 
6881     // As an exception, do not flag errors for variables binding to
6882     // const string literals.
6883     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6884       bool isConstant = false;
6885       QualType T = DR->getType();
6886 
6887       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6888         isConstant = AT->getElementType().isConstant(S.Context);
6889       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6890         isConstant = T.isConstant(S.Context) &&
6891                      PT->getPointeeType().isConstant(S.Context);
6892       } else if (T->isObjCObjectPointerType()) {
6893         // In ObjC, there is usually no "const ObjectPointer" type,
6894         // so don't check if the pointee type is constant.
6895         isConstant = T.isConstant(S.Context);
6896       }
6897 
6898       if (isConstant) {
6899         if (const Expr *Init = VD->getAnyInitializer()) {
6900           // Look through initializers like const char c[] = { "foo" }
6901           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6902             if (InitList->isStringLiteralInit())
6903               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6904           }
6905           return checkFormatStringExpr(S, Init, Args,
6906                                        HasVAListArg, format_idx,
6907                                        firstDataArg, Type, CallType,
6908                                        /*InFunctionCall*/ false, CheckedVarArgs,
6909                                        UncoveredArg, Offset);
6910         }
6911       }
6912 
6913       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6914       // special check to see if the format string is a function parameter
6915       // of the function calling the printf function.  If the function
6916       // has an attribute indicating it is a printf-like function, then we
6917       // should suppress warnings concerning non-literals being used in a call
6918       // to a vprintf function.  For example:
6919       //
6920       // void
6921       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6922       //      va_list ap;
6923       //      va_start(ap, fmt);
6924       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6925       //      ...
6926       // }
6927       if (HasVAListArg) {
6928         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6929           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6930             int PVIndex = PV->getFunctionScopeIndex() + 1;
6931             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6932               // adjust for implicit parameter
6933               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6934                 if (MD->isInstance())
6935                   ++PVIndex;
6936               // We also check if the formats are compatible.
6937               // We can't pass a 'scanf' string to a 'printf' function.
6938               if (PVIndex == PVFormat->getFormatIdx() &&
6939                   Type == S.GetFormatStringType(PVFormat))
6940                 return SLCT_UncheckedLiteral;
6941             }
6942           }
6943         }
6944       }
6945     }
6946 
6947     return SLCT_NotALiteral;
6948   }
6949 
6950   case Stmt::CallExprClass:
6951   case Stmt::CXXMemberCallExprClass: {
6952     const CallExpr *CE = cast<CallExpr>(E);
6953     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6954       bool IsFirst = true;
6955       StringLiteralCheckType CommonResult;
6956       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6957         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6958         StringLiteralCheckType Result = checkFormatStringExpr(
6959             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6960             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6961             IgnoreStringsWithoutSpecifiers);
6962         if (IsFirst) {
6963           CommonResult = Result;
6964           IsFirst = false;
6965         }
6966       }
6967       if (!IsFirst)
6968         return CommonResult;
6969 
6970       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6971         unsigned BuiltinID = FD->getBuiltinID();
6972         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6973             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6974           const Expr *Arg = CE->getArg(0);
6975           return checkFormatStringExpr(S, Arg, Args,
6976                                        HasVAListArg, format_idx,
6977                                        firstDataArg, Type, CallType,
6978                                        InFunctionCall, CheckedVarArgs,
6979                                        UncoveredArg, Offset,
6980                                        IgnoreStringsWithoutSpecifiers);
6981         }
6982       }
6983     }
6984 
6985     return SLCT_NotALiteral;
6986   }
6987   case Stmt::ObjCMessageExprClass: {
6988     const auto *ME = cast<ObjCMessageExpr>(E);
6989     if (const auto *MD = ME->getMethodDecl()) {
6990       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6991         // As a special case heuristic, if we're using the method -[NSBundle
6992         // localizedStringForKey:value:table:], ignore any key strings that lack
6993         // format specifiers. The idea is that if the key doesn't have any
6994         // format specifiers then its probably just a key to map to the
6995         // localized strings. If it does have format specifiers though, then its
6996         // likely that the text of the key is the format string in the
6997         // programmer's language, and should be checked.
6998         const ObjCInterfaceDecl *IFace;
6999         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7000             IFace->getIdentifier()->isStr("NSBundle") &&
7001             MD->getSelector().isKeywordSelector(
7002                 {"localizedStringForKey", "value", "table"})) {
7003           IgnoreStringsWithoutSpecifiers = true;
7004         }
7005 
7006         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7007         return checkFormatStringExpr(
7008             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7009             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7010             IgnoreStringsWithoutSpecifiers);
7011       }
7012     }
7013 
7014     return SLCT_NotALiteral;
7015   }
7016   case Stmt::ObjCStringLiteralClass:
7017   case Stmt::StringLiteralClass: {
7018     const StringLiteral *StrE = nullptr;
7019 
7020     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7021       StrE = ObjCFExpr->getString();
7022     else
7023       StrE = cast<StringLiteral>(E);
7024 
7025     if (StrE) {
7026       if (Offset.isNegative() || Offset > StrE->getLength()) {
7027         // TODO: It would be better to have an explicit warning for out of
7028         // bounds literals.
7029         return SLCT_NotALiteral;
7030       }
7031       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7032       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7033                         firstDataArg, Type, InFunctionCall, CallType,
7034                         CheckedVarArgs, UncoveredArg,
7035                         IgnoreStringsWithoutSpecifiers);
7036       return SLCT_CheckedLiteral;
7037     }
7038 
7039     return SLCT_NotALiteral;
7040   }
7041   case Stmt::BinaryOperatorClass: {
7042     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7043 
7044     // A string literal + an int offset is still a string literal.
7045     if (BinOp->isAdditiveOp()) {
7046       Expr::EvalResult LResult, RResult;
7047 
7048       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7049           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7050       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7051           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7052 
7053       if (LIsInt != RIsInt) {
7054         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7055 
7056         if (LIsInt) {
7057           if (BinOpKind == BO_Add) {
7058             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7059             E = BinOp->getRHS();
7060             goto tryAgain;
7061           }
7062         } else {
7063           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7064           E = BinOp->getLHS();
7065           goto tryAgain;
7066         }
7067       }
7068     }
7069 
7070     return SLCT_NotALiteral;
7071   }
7072   case Stmt::UnaryOperatorClass: {
7073     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7074     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7075     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7076       Expr::EvalResult IndexResult;
7077       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7078                                        Expr::SE_NoSideEffects,
7079                                        S.isConstantEvaluated())) {
7080         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7081                    /*RHS is int*/ true);
7082         E = ASE->getBase();
7083         goto tryAgain;
7084       }
7085     }
7086 
7087     return SLCT_NotALiteral;
7088   }
7089 
7090   default:
7091     return SLCT_NotALiteral;
7092   }
7093 }
7094 
7095 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7096   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7097       .Case("scanf", FST_Scanf)
7098       .Cases("printf", "printf0", "syslog", FST_Printf)
7099       .Cases("NSString", "CFString", FST_NSString)
7100       .Case("strftime", FST_Strftime)
7101       .Case("strfmon", FST_Strfmon)
7102       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7103       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7104       .Case("os_trace", FST_OSLog)
7105       .Case("os_log", FST_OSLog)
7106       .Default(FST_Unknown);
7107 }
7108 
7109 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7110 /// functions) for correct use of format strings.
7111 /// Returns true if a format string has been fully checked.
7112 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7113                                 ArrayRef<const Expr *> Args,
7114                                 bool IsCXXMember,
7115                                 VariadicCallType CallType,
7116                                 SourceLocation Loc, SourceRange Range,
7117                                 llvm::SmallBitVector &CheckedVarArgs) {
7118   FormatStringInfo FSI;
7119   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7120     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7121                                 FSI.FirstDataArg, GetFormatStringType(Format),
7122                                 CallType, Loc, Range, CheckedVarArgs);
7123   return false;
7124 }
7125 
7126 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7127                                 bool HasVAListArg, unsigned format_idx,
7128                                 unsigned firstDataArg, FormatStringType Type,
7129                                 VariadicCallType CallType,
7130                                 SourceLocation Loc, SourceRange Range,
7131                                 llvm::SmallBitVector &CheckedVarArgs) {
7132   // CHECK: printf/scanf-like function is called with no format string.
7133   if (format_idx >= Args.size()) {
7134     Diag(Loc, diag::warn_missing_format_string) << Range;
7135     return false;
7136   }
7137 
7138   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7139 
7140   // CHECK: format string is not a string literal.
7141   //
7142   // Dynamically generated format strings are difficult to
7143   // automatically vet at compile time.  Requiring that format strings
7144   // are string literals: (1) permits the checking of format strings by
7145   // the compiler and thereby (2) can practically remove the source of
7146   // many format string exploits.
7147 
7148   // Format string can be either ObjC string (e.g. @"%d") or
7149   // C string (e.g. "%d")
7150   // ObjC string uses the same format specifiers as C string, so we can use
7151   // the same format string checking logic for both ObjC and C strings.
7152   UncoveredArgHandler UncoveredArg;
7153   StringLiteralCheckType CT =
7154       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7155                             format_idx, firstDataArg, Type, CallType,
7156                             /*IsFunctionCall*/ true, CheckedVarArgs,
7157                             UncoveredArg,
7158                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7159 
7160   // Generate a diagnostic where an uncovered argument is detected.
7161   if (UncoveredArg.hasUncoveredArg()) {
7162     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7163     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7164     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7165   }
7166 
7167   if (CT != SLCT_NotALiteral)
7168     // Literal format string found, check done!
7169     return CT == SLCT_CheckedLiteral;
7170 
7171   // Strftime is particular as it always uses a single 'time' argument,
7172   // so it is safe to pass a non-literal string.
7173   if (Type == FST_Strftime)
7174     return false;
7175 
7176   // Do not emit diag when the string param is a macro expansion and the
7177   // format is either NSString or CFString. This is a hack to prevent
7178   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7179   // which are usually used in place of NS and CF string literals.
7180   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7181   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7182     return false;
7183 
7184   // If there are no arguments specified, warn with -Wformat-security, otherwise
7185   // warn only with -Wformat-nonliteral.
7186   if (Args.size() == firstDataArg) {
7187     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7188       << OrigFormatExpr->getSourceRange();
7189     switch (Type) {
7190     default:
7191       break;
7192     case FST_Kprintf:
7193     case FST_FreeBSDKPrintf:
7194     case FST_Printf:
7195     case FST_Syslog:
7196       Diag(FormatLoc, diag::note_format_security_fixit)
7197         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7198       break;
7199     case FST_NSString:
7200       Diag(FormatLoc, diag::note_format_security_fixit)
7201         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7202       break;
7203     }
7204   } else {
7205     Diag(FormatLoc, diag::warn_format_nonliteral)
7206       << OrigFormatExpr->getSourceRange();
7207   }
7208   return false;
7209 }
7210 
7211 namespace {
7212 
7213 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7214 protected:
7215   Sema &S;
7216   const FormatStringLiteral *FExpr;
7217   const Expr *OrigFormatExpr;
7218   const Sema::FormatStringType FSType;
7219   const unsigned FirstDataArg;
7220   const unsigned NumDataArgs;
7221   const char *Beg; // Start of format string.
7222   const bool HasVAListArg;
7223   ArrayRef<const Expr *> Args;
7224   unsigned FormatIdx;
7225   llvm::SmallBitVector CoveredArgs;
7226   bool usesPositionalArgs = false;
7227   bool atFirstArg = true;
7228   bool inFunctionCall;
7229   Sema::VariadicCallType CallType;
7230   llvm::SmallBitVector &CheckedVarArgs;
7231   UncoveredArgHandler &UncoveredArg;
7232 
7233 public:
7234   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7235                      const Expr *origFormatExpr,
7236                      const Sema::FormatStringType type, unsigned firstDataArg,
7237                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7238                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7239                      bool inFunctionCall, Sema::VariadicCallType callType,
7240                      llvm::SmallBitVector &CheckedVarArgs,
7241                      UncoveredArgHandler &UncoveredArg)
7242       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7243         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7244         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7245         inFunctionCall(inFunctionCall), CallType(callType),
7246         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7247     CoveredArgs.resize(numDataArgs);
7248     CoveredArgs.reset();
7249   }
7250 
7251   void DoneProcessing();
7252 
7253   void HandleIncompleteSpecifier(const char *startSpecifier,
7254                                  unsigned specifierLen) override;
7255 
7256   void HandleInvalidLengthModifier(
7257                            const analyze_format_string::FormatSpecifier &FS,
7258                            const analyze_format_string::ConversionSpecifier &CS,
7259                            const char *startSpecifier, unsigned specifierLen,
7260                            unsigned DiagID);
7261 
7262   void HandleNonStandardLengthModifier(
7263                     const analyze_format_string::FormatSpecifier &FS,
7264                     const char *startSpecifier, unsigned specifierLen);
7265 
7266   void HandleNonStandardConversionSpecifier(
7267                     const analyze_format_string::ConversionSpecifier &CS,
7268                     const char *startSpecifier, unsigned specifierLen);
7269 
7270   void HandlePosition(const char *startPos, unsigned posLen) override;
7271 
7272   void HandleInvalidPosition(const char *startSpecifier,
7273                              unsigned specifierLen,
7274                              analyze_format_string::PositionContext p) override;
7275 
7276   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7277 
7278   void HandleNullChar(const char *nullCharacter) override;
7279 
7280   template <typename Range>
7281   static void
7282   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7283                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7284                        bool IsStringLocation, Range StringRange,
7285                        ArrayRef<FixItHint> Fixit = None);
7286 
7287 protected:
7288   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7289                                         const char *startSpec,
7290                                         unsigned specifierLen,
7291                                         const char *csStart, unsigned csLen);
7292 
7293   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7294                                          const char *startSpec,
7295                                          unsigned specifierLen);
7296 
7297   SourceRange getFormatStringRange();
7298   CharSourceRange getSpecifierRange(const char *startSpecifier,
7299                                     unsigned specifierLen);
7300   SourceLocation getLocationOfByte(const char *x);
7301 
7302   const Expr *getDataArg(unsigned i) const;
7303 
7304   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7305                     const analyze_format_string::ConversionSpecifier &CS,
7306                     const char *startSpecifier, unsigned specifierLen,
7307                     unsigned argIndex);
7308 
7309   template <typename Range>
7310   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7311                             bool IsStringLocation, Range StringRange,
7312                             ArrayRef<FixItHint> Fixit = None);
7313 };
7314 
7315 } // namespace
7316 
7317 SourceRange CheckFormatHandler::getFormatStringRange() {
7318   return OrigFormatExpr->getSourceRange();
7319 }
7320 
7321 CharSourceRange CheckFormatHandler::
7322 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7323   SourceLocation Start = getLocationOfByte(startSpecifier);
7324   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7325 
7326   // Advance the end SourceLocation by one due to half-open ranges.
7327   End = End.getLocWithOffset(1);
7328 
7329   return CharSourceRange::getCharRange(Start, End);
7330 }
7331 
7332 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7333   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7334                                   S.getLangOpts(), S.Context.getTargetInfo());
7335 }
7336 
7337 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7338                                                    unsigned specifierLen){
7339   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7340                        getLocationOfByte(startSpecifier),
7341                        /*IsStringLocation*/true,
7342                        getSpecifierRange(startSpecifier, specifierLen));
7343 }
7344 
7345 void CheckFormatHandler::HandleInvalidLengthModifier(
7346     const analyze_format_string::FormatSpecifier &FS,
7347     const analyze_format_string::ConversionSpecifier &CS,
7348     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7349   using namespace analyze_format_string;
7350 
7351   const LengthModifier &LM = FS.getLengthModifier();
7352   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7353 
7354   // See if we know how to fix this length modifier.
7355   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7356   if (FixedLM) {
7357     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7358                          getLocationOfByte(LM.getStart()),
7359                          /*IsStringLocation*/true,
7360                          getSpecifierRange(startSpecifier, specifierLen));
7361 
7362     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7363       << FixedLM->toString()
7364       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7365 
7366   } else {
7367     FixItHint Hint;
7368     if (DiagID == diag::warn_format_nonsensical_length)
7369       Hint = FixItHint::CreateRemoval(LMRange);
7370 
7371     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7372                          getLocationOfByte(LM.getStart()),
7373                          /*IsStringLocation*/true,
7374                          getSpecifierRange(startSpecifier, specifierLen),
7375                          Hint);
7376   }
7377 }
7378 
7379 void CheckFormatHandler::HandleNonStandardLengthModifier(
7380     const analyze_format_string::FormatSpecifier &FS,
7381     const char *startSpecifier, unsigned specifierLen) {
7382   using namespace analyze_format_string;
7383 
7384   const LengthModifier &LM = FS.getLengthModifier();
7385   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7386 
7387   // See if we know how to fix this length modifier.
7388   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7389   if (FixedLM) {
7390     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7391                            << LM.toString() << 0,
7392                          getLocationOfByte(LM.getStart()),
7393                          /*IsStringLocation*/true,
7394                          getSpecifierRange(startSpecifier, specifierLen));
7395 
7396     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7397       << FixedLM->toString()
7398       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7399 
7400   } else {
7401     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7402                            << LM.toString() << 0,
7403                          getLocationOfByte(LM.getStart()),
7404                          /*IsStringLocation*/true,
7405                          getSpecifierRange(startSpecifier, specifierLen));
7406   }
7407 }
7408 
7409 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7410     const analyze_format_string::ConversionSpecifier &CS,
7411     const char *startSpecifier, unsigned specifierLen) {
7412   using namespace analyze_format_string;
7413 
7414   // See if we know how to fix this conversion specifier.
7415   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7416   if (FixedCS) {
7417     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7418                           << CS.toString() << /*conversion specifier*/1,
7419                          getLocationOfByte(CS.getStart()),
7420                          /*IsStringLocation*/true,
7421                          getSpecifierRange(startSpecifier, specifierLen));
7422 
7423     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7424     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7425       << FixedCS->toString()
7426       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7427   } else {
7428     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7429                           << CS.toString() << /*conversion specifier*/1,
7430                          getLocationOfByte(CS.getStart()),
7431                          /*IsStringLocation*/true,
7432                          getSpecifierRange(startSpecifier, specifierLen));
7433   }
7434 }
7435 
7436 void CheckFormatHandler::HandlePosition(const char *startPos,
7437                                         unsigned posLen) {
7438   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7439                                getLocationOfByte(startPos),
7440                                /*IsStringLocation*/true,
7441                                getSpecifierRange(startPos, posLen));
7442 }
7443 
7444 void
7445 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7446                                      analyze_format_string::PositionContext p) {
7447   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7448                          << (unsigned) p,
7449                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7450                        getSpecifierRange(startPos, posLen));
7451 }
7452 
7453 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7454                                             unsigned posLen) {
7455   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7456                                getLocationOfByte(startPos),
7457                                /*IsStringLocation*/true,
7458                                getSpecifierRange(startPos, posLen));
7459 }
7460 
7461 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7462   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7463     // The presence of a null character is likely an error.
7464     EmitFormatDiagnostic(
7465       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7466       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7467       getFormatStringRange());
7468   }
7469 }
7470 
7471 // Note that this may return NULL if there was an error parsing or building
7472 // one of the argument expressions.
7473 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7474   return Args[FirstDataArg + i];
7475 }
7476 
7477 void CheckFormatHandler::DoneProcessing() {
7478   // Does the number of data arguments exceed the number of
7479   // format conversions in the format string?
7480   if (!HasVAListArg) {
7481       // Find any arguments that weren't covered.
7482     CoveredArgs.flip();
7483     signed notCoveredArg = CoveredArgs.find_first();
7484     if (notCoveredArg >= 0) {
7485       assert((unsigned)notCoveredArg < NumDataArgs);
7486       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7487     } else {
7488       UncoveredArg.setAllCovered();
7489     }
7490   }
7491 }
7492 
7493 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7494                                    const Expr *ArgExpr) {
7495   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7496          "Invalid state");
7497 
7498   if (!ArgExpr)
7499     return;
7500 
7501   SourceLocation Loc = ArgExpr->getBeginLoc();
7502 
7503   if (S.getSourceManager().isInSystemMacro(Loc))
7504     return;
7505 
7506   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7507   for (auto E : DiagnosticExprs)
7508     PDiag << E->getSourceRange();
7509 
7510   CheckFormatHandler::EmitFormatDiagnostic(
7511                                   S, IsFunctionCall, DiagnosticExprs[0],
7512                                   PDiag, Loc, /*IsStringLocation*/false,
7513                                   DiagnosticExprs[0]->getSourceRange());
7514 }
7515 
7516 bool
7517 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7518                                                      SourceLocation Loc,
7519                                                      const char *startSpec,
7520                                                      unsigned specifierLen,
7521                                                      const char *csStart,
7522                                                      unsigned csLen) {
7523   bool keepGoing = true;
7524   if (argIndex < NumDataArgs) {
7525     // Consider the argument coverered, even though the specifier doesn't
7526     // make sense.
7527     CoveredArgs.set(argIndex);
7528   }
7529   else {
7530     // If argIndex exceeds the number of data arguments we
7531     // don't issue a warning because that is just a cascade of warnings (and
7532     // they may have intended '%%' anyway). We don't want to continue processing
7533     // the format string after this point, however, as we will like just get
7534     // gibberish when trying to match arguments.
7535     keepGoing = false;
7536   }
7537 
7538   StringRef Specifier(csStart, csLen);
7539 
7540   // If the specifier in non-printable, it could be the first byte of a UTF-8
7541   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7542   // hex value.
7543   std::string CodePointStr;
7544   if (!llvm::sys::locale::isPrint(*csStart)) {
7545     llvm::UTF32 CodePoint;
7546     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7547     const llvm::UTF8 *E =
7548         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7549     llvm::ConversionResult Result =
7550         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7551 
7552     if (Result != llvm::conversionOK) {
7553       unsigned char FirstChar = *csStart;
7554       CodePoint = (llvm::UTF32)FirstChar;
7555     }
7556 
7557     llvm::raw_string_ostream OS(CodePointStr);
7558     if (CodePoint < 256)
7559       OS << "\\x" << llvm::format("%02x", CodePoint);
7560     else if (CodePoint <= 0xFFFF)
7561       OS << "\\u" << llvm::format("%04x", CodePoint);
7562     else
7563       OS << "\\U" << llvm::format("%08x", CodePoint);
7564     OS.flush();
7565     Specifier = CodePointStr;
7566   }
7567 
7568   EmitFormatDiagnostic(
7569       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7570       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7571 
7572   return keepGoing;
7573 }
7574 
7575 void
7576 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7577                                                       const char *startSpec,
7578                                                       unsigned specifierLen) {
7579   EmitFormatDiagnostic(
7580     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7581     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7582 }
7583 
7584 bool
7585 CheckFormatHandler::CheckNumArgs(
7586   const analyze_format_string::FormatSpecifier &FS,
7587   const analyze_format_string::ConversionSpecifier &CS,
7588   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7589 
7590   if (argIndex >= NumDataArgs) {
7591     PartialDiagnostic PDiag = FS.usesPositionalArg()
7592       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7593            << (argIndex+1) << NumDataArgs)
7594       : S.PDiag(diag::warn_printf_insufficient_data_args);
7595     EmitFormatDiagnostic(
7596       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7597       getSpecifierRange(startSpecifier, specifierLen));
7598 
7599     // Since more arguments than conversion tokens are given, by extension
7600     // all arguments are covered, so mark this as so.
7601     UncoveredArg.setAllCovered();
7602     return false;
7603   }
7604   return true;
7605 }
7606 
7607 template<typename Range>
7608 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7609                                               SourceLocation Loc,
7610                                               bool IsStringLocation,
7611                                               Range StringRange,
7612                                               ArrayRef<FixItHint> FixIt) {
7613   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7614                        Loc, IsStringLocation, StringRange, FixIt);
7615 }
7616 
7617 /// If the format string is not within the function call, emit a note
7618 /// so that the function call and string are in diagnostic messages.
7619 ///
7620 /// \param InFunctionCall if true, the format string is within the function
7621 /// call and only one diagnostic message will be produced.  Otherwise, an
7622 /// extra note will be emitted pointing to location of the format string.
7623 ///
7624 /// \param ArgumentExpr the expression that is passed as the format string
7625 /// argument in the function call.  Used for getting locations when two
7626 /// diagnostics are emitted.
7627 ///
7628 /// \param PDiag the callee should already have provided any strings for the
7629 /// diagnostic message.  This function only adds locations and fixits
7630 /// to diagnostics.
7631 ///
7632 /// \param Loc primary location for diagnostic.  If two diagnostics are
7633 /// required, one will be at Loc and a new SourceLocation will be created for
7634 /// the other one.
7635 ///
7636 /// \param IsStringLocation if true, Loc points to the format string should be
7637 /// used for the note.  Otherwise, Loc points to the argument list and will
7638 /// be used with PDiag.
7639 ///
7640 /// \param StringRange some or all of the string to highlight.  This is
7641 /// templated so it can accept either a CharSourceRange or a SourceRange.
7642 ///
7643 /// \param FixIt optional fix it hint for the format string.
7644 template <typename Range>
7645 void CheckFormatHandler::EmitFormatDiagnostic(
7646     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7647     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7648     Range StringRange, ArrayRef<FixItHint> FixIt) {
7649   if (InFunctionCall) {
7650     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7651     D << StringRange;
7652     D << FixIt;
7653   } else {
7654     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7655       << ArgumentExpr->getSourceRange();
7656 
7657     const Sema::SemaDiagnosticBuilder &Note =
7658       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7659              diag::note_format_string_defined);
7660 
7661     Note << StringRange;
7662     Note << FixIt;
7663   }
7664 }
7665 
7666 //===--- CHECK: Printf format string checking ------------------------------===//
7667 
7668 namespace {
7669 
7670 class CheckPrintfHandler : public CheckFormatHandler {
7671 public:
7672   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7673                      const Expr *origFormatExpr,
7674                      const Sema::FormatStringType type, unsigned firstDataArg,
7675                      unsigned numDataArgs, bool isObjC, const char *beg,
7676                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7677                      unsigned formatIdx, bool inFunctionCall,
7678                      Sema::VariadicCallType CallType,
7679                      llvm::SmallBitVector &CheckedVarArgs,
7680                      UncoveredArgHandler &UncoveredArg)
7681       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7682                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7683                            inFunctionCall, CallType, CheckedVarArgs,
7684                            UncoveredArg) {}
7685 
7686   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7687 
7688   /// Returns true if '%@' specifiers are allowed in the format string.
7689   bool allowsObjCArg() const {
7690     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7691            FSType == Sema::FST_OSTrace;
7692   }
7693 
7694   bool HandleInvalidPrintfConversionSpecifier(
7695                                       const analyze_printf::PrintfSpecifier &FS,
7696                                       const char *startSpecifier,
7697                                       unsigned specifierLen) override;
7698 
7699   void handleInvalidMaskType(StringRef MaskType) override;
7700 
7701   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7702                              const char *startSpecifier,
7703                              unsigned specifierLen) override;
7704   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7705                        const char *StartSpecifier,
7706                        unsigned SpecifierLen,
7707                        const Expr *E);
7708 
7709   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7710                     const char *startSpecifier, unsigned specifierLen);
7711   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7712                            const analyze_printf::OptionalAmount &Amt,
7713                            unsigned type,
7714                            const char *startSpecifier, unsigned specifierLen);
7715   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7716                   const analyze_printf::OptionalFlag &flag,
7717                   const char *startSpecifier, unsigned specifierLen);
7718   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7719                          const analyze_printf::OptionalFlag &ignoredFlag,
7720                          const analyze_printf::OptionalFlag &flag,
7721                          const char *startSpecifier, unsigned specifierLen);
7722   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7723                            const Expr *E);
7724 
7725   void HandleEmptyObjCModifierFlag(const char *startFlag,
7726                                    unsigned flagLen) override;
7727 
7728   void HandleInvalidObjCModifierFlag(const char *startFlag,
7729                                             unsigned flagLen) override;
7730 
7731   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7732                                            const char *flagsEnd,
7733                                            const char *conversionPosition)
7734                                              override;
7735 };
7736 
7737 } // namespace
7738 
7739 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7740                                       const analyze_printf::PrintfSpecifier &FS,
7741                                       const char *startSpecifier,
7742                                       unsigned specifierLen) {
7743   const analyze_printf::PrintfConversionSpecifier &CS =
7744     FS.getConversionSpecifier();
7745 
7746   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7747                                           getLocationOfByte(CS.getStart()),
7748                                           startSpecifier, specifierLen,
7749                                           CS.getStart(), CS.getLength());
7750 }
7751 
7752 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7753   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7754 }
7755 
7756 bool CheckPrintfHandler::HandleAmount(
7757                                const analyze_format_string::OptionalAmount &Amt,
7758                                unsigned k, const char *startSpecifier,
7759                                unsigned specifierLen) {
7760   if (Amt.hasDataArgument()) {
7761     if (!HasVAListArg) {
7762       unsigned argIndex = Amt.getArgIndex();
7763       if (argIndex >= NumDataArgs) {
7764         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7765                                << k,
7766                              getLocationOfByte(Amt.getStart()),
7767                              /*IsStringLocation*/true,
7768                              getSpecifierRange(startSpecifier, specifierLen));
7769         // Don't do any more checking.  We will just emit
7770         // spurious errors.
7771         return false;
7772       }
7773 
7774       // Type check the data argument.  It should be an 'int'.
7775       // Although not in conformance with C99, we also allow the argument to be
7776       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7777       // doesn't emit a warning for that case.
7778       CoveredArgs.set(argIndex);
7779       const Expr *Arg = getDataArg(argIndex);
7780       if (!Arg)
7781         return false;
7782 
7783       QualType T = Arg->getType();
7784 
7785       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7786       assert(AT.isValid());
7787 
7788       if (!AT.matchesType(S.Context, T)) {
7789         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7790                                << k << AT.getRepresentativeTypeName(S.Context)
7791                                << T << Arg->getSourceRange(),
7792                              getLocationOfByte(Amt.getStart()),
7793                              /*IsStringLocation*/true,
7794                              getSpecifierRange(startSpecifier, specifierLen));
7795         // Don't do any more checking.  We will just emit
7796         // spurious errors.
7797         return false;
7798       }
7799     }
7800   }
7801   return true;
7802 }
7803 
7804 void CheckPrintfHandler::HandleInvalidAmount(
7805                                       const analyze_printf::PrintfSpecifier &FS,
7806                                       const analyze_printf::OptionalAmount &Amt,
7807                                       unsigned type,
7808                                       const char *startSpecifier,
7809                                       unsigned specifierLen) {
7810   const analyze_printf::PrintfConversionSpecifier &CS =
7811     FS.getConversionSpecifier();
7812 
7813   FixItHint fixit =
7814     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7815       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7816                                  Amt.getConstantLength()))
7817       : FixItHint();
7818 
7819   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7820                          << type << CS.toString(),
7821                        getLocationOfByte(Amt.getStart()),
7822                        /*IsStringLocation*/true,
7823                        getSpecifierRange(startSpecifier, specifierLen),
7824                        fixit);
7825 }
7826 
7827 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7828                                     const analyze_printf::OptionalFlag &flag,
7829                                     const char *startSpecifier,
7830                                     unsigned specifierLen) {
7831   // Warn about pointless flag with a fixit removal.
7832   const analyze_printf::PrintfConversionSpecifier &CS =
7833     FS.getConversionSpecifier();
7834   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7835                          << flag.toString() << CS.toString(),
7836                        getLocationOfByte(flag.getPosition()),
7837                        /*IsStringLocation*/true,
7838                        getSpecifierRange(startSpecifier, specifierLen),
7839                        FixItHint::CreateRemoval(
7840                          getSpecifierRange(flag.getPosition(), 1)));
7841 }
7842 
7843 void CheckPrintfHandler::HandleIgnoredFlag(
7844                                 const analyze_printf::PrintfSpecifier &FS,
7845                                 const analyze_printf::OptionalFlag &ignoredFlag,
7846                                 const analyze_printf::OptionalFlag &flag,
7847                                 const char *startSpecifier,
7848                                 unsigned specifierLen) {
7849   // Warn about ignored flag with a fixit removal.
7850   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7851                          << ignoredFlag.toString() << flag.toString(),
7852                        getLocationOfByte(ignoredFlag.getPosition()),
7853                        /*IsStringLocation*/true,
7854                        getSpecifierRange(startSpecifier, specifierLen),
7855                        FixItHint::CreateRemoval(
7856                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7857 }
7858 
7859 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7860                                                      unsigned flagLen) {
7861   // Warn about an empty flag.
7862   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7863                        getLocationOfByte(startFlag),
7864                        /*IsStringLocation*/true,
7865                        getSpecifierRange(startFlag, flagLen));
7866 }
7867 
7868 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7869                                                        unsigned flagLen) {
7870   // Warn about an invalid flag.
7871   auto Range = getSpecifierRange(startFlag, flagLen);
7872   StringRef flag(startFlag, flagLen);
7873   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7874                       getLocationOfByte(startFlag),
7875                       /*IsStringLocation*/true,
7876                       Range, FixItHint::CreateRemoval(Range));
7877 }
7878 
7879 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7880     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7881     // Warn about using '[...]' without a '@' conversion.
7882     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7883     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7884     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7885                          getLocationOfByte(conversionPosition),
7886                          /*IsStringLocation*/true,
7887                          Range, FixItHint::CreateRemoval(Range));
7888 }
7889 
7890 // Determines if the specified is a C++ class or struct containing
7891 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7892 // "c_str()").
7893 template<typename MemberKind>
7894 static llvm::SmallPtrSet<MemberKind*, 1>
7895 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7896   const RecordType *RT = Ty->getAs<RecordType>();
7897   llvm::SmallPtrSet<MemberKind*, 1> Results;
7898 
7899   if (!RT)
7900     return Results;
7901   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7902   if (!RD || !RD->getDefinition())
7903     return Results;
7904 
7905   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7906                  Sema::LookupMemberName);
7907   R.suppressDiagnostics();
7908 
7909   // We just need to include all members of the right kind turned up by the
7910   // filter, at this point.
7911   if (S.LookupQualifiedName(R, RT->getDecl()))
7912     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7913       NamedDecl *decl = (*I)->getUnderlyingDecl();
7914       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7915         Results.insert(FK);
7916     }
7917   return Results;
7918 }
7919 
7920 /// Check if we could call '.c_str()' on an object.
7921 ///
7922 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7923 /// allow the call, or if it would be ambiguous).
7924 bool Sema::hasCStrMethod(const Expr *E) {
7925   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7926 
7927   MethodSet Results =
7928       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7929   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7930        MI != ME; ++MI)
7931     if ((*MI)->getMinRequiredArguments() == 0)
7932       return true;
7933   return false;
7934 }
7935 
7936 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7937 // better diagnostic if so. AT is assumed to be valid.
7938 // Returns true when a c_str() conversion method is found.
7939 bool CheckPrintfHandler::checkForCStrMembers(
7940     const analyze_printf::ArgType &AT, const Expr *E) {
7941   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7942 
7943   MethodSet Results =
7944       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7945 
7946   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7947        MI != ME; ++MI) {
7948     const CXXMethodDecl *Method = *MI;
7949     if (Method->getMinRequiredArguments() == 0 &&
7950         AT.matchesType(S.Context, Method->getReturnType())) {
7951       // FIXME: Suggest parens if the expression needs them.
7952       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7953       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7954           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7955       return true;
7956     }
7957   }
7958 
7959   return false;
7960 }
7961 
7962 bool
7963 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7964                                             &FS,
7965                                           const char *startSpecifier,
7966                                           unsigned specifierLen) {
7967   using namespace analyze_format_string;
7968   using namespace analyze_printf;
7969 
7970   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7971 
7972   if (FS.consumesDataArgument()) {
7973     if (atFirstArg) {
7974         atFirstArg = false;
7975         usesPositionalArgs = FS.usesPositionalArg();
7976     }
7977     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7978       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7979                                         startSpecifier, specifierLen);
7980       return false;
7981     }
7982   }
7983 
7984   // First check if the field width, precision, and conversion specifier
7985   // have matching data arguments.
7986   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7987                     startSpecifier, specifierLen)) {
7988     return false;
7989   }
7990 
7991   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7992                     startSpecifier, specifierLen)) {
7993     return false;
7994   }
7995 
7996   if (!CS.consumesDataArgument()) {
7997     // FIXME: Technically specifying a precision or field width here
7998     // makes no sense.  Worth issuing a warning at some point.
7999     return true;
8000   }
8001 
8002   // Consume the argument.
8003   unsigned argIndex = FS.getArgIndex();
8004   if (argIndex < NumDataArgs) {
8005     // The check to see if the argIndex is valid will come later.
8006     // We set the bit here because we may exit early from this
8007     // function if we encounter some other error.
8008     CoveredArgs.set(argIndex);
8009   }
8010 
8011   // FreeBSD kernel extensions.
8012   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8013       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8014     // We need at least two arguments.
8015     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8016       return false;
8017 
8018     // Claim the second argument.
8019     CoveredArgs.set(argIndex + 1);
8020 
8021     const Expr *Ex = getDataArg(argIndex);
8022     if (CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8023       // Type check the first argument (pointer for %D)
8024       const analyze_printf::ArgType &AT = ArgType::CPointerTy;
8025       if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8026         EmitFormatDiagnostic(
8027           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8028           << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8029           << false << Ex->getSourceRange(),
8030           Ex->getBeginLoc(), /*IsStringLocation*/false,
8031           getSpecifierRange(startSpecifier, specifierLen));
8032     } else {
8033       // Check the length modifier for %b
8034       if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8035                                      S.getLangOpts()))
8036         HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8037                                     diag::warn_format_nonsensical_length);
8038       else if (!FS.hasStandardLengthModifier())
8039         HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8040       else if (!FS.hasStandardLengthConversionCombination())
8041         HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8042                                     diag::warn_format_non_standard_conversion_spec);
8043 
8044       // Type check the first argument of %b
8045       if (!checkFormatExpr(FS, startSpecifier, specifierLen, Ex))
8046         return false;
8047     }
8048 
8049     // Type check the second argument (char * for both %b and %D)
8050     Ex = getDataArg(argIndex + 1);
8051     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8052     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8053       EmitFormatDiagnostic(
8054           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8055               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8056               << false << Ex->getSourceRange(),
8057           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8058           getSpecifierRange(startSpecifier, specifierLen));
8059 
8060      return true;
8061   }
8062 
8063   // Check for using an Objective-C specific conversion specifier
8064   // in a non-ObjC literal.
8065   if (!allowsObjCArg() && CS.isObjCArg()) {
8066     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8067                                                   specifierLen);
8068   }
8069 
8070   // %P can only be used with os_log.
8071   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8072     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8073                                                   specifierLen);
8074   }
8075 
8076   // %n is not allowed with os_log.
8077   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8078     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8079                          getLocationOfByte(CS.getStart()),
8080                          /*IsStringLocation*/ false,
8081                          getSpecifierRange(startSpecifier, specifierLen));
8082 
8083     return true;
8084   }
8085 
8086   // Only scalars are allowed for os_trace.
8087   if (FSType == Sema::FST_OSTrace &&
8088       (CS.getKind() == ConversionSpecifier::PArg ||
8089        CS.getKind() == ConversionSpecifier::sArg ||
8090        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8091     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8092                                                   specifierLen);
8093   }
8094 
8095   // Check for use of public/private annotation outside of os_log().
8096   if (FSType != Sema::FST_OSLog) {
8097     if (FS.isPublic().isSet()) {
8098       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8099                                << "public",
8100                            getLocationOfByte(FS.isPublic().getPosition()),
8101                            /*IsStringLocation*/ false,
8102                            getSpecifierRange(startSpecifier, specifierLen));
8103     }
8104     if (FS.isPrivate().isSet()) {
8105       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8106                                << "private",
8107                            getLocationOfByte(FS.isPrivate().getPosition()),
8108                            /*IsStringLocation*/ false,
8109                            getSpecifierRange(startSpecifier, specifierLen));
8110     }
8111   }
8112 
8113   // Check for invalid use of field width
8114   if (!FS.hasValidFieldWidth()) {
8115     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8116         startSpecifier, specifierLen);
8117   }
8118 
8119   // Check for invalid use of precision
8120   if (!FS.hasValidPrecision()) {
8121     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8122         startSpecifier, specifierLen);
8123   }
8124 
8125   // Precision is mandatory for %P specifier.
8126   if (CS.getKind() == ConversionSpecifier::PArg &&
8127       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8128     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8129                          getLocationOfByte(startSpecifier),
8130                          /*IsStringLocation*/ false,
8131                          getSpecifierRange(startSpecifier, specifierLen));
8132   }
8133 
8134   // Check each flag does not conflict with any other component.
8135   if (!FS.hasValidThousandsGroupingPrefix())
8136     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8137   if (!FS.hasValidLeadingZeros())
8138     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8139   if (!FS.hasValidPlusPrefix())
8140     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8141   if (!FS.hasValidSpacePrefix())
8142     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8143   if (!FS.hasValidAlternativeForm())
8144     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8145   if (!FS.hasValidLeftJustified())
8146     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8147 
8148   // Check that flags are not ignored by another flag
8149   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8150     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8151         startSpecifier, specifierLen);
8152   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8153     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8154             startSpecifier, specifierLen);
8155 
8156   // Check the length modifier is valid with the given conversion specifier.
8157   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8158                                  S.getLangOpts()))
8159     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8160                                 diag::warn_format_nonsensical_length);
8161   else if (!FS.hasStandardLengthModifier())
8162     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8163   else if (!FS.hasStandardLengthConversionCombination())
8164     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8165                                 diag::warn_format_non_standard_conversion_spec);
8166 
8167   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8168     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8169 
8170   // The remaining checks depend on the data arguments.
8171   if (HasVAListArg)
8172     return true;
8173 
8174   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8175     return false;
8176 
8177   const Expr *Arg = getDataArg(argIndex);
8178   if (!Arg)
8179     return true;
8180 
8181   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8182 }
8183 
8184 static bool requiresParensToAddCast(const Expr *E) {
8185   // FIXME: We should have a general way to reason about operator
8186   // precedence and whether parens are actually needed here.
8187   // Take care of a few common cases where they aren't.
8188   const Expr *Inside = E->IgnoreImpCasts();
8189   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8190     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8191 
8192   switch (Inside->getStmtClass()) {
8193   case Stmt::ArraySubscriptExprClass:
8194   case Stmt::CallExprClass:
8195   case Stmt::CharacterLiteralClass:
8196   case Stmt::CXXBoolLiteralExprClass:
8197   case Stmt::DeclRefExprClass:
8198   case Stmt::FloatingLiteralClass:
8199   case Stmt::IntegerLiteralClass:
8200   case Stmt::MemberExprClass:
8201   case Stmt::ObjCArrayLiteralClass:
8202   case Stmt::ObjCBoolLiteralExprClass:
8203   case Stmt::ObjCBoxedExprClass:
8204   case Stmt::ObjCDictionaryLiteralClass:
8205   case Stmt::ObjCEncodeExprClass:
8206   case Stmt::ObjCIvarRefExprClass:
8207   case Stmt::ObjCMessageExprClass:
8208   case Stmt::ObjCPropertyRefExprClass:
8209   case Stmt::ObjCStringLiteralClass:
8210   case Stmt::ObjCSubscriptRefExprClass:
8211   case Stmt::ParenExprClass:
8212   case Stmt::StringLiteralClass:
8213   case Stmt::UnaryOperatorClass:
8214     return false;
8215   default:
8216     return true;
8217   }
8218 }
8219 
8220 static std::pair<QualType, StringRef>
8221 shouldNotPrintDirectly(const ASTContext &Context,
8222                        QualType IntendedTy,
8223                        const Expr *E) {
8224   // Use a 'while' to peel off layers of typedefs.
8225   QualType TyTy = IntendedTy;
8226   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8227     StringRef Name = UserTy->getDecl()->getName();
8228     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8229       .Case("CFIndex", Context.getNSIntegerType())
8230       .Case("NSInteger", Context.getNSIntegerType())
8231       .Case("NSUInteger", Context.getNSUIntegerType())
8232       .Case("SInt32", Context.IntTy)
8233       .Case("UInt32", Context.UnsignedIntTy)
8234       .Default(QualType());
8235 
8236     if (!CastTy.isNull())
8237       return std::make_pair(CastTy, Name);
8238 
8239     TyTy = UserTy->desugar();
8240   }
8241 
8242   // Strip parens if necessary.
8243   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8244     return shouldNotPrintDirectly(Context,
8245                                   PE->getSubExpr()->getType(),
8246                                   PE->getSubExpr());
8247 
8248   // If this is a conditional expression, then its result type is constructed
8249   // via usual arithmetic conversions and thus there might be no necessary
8250   // typedef sugar there.  Recurse to operands to check for NSInteger &
8251   // Co. usage condition.
8252   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8253     QualType TrueTy, FalseTy;
8254     StringRef TrueName, FalseName;
8255 
8256     std::tie(TrueTy, TrueName) =
8257       shouldNotPrintDirectly(Context,
8258                              CO->getTrueExpr()->getType(),
8259                              CO->getTrueExpr());
8260     std::tie(FalseTy, FalseName) =
8261       shouldNotPrintDirectly(Context,
8262                              CO->getFalseExpr()->getType(),
8263                              CO->getFalseExpr());
8264 
8265     if (TrueTy == FalseTy)
8266       return std::make_pair(TrueTy, TrueName);
8267     else if (TrueTy.isNull())
8268       return std::make_pair(FalseTy, FalseName);
8269     else if (FalseTy.isNull())
8270       return std::make_pair(TrueTy, TrueName);
8271   }
8272 
8273   return std::make_pair(QualType(), StringRef());
8274 }
8275 
8276 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8277 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8278 /// type do not count.
8279 static bool
8280 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8281   QualType From = ICE->getSubExpr()->getType();
8282   QualType To = ICE->getType();
8283   // It's an integer promotion if the destination type is the promoted
8284   // source type.
8285   if (ICE->getCastKind() == CK_IntegralCast &&
8286       From->isPromotableIntegerType() &&
8287       S.Context.getPromotedIntegerType(From) == To)
8288     return true;
8289   // Look through vector types, since we do default argument promotion for
8290   // those in OpenCL.
8291   if (const auto *VecTy = From->getAs<ExtVectorType>())
8292     From = VecTy->getElementType();
8293   if (const auto *VecTy = To->getAs<ExtVectorType>())
8294     To = VecTy->getElementType();
8295   // It's a floating promotion if the source type is a lower rank.
8296   return ICE->getCastKind() == CK_FloatingCast &&
8297          S.Context.getFloatingTypeOrder(From, To) < 0;
8298 }
8299 
8300 bool
8301 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8302                                     const char *StartSpecifier,
8303                                     unsigned SpecifierLen,
8304                                     const Expr *E) {
8305   using namespace analyze_format_string;
8306   using namespace analyze_printf;
8307 
8308   // Now type check the data expression that matches the
8309   // format specifier.
8310   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8311   if (!AT.isValid())
8312     return true;
8313 
8314   QualType ExprTy = E->getType();
8315   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8316     ExprTy = TET->getUnderlyingExpr()->getType();
8317   }
8318 
8319   // Diagnose attempts to print a boolean value as a character. Unlike other
8320   // -Wformat diagnostics, this is fine from a type perspective, but it still
8321   // doesn't make sense.
8322   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8323       E->isKnownToHaveBooleanValue()) {
8324     const CharSourceRange &CSR =
8325         getSpecifierRange(StartSpecifier, SpecifierLen);
8326     SmallString<4> FSString;
8327     llvm::raw_svector_ostream os(FSString);
8328     FS.toString(os);
8329     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8330                              << FSString,
8331                          E->getExprLoc(), false, CSR);
8332     return true;
8333   }
8334 
8335   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8336   if (Match == analyze_printf::ArgType::Match)
8337     return true;
8338 
8339   // Look through argument promotions for our error message's reported type.
8340   // This includes the integral and floating promotions, but excludes array
8341   // and function pointer decay (seeing that an argument intended to be a
8342   // string has type 'char [6]' is probably more confusing than 'char *') and
8343   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8344   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8345     if (isArithmeticArgumentPromotion(S, ICE)) {
8346       E = ICE->getSubExpr();
8347       ExprTy = E->getType();
8348 
8349       // Check if we didn't match because of an implicit cast from a 'char'
8350       // or 'short' to an 'int'.  This is done because printf is a varargs
8351       // function.
8352       if (ICE->getType() == S.Context.IntTy ||
8353           ICE->getType() == S.Context.UnsignedIntTy) {
8354         // All further checking is done on the subexpression
8355         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8356             AT.matchesType(S.Context, ExprTy);
8357         if (ImplicitMatch == analyze_printf::ArgType::Match)
8358           return true;
8359         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8360             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8361           Match = ImplicitMatch;
8362       }
8363     }
8364   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8365     // Special case for 'a', which has type 'int' in C.
8366     // Note, however, that we do /not/ want to treat multibyte constants like
8367     // 'MooV' as characters! This form is deprecated but still exists.
8368     if (ExprTy == S.Context.IntTy)
8369       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8370         ExprTy = S.Context.CharTy;
8371   }
8372 
8373   // Look through enums to their underlying type.
8374   bool IsEnum = false;
8375   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8376     ExprTy = EnumTy->getDecl()->getIntegerType();
8377     IsEnum = true;
8378   }
8379 
8380   // %C in an Objective-C context prints a unichar, not a wchar_t.
8381   // If the argument is an integer of some kind, believe the %C and suggest
8382   // a cast instead of changing the conversion specifier.
8383   QualType IntendedTy = ExprTy;
8384   if (isObjCContext() &&
8385       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8386     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8387         !ExprTy->isCharType()) {
8388       // 'unichar' is defined as a typedef of unsigned short, but we should
8389       // prefer using the typedef if it is visible.
8390       IntendedTy = S.Context.UnsignedShortTy;
8391 
8392       // While we are here, check if the value is an IntegerLiteral that happens
8393       // to be within the valid range.
8394       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8395         const llvm::APInt &V = IL->getValue();
8396         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8397           return true;
8398       }
8399 
8400       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8401                           Sema::LookupOrdinaryName);
8402       if (S.LookupName(Result, S.getCurScope())) {
8403         NamedDecl *ND = Result.getFoundDecl();
8404         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8405           if (TD->getUnderlyingType() == IntendedTy)
8406             IntendedTy = S.Context.getTypedefType(TD);
8407       }
8408     }
8409   }
8410 
8411   // Special-case some of Darwin's platform-independence types by suggesting
8412   // casts to primitive types that are known to be large enough.
8413   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8414   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8415     QualType CastTy;
8416     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8417     if (!CastTy.isNull()) {
8418       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8419       // (long in ASTContext). Only complain to pedants.
8420       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8421           (AT.isSizeT() || AT.isPtrdiffT()) &&
8422           AT.matchesType(S.Context, CastTy))
8423         Match = ArgType::NoMatchPedantic;
8424       IntendedTy = CastTy;
8425       ShouldNotPrintDirectly = true;
8426     }
8427   }
8428 
8429   // We may be able to offer a FixItHint if it is a supported type.
8430   PrintfSpecifier fixedFS = FS;
8431   bool Success =
8432       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8433 
8434   if (Success) {
8435     // Get the fix string from the fixed format specifier
8436     SmallString<16> buf;
8437     llvm::raw_svector_ostream os(buf);
8438     fixedFS.toString(os);
8439 
8440     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8441 
8442     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8443       unsigned Diag;
8444       switch (Match) {
8445       case ArgType::Match: llvm_unreachable("expected non-matching");
8446       case ArgType::NoMatchPedantic:
8447         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8448         break;
8449       case ArgType::NoMatchTypeConfusion:
8450         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8451         break;
8452       case ArgType::NoMatch:
8453         Diag = diag::warn_format_conversion_argument_type_mismatch;
8454         break;
8455       }
8456 
8457       // In this case, the specifier is wrong and should be changed to match
8458       // the argument.
8459       EmitFormatDiagnostic(S.PDiag(Diag)
8460                                << AT.getRepresentativeTypeName(S.Context)
8461                                << IntendedTy << IsEnum << E->getSourceRange(),
8462                            E->getBeginLoc(),
8463                            /*IsStringLocation*/ false, SpecRange,
8464                            FixItHint::CreateReplacement(SpecRange, os.str()));
8465     } else {
8466       // The canonical type for formatting this value is different from the
8467       // actual type of the expression. (This occurs, for example, with Darwin's
8468       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8469       // should be printed as 'long' for 64-bit compatibility.)
8470       // Rather than emitting a normal format/argument mismatch, we want to
8471       // add a cast to the recommended type (and correct the format string
8472       // if necessary).
8473       SmallString<16> CastBuf;
8474       llvm::raw_svector_ostream CastFix(CastBuf);
8475       CastFix << "(";
8476       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8477       CastFix << ")";
8478 
8479       SmallVector<FixItHint,4> Hints;
8480       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8481         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8482 
8483       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8484         // If there's already a cast present, just replace it.
8485         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8486         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8487 
8488       } else if (!requiresParensToAddCast(E)) {
8489         // If the expression has high enough precedence,
8490         // just write the C-style cast.
8491         Hints.push_back(
8492             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8493       } else {
8494         // Otherwise, add parens around the expression as well as the cast.
8495         CastFix << "(";
8496         Hints.push_back(
8497             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8498 
8499         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8500         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8501       }
8502 
8503       if (ShouldNotPrintDirectly) {
8504         // The expression has a type that should not be printed directly.
8505         // We extract the name from the typedef because we don't want to show
8506         // the underlying type in the diagnostic.
8507         StringRef Name;
8508         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8509           Name = TypedefTy->getDecl()->getName();
8510         else
8511           Name = CastTyName;
8512         unsigned Diag = Match == ArgType::NoMatchPedantic
8513                             ? diag::warn_format_argument_needs_cast_pedantic
8514                             : diag::warn_format_argument_needs_cast;
8515         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8516                                            << E->getSourceRange(),
8517                              E->getBeginLoc(), /*IsStringLocation=*/false,
8518                              SpecRange, Hints);
8519       } else {
8520         // In this case, the expression could be printed using a different
8521         // specifier, but we've decided that the specifier is probably correct
8522         // and we should cast instead. Just use the normal warning message.
8523         EmitFormatDiagnostic(
8524             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8525                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8526                 << E->getSourceRange(),
8527             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8528       }
8529     }
8530   } else {
8531     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8532                                                    SpecifierLen);
8533     // Since the warning for passing non-POD types to variadic functions
8534     // was deferred until now, we emit a warning for non-POD
8535     // arguments here.
8536     switch (S.isValidVarArgType(ExprTy)) {
8537     case Sema::VAK_Valid:
8538     case Sema::VAK_ValidInCXX11: {
8539       unsigned Diag;
8540       switch (Match) {
8541       case ArgType::Match: llvm_unreachable("expected non-matching");
8542       case ArgType::NoMatchPedantic:
8543         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8544         break;
8545       case ArgType::NoMatchTypeConfusion:
8546         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8547         break;
8548       case ArgType::NoMatch:
8549         Diag = diag::warn_format_conversion_argument_type_mismatch;
8550         break;
8551       }
8552 
8553       EmitFormatDiagnostic(
8554           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8555                         << IsEnum << CSR << E->getSourceRange(),
8556           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8557       break;
8558     }
8559     case Sema::VAK_Undefined:
8560     case Sema::VAK_MSVCUndefined:
8561       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8562                                << S.getLangOpts().CPlusPlus11 << ExprTy
8563                                << CallType
8564                                << AT.getRepresentativeTypeName(S.Context) << CSR
8565                                << E->getSourceRange(),
8566                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8567       checkForCStrMembers(AT, E);
8568       break;
8569 
8570     case Sema::VAK_Invalid:
8571       if (ExprTy->isObjCObjectType())
8572         EmitFormatDiagnostic(
8573             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8574                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8575                 << AT.getRepresentativeTypeName(S.Context) << CSR
8576                 << E->getSourceRange(),
8577             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8578       else
8579         // FIXME: If this is an initializer list, suggest removing the braces
8580         // or inserting a cast to the target type.
8581         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8582             << isa<InitListExpr>(E) << ExprTy << CallType
8583             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8584       break;
8585     }
8586 
8587     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8588            "format string specifier index out of range");
8589     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8590   }
8591 
8592   return true;
8593 }
8594 
8595 //===--- CHECK: Scanf format string checking ------------------------------===//
8596 
8597 namespace {
8598 
8599 class CheckScanfHandler : public CheckFormatHandler {
8600 public:
8601   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8602                     const Expr *origFormatExpr, Sema::FormatStringType type,
8603                     unsigned firstDataArg, unsigned numDataArgs,
8604                     const char *beg, bool hasVAListArg,
8605                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8606                     bool inFunctionCall, Sema::VariadicCallType CallType,
8607                     llvm::SmallBitVector &CheckedVarArgs,
8608                     UncoveredArgHandler &UncoveredArg)
8609       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8610                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8611                            inFunctionCall, CallType, CheckedVarArgs,
8612                            UncoveredArg) {}
8613 
8614   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8615                             const char *startSpecifier,
8616                             unsigned specifierLen) override;
8617 
8618   bool HandleInvalidScanfConversionSpecifier(
8619           const analyze_scanf::ScanfSpecifier &FS,
8620           const char *startSpecifier,
8621           unsigned specifierLen) override;
8622 
8623   void HandleIncompleteScanList(const char *start, const char *end) override;
8624 };
8625 
8626 } // namespace
8627 
8628 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8629                                                  const char *end) {
8630   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8631                        getLocationOfByte(end), /*IsStringLocation*/true,
8632                        getSpecifierRange(start, end - start));
8633 }
8634 
8635 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8636                                         const analyze_scanf::ScanfSpecifier &FS,
8637                                         const char *startSpecifier,
8638                                         unsigned specifierLen) {
8639   const analyze_scanf::ScanfConversionSpecifier &CS =
8640     FS.getConversionSpecifier();
8641 
8642   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8643                                           getLocationOfByte(CS.getStart()),
8644                                           startSpecifier, specifierLen,
8645                                           CS.getStart(), CS.getLength());
8646 }
8647 
8648 bool CheckScanfHandler::HandleScanfSpecifier(
8649                                        const analyze_scanf::ScanfSpecifier &FS,
8650                                        const char *startSpecifier,
8651                                        unsigned specifierLen) {
8652   using namespace analyze_scanf;
8653   using namespace analyze_format_string;
8654 
8655   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8656 
8657   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8658   // be used to decide if we are using positional arguments consistently.
8659   if (FS.consumesDataArgument()) {
8660     if (atFirstArg) {
8661       atFirstArg = false;
8662       usesPositionalArgs = FS.usesPositionalArg();
8663     }
8664     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8665       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8666                                         startSpecifier, specifierLen);
8667       return false;
8668     }
8669   }
8670 
8671   // Check if the field with is non-zero.
8672   const OptionalAmount &Amt = FS.getFieldWidth();
8673   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8674     if (Amt.getConstantAmount() == 0) {
8675       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8676                                                    Amt.getConstantLength());
8677       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8678                            getLocationOfByte(Amt.getStart()),
8679                            /*IsStringLocation*/true, R,
8680                            FixItHint::CreateRemoval(R));
8681     }
8682   }
8683 
8684   if (!FS.consumesDataArgument()) {
8685     // FIXME: Technically specifying a precision or field width here
8686     // makes no sense.  Worth issuing a warning at some point.
8687     return true;
8688   }
8689 
8690   // Consume the argument.
8691   unsigned argIndex = FS.getArgIndex();
8692   if (argIndex < NumDataArgs) {
8693       // The check to see if the argIndex is valid will come later.
8694       // We set the bit here because we may exit early from this
8695       // function if we encounter some other error.
8696     CoveredArgs.set(argIndex);
8697   }
8698 
8699   // Check the length modifier is valid with the given conversion specifier.
8700   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8701                                  S.getLangOpts()))
8702     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8703                                 diag::warn_format_nonsensical_length);
8704   else if (!FS.hasStandardLengthModifier())
8705     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8706   else if (!FS.hasStandardLengthConversionCombination())
8707     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8708                                 diag::warn_format_non_standard_conversion_spec);
8709 
8710   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8711     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8712 
8713   // The remaining checks depend on the data arguments.
8714   if (HasVAListArg)
8715     return true;
8716 
8717   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8718     return false;
8719 
8720   // Check that the argument type matches the format specifier.
8721   const Expr *Ex = getDataArg(argIndex);
8722   if (!Ex)
8723     return true;
8724 
8725   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8726 
8727   if (!AT.isValid()) {
8728     return true;
8729   }
8730 
8731   analyze_format_string::ArgType::MatchKind Match =
8732       AT.matchesType(S.Context, Ex->getType());
8733   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8734   if (Match == analyze_format_string::ArgType::Match)
8735     return true;
8736 
8737   ScanfSpecifier fixedFS = FS;
8738   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8739                                  S.getLangOpts(), S.Context);
8740 
8741   unsigned Diag =
8742       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8743                : diag::warn_format_conversion_argument_type_mismatch;
8744 
8745   if (Success) {
8746     // Get the fix string from the fixed format specifier.
8747     SmallString<128> buf;
8748     llvm::raw_svector_ostream os(buf);
8749     fixedFS.toString(os);
8750 
8751     EmitFormatDiagnostic(
8752         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8753                       << Ex->getType() << false << Ex->getSourceRange(),
8754         Ex->getBeginLoc(),
8755         /*IsStringLocation*/ false,
8756         getSpecifierRange(startSpecifier, specifierLen),
8757         FixItHint::CreateReplacement(
8758             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8759   } else {
8760     EmitFormatDiagnostic(S.PDiag(Diag)
8761                              << AT.getRepresentativeTypeName(S.Context)
8762                              << Ex->getType() << false << Ex->getSourceRange(),
8763                          Ex->getBeginLoc(),
8764                          /*IsStringLocation*/ false,
8765                          getSpecifierRange(startSpecifier, specifierLen));
8766   }
8767 
8768   return true;
8769 }
8770 
8771 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8772                               const Expr *OrigFormatExpr,
8773                               ArrayRef<const Expr *> Args,
8774                               bool HasVAListArg, unsigned format_idx,
8775                               unsigned firstDataArg,
8776                               Sema::FormatStringType Type,
8777                               bool inFunctionCall,
8778                               Sema::VariadicCallType CallType,
8779                               llvm::SmallBitVector &CheckedVarArgs,
8780                               UncoveredArgHandler &UncoveredArg,
8781                               bool IgnoreStringsWithoutSpecifiers) {
8782   // CHECK: is the format string a wide literal?
8783   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8784     CheckFormatHandler::EmitFormatDiagnostic(
8785         S, inFunctionCall, Args[format_idx],
8786         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8787         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8788     return;
8789   }
8790 
8791   // Str - The format string.  NOTE: this is NOT null-terminated!
8792   StringRef StrRef = FExpr->getString();
8793   const char *Str = StrRef.data();
8794   // Account for cases where the string literal is truncated in a declaration.
8795   const ConstantArrayType *T =
8796     S.Context.getAsConstantArrayType(FExpr->getType());
8797   assert(T && "String literal not of constant array type!");
8798   size_t TypeSize = T->getSize().getZExtValue();
8799   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8800   const unsigned numDataArgs = Args.size() - firstDataArg;
8801 
8802   if (IgnoreStringsWithoutSpecifiers &&
8803       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8804           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8805     return;
8806 
8807   // Emit a warning if the string literal is truncated and does not contain an
8808   // embedded null character.
8809   if (TypeSize <= StrRef.size() &&
8810       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8811     CheckFormatHandler::EmitFormatDiagnostic(
8812         S, inFunctionCall, Args[format_idx],
8813         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8814         FExpr->getBeginLoc(),
8815         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8816     return;
8817   }
8818 
8819   // CHECK: empty format string?
8820   if (StrLen == 0 && numDataArgs > 0) {
8821     CheckFormatHandler::EmitFormatDiagnostic(
8822         S, inFunctionCall, Args[format_idx],
8823         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8824         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8825     return;
8826   }
8827 
8828   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8829       Type == Sema::FST_Kprintf || Type == Sema::FST_FreeBSDKPrintf ||
8830       Type == Sema::FST_OSLog || Type == Sema::FST_OSTrace ||
8831       Type == Sema::FST_Syslog) {
8832     CheckPrintfHandler H(
8833         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8834         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8835         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8836         CheckedVarArgs, UncoveredArg);
8837 
8838     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8839                                                   S.getLangOpts(),
8840                                                   S.Context.getTargetInfo(),
8841                 Type == Sema::FST_Kprintf || Type == Sema::FST_FreeBSDKPrintf))
8842       H.DoneProcessing();
8843   } else if (Type == Sema::FST_Scanf) {
8844     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8845                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8846                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8847 
8848     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8849                                                  S.getLangOpts(),
8850                                                  S.Context.getTargetInfo()))
8851       H.DoneProcessing();
8852   } // TODO: handle other formats
8853 }
8854 
8855 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8856   // Str - The format string.  NOTE: this is NOT null-terminated!
8857   StringRef StrRef = FExpr->getString();
8858   const char *Str = StrRef.data();
8859   // Account for cases where the string literal is truncated in a declaration.
8860   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8861   assert(T && "String literal not of constant array type!");
8862   size_t TypeSize = T->getSize().getZExtValue();
8863   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8864   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8865                                                          getLangOpts(),
8866                                                          Context.getTargetInfo());
8867 }
8868 
8869 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8870 
8871 // Returns the related absolute value function that is larger, of 0 if one
8872 // does not exist.
8873 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8874   switch (AbsFunction) {
8875   default:
8876     return 0;
8877 
8878   case Builtin::BI__builtin_abs:
8879     return Builtin::BI__builtin_labs;
8880   case Builtin::BI__builtin_labs:
8881     return Builtin::BI__builtin_llabs;
8882   case Builtin::BI__builtin_llabs:
8883     return 0;
8884 
8885   case Builtin::BI__builtin_fabsf:
8886     return Builtin::BI__builtin_fabs;
8887   case Builtin::BI__builtin_fabs:
8888     return Builtin::BI__builtin_fabsl;
8889   case Builtin::BI__builtin_fabsl:
8890     return 0;
8891 
8892   case Builtin::BI__builtin_cabsf:
8893     return Builtin::BI__builtin_cabs;
8894   case Builtin::BI__builtin_cabs:
8895     return Builtin::BI__builtin_cabsl;
8896   case Builtin::BI__builtin_cabsl:
8897     return 0;
8898 
8899   case Builtin::BIabs:
8900     return Builtin::BIlabs;
8901   case Builtin::BIlabs:
8902     return Builtin::BIllabs;
8903   case Builtin::BIllabs:
8904     return 0;
8905 
8906   case Builtin::BIfabsf:
8907     return Builtin::BIfabs;
8908   case Builtin::BIfabs:
8909     return Builtin::BIfabsl;
8910   case Builtin::BIfabsl:
8911     return 0;
8912 
8913   case Builtin::BIcabsf:
8914    return Builtin::BIcabs;
8915   case Builtin::BIcabs:
8916     return Builtin::BIcabsl;
8917   case Builtin::BIcabsl:
8918     return 0;
8919   }
8920 }
8921 
8922 // Returns the argument type of the absolute value function.
8923 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8924                                              unsigned AbsType) {
8925   if (AbsType == 0)
8926     return QualType();
8927 
8928   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8929   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8930   if (Error != ASTContext::GE_None)
8931     return QualType();
8932 
8933   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8934   if (!FT)
8935     return QualType();
8936 
8937   if (FT->getNumParams() != 1)
8938     return QualType();
8939 
8940   return FT->getParamType(0);
8941 }
8942 
8943 // Returns the best absolute value function, or zero, based on type and
8944 // current absolute value function.
8945 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8946                                    unsigned AbsFunctionKind) {
8947   unsigned BestKind = 0;
8948   uint64_t ArgSize = Context.getTypeSize(ArgType);
8949   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8950        Kind = getLargerAbsoluteValueFunction(Kind)) {
8951     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8952     if (Context.getTypeSize(ParamType) >= ArgSize) {
8953       if (BestKind == 0)
8954         BestKind = Kind;
8955       else if (Context.hasSameType(ParamType, ArgType)) {
8956         BestKind = Kind;
8957         break;
8958       }
8959     }
8960   }
8961   return BestKind;
8962 }
8963 
8964 enum AbsoluteValueKind {
8965   AVK_Integer,
8966   AVK_Floating,
8967   AVK_Complex
8968 };
8969 
8970 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8971   if (T->isIntegralOrEnumerationType())
8972     return AVK_Integer;
8973   if (T->isRealFloatingType())
8974     return AVK_Floating;
8975   if (T->isAnyComplexType())
8976     return AVK_Complex;
8977 
8978   llvm_unreachable("Type not integer, floating, or complex");
8979 }
8980 
8981 // Changes the absolute value function to a different type.  Preserves whether
8982 // the function is a builtin.
8983 static unsigned changeAbsFunction(unsigned AbsKind,
8984                                   AbsoluteValueKind ValueKind) {
8985   switch (ValueKind) {
8986   case AVK_Integer:
8987     switch (AbsKind) {
8988     default:
8989       return 0;
8990     case Builtin::BI__builtin_fabsf:
8991     case Builtin::BI__builtin_fabs:
8992     case Builtin::BI__builtin_fabsl:
8993     case Builtin::BI__builtin_cabsf:
8994     case Builtin::BI__builtin_cabs:
8995     case Builtin::BI__builtin_cabsl:
8996       return Builtin::BI__builtin_abs;
8997     case Builtin::BIfabsf:
8998     case Builtin::BIfabs:
8999     case Builtin::BIfabsl:
9000     case Builtin::BIcabsf:
9001     case Builtin::BIcabs:
9002     case Builtin::BIcabsl:
9003       return Builtin::BIabs;
9004     }
9005   case AVK_Floating:
9006     switch (AbsKind) {
9007     default:
9008       return 0;
9009     case Builtin::BI__builtin_abs:
9010     case Builtin::BI__builtin_labs:
9011     case Builtin::BI__builtin_llabs:
9012     case Builtin::BI__builtin_cabsf:
9013     case Builtin::BI__builtin_cabs:
9014     case Builtin::BI__builtin_cabsl:
9015       return Builtin::BI__builtin_fabsf;
9016     case Builtin::BIabs:
9017     case Builtin::BIlabs:
9018     case Builtin::BIllabs:
9019     case Builtin::BIcabsf:
9020     case Builtin::BIcabs:
9021     case Builtin::BIcabsl:
9022       return Builtin::BIfabsf;
9023     }
9024   case AVK_Complex:
9025     switch (AbsKind) {
9026     default:
9027       return 0;
9028     case Builtin::BI__builtin_abs:
9029     case Builtin::BI__builtin_labs:
9030     case Builtin::BI__builtin_llabs:
9031     case Builtin::BI__builtin_fabsf:
9032     case Builtin::BI__builtin_fabs:
9033     case Builtin::BI__builtin_fabsl:
9034       return Builtin::BI__builtin_cabsf;
9035     case Builtin::BIabs:
9036     case Builtin::BIlabs:
9037     case Builtin::BIllabs:
9038     case Builtin::BIfabsf:
9039     case Builtin::BIfabs:
9040     case Builtin::BIfabsl:
9041       return Builtin::BIcabsf;
9042     }
9043   }
9044   llvm_unreachable("Unable to convert function");
9045 }
9046 
9047 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9048   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9049   if (!FnInfo)
9050     return 0;
9051 
9052   switch (FDecl->getBuiltinID()) {
9053   default:
9054     return 0;
9055   case Builtin::BI__builtin_abs:
9056   case Builtin::BI__builtin_fabs:
9057   case Builtin::BI__builtin_fabsf:
9058   case Builtin::BI__builtin_fabsl:
9059   case Builtin::BI__builtin_labs:
9060   case Builtin::BI__builtin_llabs:
9061   case Builtin::BI__builtin_cabs:
9062   case Builtin::BI__builtin_cabsf:
9063   case Builtin::BI__builtin_cabsl:
9064   case Builtin::BIabs:
9065   case Builtin::BIlabs:
9066   case Builtin::BIllabs:
9067   case Builtin::BIfabs:
9068   case Builtin::BIfabsf:
9069   case Builtin::BIfabsl:
9070   case Builtin::BIcabs:
9071   case Builtin::BIcabsf:
9072   case Builtin::BIcabsl:
9073     return FDecl->getBuiltinID();
9074   }
9075   llvm_unreachable("Unknown Builtin type");
9076 }
9077 
9078 // If the replacement is valid, emit a note with replacement function.
9079 // Additionally, suggest including the proper header if not already included.
9080 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9081                             unsigned AbsKind, QualType ArgType) {
9082   bool EmitHeaderHint = true;
9083   const char *HeaderName = nullptr;
9084   const char *FunctionName = nullptr;
9085   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9086     FunctionName = "std::abs";
9087     if (ArgType->isIntegralOrEnumerationType()) {
9088       HeaderName = "cstdlib";
9089     } else if (ArgType->isRealFloatingType()) {
9090       HeaderName = "cmath";
9091     } else {
9092       llvm_unreachable("Invalid Type");
9093     }
9094 
9095     // Lookup all std::abs
9096     if (NamespaceDecl *Std = S.getStdNamespace()) {
9097       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9098       R.suppressDiagnostics();
9099       S.LookupQualifiedName(R, Std);
9100 
9101       for (const auto *I : R) {
9102         const FunctionDecl *FDecl = nullptr;
9103         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9104           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9105         } else {
9106           FDecl = dyn_cast<FunctionDecl>(I);
9107         }
9108         if (!FDecl)
9109           continue;
9110 
9111         // Found std::abs(), check that they are the right ones.
9112         if (FDecl->getNumParams() != 1)
9113           continue;
9114 
9115         // Check that the parameter type can handle the argument.
9116         QualType ParamType = FDecl->getParamDecl(0)->getType();
9117         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9118             S.Context.getTypeSize(ArgType) <=
9119                 S.Context.getTypeSize(ParamType)) {
9120           // Found a function, don't need the header hint.
9121           EmitHeaderHint = false;
9122           break;
9123         }
9124       }
9125     }
9126   } else {
9127     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9128     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9129 
9130     if (HeaderName) {
9131       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9132       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9133       R.suppressDiagnostics();
9134       S.LookupName(R, S.getCurScope());
9135 
9136       if (R.isSingleResult()) {
9137         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9138         if (FD && FD->getBuiltinID() == AbsKind) {
9139           EmitHeaderHint = false;
9140         } else {
9141           return;
9142         }
9143       } else if (!R.empty()) {
9144         return;
9145       }
9146     }
9147   }
9148 
9149   S.Diag(Loc, diag::note_replace_abs_function)
9150       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9151 
9152   if (!HeaderName)
9153     return;
9154 
9155   if (!EmitHeaderHint)
9156     return;
9157 
9158   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9159                                                     << FunctionName;
9160 }
9161 
9162 template <std::size_t StrLen>
9163 static bool IsStdFunction(const FunctionDecl *FDecl,
9164                           const char (&Str)[StrLen]) {
9165   if (!FDecl)
9166     return false;
9167   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9168     return false;
9169   if (!FDecl->isInStdNamespace())
9170     return false;
9171 
9172   return true;
9173 }
9174 
9175 // Warn when using the wrong abs() function.
9176 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9177                                       const FunctionDecl *FDecl) {
9178   if (Call->getNumArgs() != 1)
9179     return;
9180 
9181   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9182   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9183   if (AbsKind == 0 && !IsStdAbs)
9184     return;
9185 
9186   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9187   QualType ParamType = Call->getArg(0)->getType();
9188 
9189   // Unsigned types cannot be negative.  Suggest removing the absolute value
9190   // function call.
9191   if (ArgType->isUnsignedIntegerType()) {
9192     const char *FunctionName =
9193         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9194     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9195     Diag(Call->getExprLoc(), diag::note_remove_abs)
9196         << FunctionName
9197         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9198     return;
9199   }
9200 
9201   // Taking the absolute value of a pointer is very suspicious, they probably
9202   // wanted to index into an array, dereference a pointer, call a function, etc.
9203   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9204     unsigned DiagType = 0;
9205     if (ArgType->isFunctionType())
9206       DiagType = 1;
9207     else if (ArgType->isArrayType())
9208       DiagType = 2;
9209 
9210     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9211     return;
9212   }
9213 
9214   // std::abs has overloads which prevent most of the absolute value problems
9215   // from occurring.
9216   if (IsStdAbs)
9217     return;
9218 
9219   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9220   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9221 
9222   // The argument and parameter are the same kind.  Check if they are the right
9223   // size.
9224   if (ArgValueKind == ParamValueKind) {
9225     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9226       return;
9227 
9228     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9229     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9230         << FDecl << ArgType << ParamType;
9231 
9232     if (NewAbsKind == 0)
9233       return;
9234 
9235     emitReplacement(*this, Call->getExprLoc(),
9236                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9237     return;
9238   }
9239 
9240   // ArgValueKind != ParamValueKind
9241   // The wrong type of absolute value function was used.  Attempt to find the
9242   // proper one.
9243   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9244   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9245   if (NewAbsKind == 0)
9246     return;
9247 
9248   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9249       << FDecl << ParamValueKind << ArgValueKind;
9250 
9251   emitReplacement(*this, Call->getExprLoc(),
9252                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9253 }
9254 
9255 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9256 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9257                                 const FunctionDecl *FDecl) {
9258   if (!Call || !FDecl) return;
9259 
9260   // Ignore template specializations and macros.
9261   if (inTemplateInstantiation()) return;
9262   if (Call->getExprLoc().isMacroID()) return;
9263 
9264   // Only care about the one template argument, two function parameter std::max
9265   if (Call->getNumArgs() != 2) return;
9266   if (!IsStdFunction(FDecl, "max")) return;
9267   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9268   if (!ArgList) return;
9269   if (ArgList->size() != 1) return;
9270 
9271   // Check that template type argument is unsigned integer.
9272   const auto& TA = ArgList->get(0);
9273   if (TA.getKind() != TemplateArgument::Type) return;
9274   QualType ArgType = TA.getAsType();
9275   if (!ArgType->isUnsignedIntegerType()) return;
9276 
9277   // See if either argument is a literal zero.
9278   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9279     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9280     if (!MTE) return false;
9281     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9282     if (!Num) return false;
9283     if (Num->getValue() != 0) return false;
9284     return true;
9285   };
9286 
9287   const Expr *FirstArg = Call->getArg(0);
9288   const Expr *SecondArg = Call->getArg(1);
9289   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9290   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9291 
9292   // Only warn when exactly one argument is zero.
9293   if (IsFirstArgZero == IsSecondArgZero) return;
9294 
9295   SourceRange FirstRange = FirstArg->getSourceRange();
9296   SourceRange SecondRange = SecondArg->getSourceRange();
9297 
9298   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9299 
9300   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9301       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9302 
9303   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9304   SourceRange RemovalRange;
9305   if (IsFirstArgZero) {
9306     RemovalRange = SourceRange(FirstRange.getBegin(),
9307                                SecondRange.getBegin().getLocWithOffset(-1));
9308   } else {
9309     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9310                                SecondRange.getEnd());
9311   }
9312 
9313   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9314         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9315         << FixItHint::CreateRemoval(RemovalRange);
9316 }
9317 
9318 //===--- CHECK: Standard memory functions ---------------------------------===//
9319 
9320 /// Takes the expression passed to the size_t parameter of functions
9321 /// such as memcmp, strncat, etc and warns if it's a comparison.
9322 ///
9323 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9324 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9325                                            IdentifierInfo *FnName,
9326                                            SourceLocation FnLoc,
9327                                            SourceLocation RParenLoc) {
9328   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9329   if (!Size)
9330     return false;
9331 
9332   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9333   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9334     return false;
9335 
9336   SourceRange SizeRange = Size->getSourceRange();
9337   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9338       << SizeRange << FnName;
9339   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9340       << FnName
9341       << FixItHint::CreateInsertion(
9342              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9343       << FixItHint::CreateRemoval(RParenLoc);
9344   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9345       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9346       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9347                                     ")");
9348 
9349   return true;
9350 }
9351 
9352 /// Determine whether the given type is or contains a dynamic class type
9353 /// (e.g., whether it has a vtable).
9354 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9355                                                      bool &IsContained) {
9356   // Look through array types while ignoring qualifiers.
9357   const Type *Ty = T->getBaseElementTypeUnsafe();
9358   IsContained = false;
9359 
9360   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9361   RD = RD ? RD->getDefinition() : nullptr;
9362   if (!RD || RD->isInvalidDecl())
9363     return nullptr;
9364 
9365   if (RD->isDynamicClass())
9366     return RD;
9367 
9368   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9369   // It's impossible for a class to transitively contain itself by value, so
9370   // infinite recursion is impossible.
9371   for (auto *FD : RD->fields()) {
9372     bool SubContained;
9373     if (const CXXRecordDecl *ContainedRD =
9374             getContainedDynamicClass(FD->getType(), SubContained)) {
9375       IsContained = true;
9376       return ContainedRD;
9377     }
9378   }
9379 
9380   return nullptr;
9381 }
9382 
9383 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9384   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9385     if (Unary->getKind() == UETT_SizeOf)
9386       return Unary;
9387   return nullptr;
9388 }
9389 
9390 /// If E is a sizeof expression, returns its argument expression,
9391 /// otherwise returns NULL.
9392 static const Expr *getSizeOfExprArg(const Expr *E) {
9393   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9394     if (!SizeOf->isArgumentType())
9395       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9396   return nullptr;
9397 }
9398 
9399 /// If E is a sizeof expression, returns its argument type.
9400 static QualType getSizeOfArgType(const Expr *E) {
9401   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9402     return SizeOf->getTypeOfArgument();
9403   return QualType();
9404 }
9405 
9406 namespace {
9407 
9408 struct SearchNonTrivialToInitializeField
9409     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9410   using Super =
9411       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9412 
9413   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9414 
9415   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9416                      SourceLocation SL) {
9417     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9418       asDerived().visitArray(PDIK, AT, SL);
9419       return;
9420     }
9421 
9422     Super::visitWithKind(PDIK, FT, SL);
9423   }
9424 
9425   void visitARCStrong(QualType FT, SourceLocation SL) {
9426     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9427   }
9428   void visitARCWeak(QualType FT, SourceLocation SL) {
9429     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9430   }
9431   void visitStruct(QualType FT, SourceLocation SL) {
9432     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9433       visit(FD->getType(), FD->getLocation());
9434   }
9435   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9436                   const ArrayType *AT, SourceLocation SL) {
9437     visit(getContext().getBaseElementType(AT), SL);
9438   }
9439   void visitTrivial(QualType FT, SourceLocation SL) {}
9440 
9441   static void diag(QualType RT, const Expr *E, Sema &S) {
9442     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9443   }
9444 
9445   ASTContext &getContext() { return S.getASTContext(); }
9446 
9447   const Expr *E;
9448   Sema &S;
9449 };
9450 
9451 struct SearchNonTrivialToCopyField
9452     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9453   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9454 
9455   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9456 
9457   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9458                      SourceLocation SL) {
9459     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9460       asDerived().visitArray(PCK, AT, SL);
9461       return;
9462     }
9463 
9464     Super::visitWithKind(PCK, FT, SL);
9465   }
9466 
9467   void visitARCStrong(QualType FT, SourceLocation SL) {
9468     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9469   }
9470   void visitARCWeak(QualType FT, SourceLocation SL) {
9471     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9472   }
9473   void visitStruct(QualType FT, SourceLocation SL) {
9474     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9475       visit(FD->getType(), FD->getLocation());
9476   }
9477   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9478                   SourceLocation SL) {
9479     visit(getContext().getBaseElementType(AT), SL);
9480   }
9481   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9482                 SourceLocation SL) {}
9483   void visitTrivial(QualType FT, SourceLocation SL) {}
9484   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9485 
9486   static void diag(QualType RT, const Expr *E, Sema &S) {
9487     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9488   }
9489 
9490   ASTContext &getContext() { return S.getASTContext(); }
9491 
9492   const Expr *E;
9493   Sema &S;
9494 };
9495 
9496 }
9497 
9498 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9499 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9500   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9501 
9502   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9503     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9504       return false;
9505 
9506     return doesExprLikelyComputeSize(BO->getLHS()) ||
9507            doesExprLikelyComputeSize(BO->getRHS());
9508   }
9509 
9510   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9511 }
9512 
9513 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9514 ///
9515 /// \code
9516 ///   #define MACRO 0
9517 ///   foo(MACRO);
9518 ///   foo(0);
9519 /// \endcode
9520 ///
9521 /// This should return true for the first call to foo, but not for the second
9522 /// (regardless of whether foo is a macro or function).
9523 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9524                                         SourceLocation CallLoc,
9525                                         SourceLocation ArgLoc) {
9526   if (!CallLoc.isMacroID())
9527     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9528 
9529   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9530          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9531 }
9532 
9533 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9534 /// last two arguments transposed.
9535 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9536   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9537     return;
9538 
9539   const Expr *SizeArg =
9540     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9541 
9542   auto isLiteralZero = [](const Expr *E) {
9543     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9544   };
9545 
9546   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9547   SourceLocation CallLoc = Call->getRParenLoc();
9548   SourceManager &SM = S.getSourceManager();
9549   if (isLiteralZero(SizeArg) &&
9550       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9551 
9552     SourceLocation DiagLoc = SizeArg->getExprLoc();
9553 
9554     // Some platforms #define bzero to __builtin_memset. See if this is the
9555     // case, and if so, emit a better diagnostic.
9556     if (BId == Builtin::BIbzero ||
9557         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9558                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9559       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9560       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9561     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9562       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9563       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9564     }
9565     return;
9566   }
9567 
9568   // If the second argument to a memset is a sizeof expression and the third
9569   // isn't, this is also likely an error. This should catch
9570   // 'memset(buf, sizeof(buf), 0xff)'.
9571   if (BId == Builtin::BImemset &&
9572       doesExprLikelyComputeSize(Call->getArg(1)) &&
9573       !doesExprLikelyComputeSize(Call->getArg(2))) {
9574     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9575     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9576     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9577     return;
9578   }
9579 }
9580 
9581 /// Check for dangerous or invalid arguments to memset().
9582 ///
9583 /// This issues warnings on known problematic, dangerous or unspecified
9584 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9585 /// function calls.
9586 ///
9587 /// \param Call The call expression to diagnose.
9588 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9589                                    unsigned BId,
9590                                    IdentifierInfo *FnName) {
9591   assert(BId != 0);
9592 
9593   // It is possible to have a non-standard definition of memset.  Validate
9594   // we have enough arguments, and if not, abort further checking.
9595   unsigned ExpectedNumArgs =
9596       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9597   if (Call->getNumArgs() < ExpectedNumArgs)
9598     return;
9599 
9600   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9601                       BId == Builtin::BIstrndup ? 1 : 2);
9602   unsigned LenArg =
9603       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9604   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9605 
9606   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9607                                      Call->getBeginLoc(), Call->getRParenLoc()))
9608     return;
9609 
9610   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9611   CheckMemaccessSize(*this, BId, Call);
9612 
9613   // We have special checking when the length is a sizeof expression.
9614   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9615   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9616   llvm::FoldingSetNodeID SizeOfArgID;
9617 
9618   // Although widely used, 'bzero' is not a standard function. Be more strict
9619   // with the argument types before allowing diagnostics and only allow the
9620   // form bzero(ptr, sizeof(...)).
9621   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9622   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9623     return;
9624 
9625   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9626     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9627     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9628 
9629     QualType DestTy = Dest->getType();
9630     QualType PointeeTy;
9631     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9632       PointeeTy = DestPtrTy->getPointeeType();
9633 
9634       // Never warn about void type pointers. This can be used to suppress
9635       // false positives.
9636       if (PointeeTy->isVoidType())
9637         continue;
9638 
9639       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9640       // actually comparing the expressions for equality. Because computing the
9641       // expression IDs can be expensive, we only do this if the diagnostic is
9642       // enabled.
9643       if (SizeOfArg &&
9644           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9645                            SizeOfArg->getExprLoc())) {
9646         // We only compute IDs for expressions if the warning is enabled, and
9647         // cache the sizeof arg's ID.
9648         if (SizeOfArgID == llvm::FoldingSetNodeID())
9649           SizeOfArg->Profile(SizeOfArgID, Context, true);
9650         llvm::FoldingSetNodeID DestID;
9651         Dest->Profile(DestID, Context, true);
9652         if (DestID == SizeOfArgID) {
9653           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9654           //       over sizeof(src) as well.
9655           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9656           StringRef ReadableName = FnName->getName();
9657 
9658           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9659             if (UnaryOp->getOpcode() == UO_AddrOf)
9660               ActionIdx = 1; // If its an address-of operator, just remove it.
9661           if (!PointeeTy->isIncompleteType() &&
9662               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9663             ActionIdx = 2; // If the pointee's size is sizeof(char),
9664                            // suggest an explicit length.
9665 
9666           // If the function is defined as a builtin macro, do not show macro
9667           // expansion.
9668           SourceLocation SL = SizeOfArg->getExprLoc();
9669           SourceRange DSR = Dest->getSourceRange();
9670           SourceRange SSR = SizeOfArg->getSourceRange();
9671           SourceManager &SM = getSourceManager();
9672 
9673           if (SM.isMacroArgExpansion(SL)) {
9674             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9675             SL = SM.getSpellingLoc(SL);
9676             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9677                              SM.getSpellingLoc(DSR.getEnd()));
9678             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9679                              SM.getSpellingLoc(SSR.getEnd()));
9680           }
9681 
9682           DiagRuntimeBehavior(SL, SizeOfArg,
9683                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9684                                 << ReadableName
9685                                 << PointeeTy
9686                                 << DestTy
9687                                 << DSR
9688                                 << SSR);
9689           DiagRuntimeBehavior(SL, SizeOfArg,
9690                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9691                                 << ActionIdx
9692                                 << SSR);
9693 
9694           break;
9695         }
9696       }
9697 
9698       // Also check for cases where the sizeof argument is the exact same
9699       // type as the memory argument, and where it points to a user-defined
9700       // record type.
9701       if (SizeOfArgTy != QualType()) {
9702         if (PointeeTy->isRecordType() &&
9703             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9704           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9705                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9706                                 << FnName << SizeOfArgTy << ArgIdx
9707                                 << PointeeTy << Dest->getSourceRange()
9708                                 << LenExpr->getSourceRange());
9709           break;
9710         }
9711       }
9712     } else if (DestTy->isArrayType()) {
9713       PointeeTy = DestTy;
9714     }
9715 
9716     if (PointeeTy == QualType())
9717       continue;
9718 
9719     // Always complain about dynamic classes.
9720     bool IsContained;
9721     if (const CXXRecordDecl *ContainedRD =
9722             getContainedDynamicClass(PointeeTy, IsContained)) {
9723 
9724       unsigned OperationType = 0;
9725       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9726       // "overwritten" if we're warning about the destination for any call
9727       // but memcmp; otherwise a verb appropriate to the call.
9728       if (ArgIdx != 0 || IsCmp) {
9729         if (BId == Builtin::BImemcpy)
9730           OperationType = 1;
9731         else if(BId == Builtin::BImemmove)
9732           OperationType = 2;
9733         else if (IsCmp)
9734           OperationType = 3;
9735       }
9736 
9737       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9738                           PDiag(diag::warn_dyn_class_memaccess)
9739                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9740                               << IsContained << ContainedRD << OperationType
9741                               << Call->getCallee()->getSourceRange());
9742     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9743              BId != Builtin::BImemset)
9744       DiagRuntimeBehavior(
9745         Dest->getExprLoc(), Dest,
9746         PDiag(diag::warn_arc_object_memaccess)
9747           << ArgIdx << FnName << PointeeTy
9748           << Call->getCallee()->getSourceRange());
9749     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9750       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9751           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9752         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9753                             PDiag(diag::warn_cstruct_memaccess)
9754                                 << ArgIdx << FnName << PointeeTy << 0);
9755         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9756       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9757                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9758         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9759                             PDiag(diag::warn_cstruct_memaccess)
9760                                 << ArgIdx << FnName << PointeeTy << 1);
9761         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9762       } else {
9763         continue;
9764       }
9765     } else
9766       continue;
9767 
9768     DiagRuntimeBehavior(
9769       Dest->getExprLoc(), Dest,
9770       PDiag(diag::note_bad_memaccess_silence)
9771         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9772     break;
9773   }
9774 }
9775 
9776 // A little helper routine: ignore addition and subtraction of integer literals.
9777 // This intentionally does not ignore all integer constant expressions because
9778 // we don't want to remove sizeof().
9779 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9780   Ex = Ex->IgnoreParenCasts();
9781 
9782   while (true) {
9783     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9784     if (!BO || !BO->isAdditiveOp())
9785       break;
9786 
9787     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9788     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9789 
9790     if (isa<IntegerLiteral>(RHS))
9791       Ex = LHS;
9792     else if (isa<IntegerLiteral>(LHS))
9793       Ex = RHS;
9794     else
9795       break;
9796   }
9797 
9798   return Ex;
9799 }
9800 
9801 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9802                                                       ASTContext &Context) {
9803   // Only handle constant-sized or VLAs, but not flexible members.
9804   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9805     // Only issue the FIXIT for arrays of size > 1.
9806     if (CAT->getSize().getSExtValue() <= 1)
9807       return false;
9808   } else if (!Ty->isVariableArrayType()) {
9809     return false;
9810   }
9811   return true;
9812 }
9813 
9814 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9815 // be the size of the source, instead of the destination.
9816 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9817                                     IdentifierInfo *FnName) {
9818 
9819   // Don't crash if the user has the wrong number of arguments
9820   unsigned NumArgs = Call->getNumArgs();
9821   if ((NumArgs != 3) && (NumArgs != 4))
9822     return;
9823 
9824   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9825   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9826   const Expr *CompareWithSrc = nullptr;
9827 
9828   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9829                                      Call->getBeginLoc(), Call->getRParenLoc()))
9830     return;
9831 
9832   // Look for 'strlcpy(dst, x, sizeof(x))'
9833   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9834     CompareWithSrc = Ex;
9835   else {
9836     // Look for 'strlcpy(dst, x, strlen(x))'
9837     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9838       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9839           SizeCall->getNumArgs() == 1)
9840         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9841     }
9842   }
9843 
9844   if (!CompareWithSrc)
9845     return;
9846 
9847   // Determine if the argument to sizeof/strlen is equal to the source
9848   // argument.  In principle there's all kinds of things you could do
9849   // here, for instance creating an == expression and evaluating it with
9850   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9851   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9852   if (!SrcArgDRE)
9853     return;
9854 
9855   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9856   if (!CompareWithSrcDRE ||
9857       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9858     return;
9859 
9860   const Expr *OriginalSizeArg = Call->getArg(2);
9861   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9862       << OriginalSizeArg->getSourceRange() << FnName;
9863 
9864   // Output a FIXIT hint if the destination is an array (rather than a
9865   // pointer to an array).  This could be enhanced to handle some
9866   // pointers if we know the actual size, like if DstArg is 'array+2'
9867   // we could say 'sizeof(array)-2'.
9868   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9869   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9870     return;
9871 
9872   SmallString<128> sizeString;
9873   llvm::raw_svector_ostream OS(sizeString);
9874   OS << "sizeof(";
9875   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9876   OS << ")";
9877 
9878   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9879       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9880                                       OS.str());
9881 }
9882 
9883 /// Check if two expressions refer to the same declaration.
9884 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9885   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9886     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9887       return D1->getDecl() == D2->getDecl();
9888   return false;
9889 }
9890 
9891 static const Expr *getStrlenExprArg(const Expr *E) {
9892   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9893     const FunctionDecl *FD = CE->getDirectCallee();
9894     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9895       return nullptr;
9896     return CE->getArg(0)->IgnoreParenCasts();
9897   }
9898   return nullptr;
9899 }
9900 
9901 // Warn on anti-patterns as the 'size' argument to strncat.
9902 // The correct size argument should look like following:
9903 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9904 void Sema::CheckStrncatArguments(const CallExpr *CE,
9905                                  IdentifierInfo *FnName) {
9906   // Don't crash if the user has the wrong number of arguments.
9907   if (CE->getNumArgs() < 3)
9908     return;
9909   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9910   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9911   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9912 
9913   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9914                                      CE->getRParenLoc()))
9915     return;
9916 
9917   // Identify common expressions, which are wrongly used as the size argument
9918   // to strncat and may lead to buffer overflows.
9919   unsigned PatternType = 0;
9920   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9921     // - sizeof(dst)
9922     if (referToTheSameDecl(SizeOfArg, DstArg))
9923       PatternType = 1;
9924     // - sizeof(src)
9925     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9926       PatternType = 2;
9927   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9928     if (BE->getOpcode() == BO_Sub) {
9929       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9930       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9931       // - sizeof(dst) - strlen(dst)
9932       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9933           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9934         PatternType = 1;
9935       // - sizeof(src) - (anything)
9936       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9937         PatternType = 2;
9938     }
9939   }
9940 
9941   if (PatternType == 0)
9942     return;
9943 
9944   // Generate the diagnostic.
9945   SourceLocation SL = LenArg->getBeginLoc();
9946   SourceRange SR = LenArg->getSourceRange();
9947   SourceManager &SM = getSourceManager();
9948 
9949   // If the function is defined as a builtin macro, do not show macro expansion.
9950   if (SM.isMacroArgExpansion(SL)) {
9951     SL = SM.getSpellingLoc(SL);
9952     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9953                      SM.getSpellingLoc(SR.getEnd()));
9954   }
9955 
9956   // Check if the destination is an array (rather than a pointer to an array).
9957   QualType DstTy = DstArg->getType();
9958   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9959                                                                     Context);
9960   if (!isKnownSizeArray) {
9961     if (PatternType == 1)
9962       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9963     else
9964       Diag(SL, diag::warn_strncat_src_size) << SR;
9965     return;
9966   }
9967 
9968   if (PatternType == 1)
9969     Diag(SL, diag::warn_strncat_large_size) << SR;
9970   else
9971     Diag(SL, diag::warn_strncat_src_size) << SR;
9972 
9973   SmallString<128> sizeString;
9974   llvm::raw_svector_ostream OS(sizeString);
9975   OS << "sizeof(";
9976   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9977   OS << ") - ";
9978   OS << "strlen(";
9979   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9980   OS << ") - 1";
9981 
9982   Diag(SL, diag::note_strncat_wrong_size)
9983     << FixItHint::CreateReplacement(SR, OS.str());
9984 }
9985 
9986 void
9987 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9988                          SourceLocation ReturnLoc,
9989                          bool isObjCMethod,
9990                          const AttrVec *Attrs,
9991                          const FunctionDecl *FD) {
9992   // Check if the return value is null but should not be.
9993   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9994        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9995       CheckNonNullExpr(*this, RetValExp))
9996     Diag(ReturnLoc, diag::warn_null_ret)
9997       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9998 
9999   // C++11 [basic.stc.dynamic.allocation]p4:
10000   //   If an allocation function declared with a non-throwing
10001   //   exception-specification fails to allocate storage, it shall return
10002   //   a null pointer. Any other allocation function that fails to allocate
10003   //   storage shall indicate failure only by throwing an exception [...]
10004   if (FD) {
10005     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10006     if (Op == OO_New || Op == OO_Array_New) {
10007       const FunctionProtoType *Proto
10008         = FD->getType()->castAs<FunctionProtoType>();
10009       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10010           CheckNonNullExpr(*this, RetValExp))
10011         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10012           << FD << getLangOpts().CPlusPlus11;
10013     }
10014   }
10015 }
10016 
10017 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10018 
10019 /// Check for comparisons of floating point operands using != and ==.
10020 /// Issue a warning if these are no self-comparisons, as they are not likely
10021 /// to do what the programmer intended.
10022 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10023   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10024   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10025 
10026   // Special case: check for x == x (which is OK).
10027   // Do not emit warnings for such cases.
10028   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10029     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10030       if (DRL->getDecl() == DRR->getDecl())
10031         return;
10032 
10033   // Special case: check for comparisons against literals that can be exactly
10034   //  represented by APFloat.  In such cases, do not emit a warning.  This
10035   //  is a heuristic: often comparison against such literals are used to
10036   //  detect if a value in a variable has not changed.  This clearly can
10037   //  lead to false negatives.
10038   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10039     if (FLL->isExact())
10040       return;
10041   } else
10042     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10043       if (FLR->isExact())
10044         return;
10045 
10046   // Check for comparisons with builtin types.
10047   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10048     if (CL->getBuiltinCallee())
10049       return;
10050 
10051   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10052     if (CR->getBuiltinCallee())
10053       return;
10054 
10055   // Emit the diagnostic.
10056   Diag(Loc, diag::warn_floatingpoint_eq)
10057     << LHS->getSourceRange() << RHS->getSourceRange();
10058 }
10059 
10060 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10061 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10062 
10063 namespace {
10064 
10065 /// Structure recording the 'active' range of an integer-valued
10066 /// expression.
10067 struct IntRange {
10068   /// The number of bits active in the int.
10069   unsigned Width;
10070 
10071   /// True if the int is known not to have negative values.
10072   bool NonNegative;
10073 
10074   IntRange(unsigned Width, bool NonNegative)
10075       : Width(Width), NonNegative(NonNegative) {}
10076 
10077   /// Returns the range of the bool type.
10078   static IntRange forBoolType() {
10079     return IntRange(1, true);
10080   }
10081 
10082   /// Returns the range of an opaque value of the given integral type.
10083   static IntRange forValueOfType(ASTContext &C, QualType T) {
10084     return forValueOfCanonicalType(C,
10085                           T->getCanonicalTypeInternal().getTypePtr());
10086   }
10087 
10088   /// Returns the range of an opaque value of a canonical integral type.
10089   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10090     assert(T->isCanonicalUnqualified());
10091 
10092     if (const VectorType *VT = dyn_cast<VectorType>(T))
10093       T = VT->getElementType().getTypePtr();
10094     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10095       T = CT->getElementType().getTypePtr();
10096     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10097       T = AT->getValueType().getTypePtr();
10098 
10099     if (!C.getLangOpts().CPlusPlus) {
10100       // For enum types in C code, use the underlying datatype.
10101       if (const EnumType *ET = dyn_cast<EnumType>(T))
10102         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10103     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10104       // For enum types in C++, use the known bit width of the enumerators.
10105       EnumDecl *Enum = ET->getDecl();
10106       // In C++11, enums can have a fixed underlying type. Use this type to
10107       // compute the range.
10108       if (Enum->isFixed()) {
10109         return IntRange(C.getIntWidth(QualType(T, 0)),
10110                         !ET->isSignedIntegerOrEnumerationType());
10111       }
10112 
10113       unsigned NumPositive = Enum->getNumPositiveBits();
10114       unsigned NumNegative = Enum->getNumNegativeBits();
10115 
10116       if (NumNegative == 0)
10117         return IntRange(NumPositive, true/*NonNegative*/);
10118       else
10119         return IntRange(std::max(NumPositive + 1, NumNegative),
10120                         false/*NonNegative*/);
10121     }
10122 
10123     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10124       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10125 
10126     const BuiltinType *BT = cast<BuiltinType>(T);
10127     assert(BT->isInteger());
10128 
10129     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10130   }
10131 
10132   /// Returns the "target" range of a canonical integral type, i.e.
10133   /// the range of values expressible in the type.
10134   ///
10135   /// This matches forValueOfCanonicalType except that enums have the
10136   /// full range of their type, not the range of their enumerators.
10137   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10138     assert(T->isCanonicalUnqualified());
10139 
10140     if (const VectorType *VT = dyn_cast<VectorType>(T))
10141       T = VT->getElementType().getTypePtr();
10142     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10143       T = CT->getElementType().getTypePtr();
10144     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10145       T = AT->getValueType().getTypePtr();
10146     if (const EnumType *ET = dyn_cast<EnumType>(T))
10147       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10148 
10149     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10150       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10151 
10152     const BuiltinType *BT = cast<BuiltinType>(T);
10153     assert(BT->isInteger());
10154 
10155     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10156   }
10157 
10158   /// Returns the supremum of two ranges: i.e. their conservative merge.
10159   static IntRange join(IntRange L, IntRange R) {
10160     return IntRange(std::max(L.Width, R.Width),
10161                     L.NonNegative && R.NonNegative);
10162   }
10163 
10164   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10165   static IntRange meet(IntRange L, IntRange R) {
10166     return IntRange(std::min(L.Width, R.Width),
10167                     L.NonNegative || R.NonNegative);
10168   }
10169 };
10170 
10171 } // namespace
10172 
10173 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10174                               unsigned MaxWidth) {
10175   if (value.isSigned() && value.isNegative())
10176     return IntRange(value.getMinSignedBits(), false);
10177 
10178   if (value.getBitWidth() > MaxWidth)
10179     value = value.trunc(MaxWidth);
10180 
10181   // isNonNegative() just checks the sign bit without considering
10182   // signedness.
10183   return IntRange(value.getActiveBits(), true);
10184 }
10185 
10186 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10187                               unsigned MaxWidth) {
10188   if (result.isInt())
10189     return GetValueRange(C, result.getInt(), MaxWidth);
10190 
10191   if (result.isVector()) {
10192     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10193     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10194       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10195       R = IntRange::join(R, El);
10196     }
10197     return R;
10198   }
10199 
10200   if (result.isComplexInt()) {
10201     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10202     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10203     return IntRange::join(R, I);
10204   }
10205 
10206   // This can happen with lossless casts to intptr_t of "based" lvalues.
10207   // Assume it might use arbitrary bits.
10208   // FIXME: The only reason we need to pass the type in here is to get
10209   // the sign right on this one case.  It would be nice if APValue
10210   // preserved this.
10211   assert(result.isLValue() || result.isAddrLabelDiff());
10212   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10213 }
10214 
10215 static QualType GetExprType(const Expr *E) {
10216   QualType Ty = E->getType();
10217   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10218     Ty = AtomicRHS->getValueType();
10219   return Ty;
10220 }
10221 
10222 /// Pseudo-evaluate the given integer expression, estimating the
10223 /// range of values it might take.
10224 ///
10225 /// \param MaxWidth - the width to which the value will be truncated
10226 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10227                              bool InConstantContext) {
10228   E = E->IgnoreParens();
10229 
10230   // Try a full evaluation first.
10231   Expr::EvalResult result;
10232   if (E->EvaluateAsRValue(result, C, InConstantContext))
10233     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10234 
10235   // I think we only want to look through implicit casts here; if the
10236   // user has an explicit widening cast, we should treat the value as
10237   // being of the new, wider type.
10238   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10239     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10240       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10241 
10242     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10243 
10244     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10245                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10246 
10247     // Assume that non-integer casts can span the full range of the type.
10248     if (!isIntegerCast)
10249       return OutputTypeRange;
10250 
10251     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10252                                      std::min(MaxWidth, OutputTypeRange.Width),
10253                                      InConstantContext);
10254 
10255     // Bail out if the subexpr's range is as wide as the cast type.
10256     if (SubRange.Width >= OutputTypeRange.Width)
10257       return OutputTypeRange;
10258 
10259     // Otherwise, we take the smaller width, and we're non-negative if
10260     // either the output type or the subexpr is.
10261     return IntRange(SubRange.Width,
10262                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10263   }
10264 
10265   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10266     // If we can fold the condition, just take that operand.
10267     bool CondResult;
10268     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10269       return GetExprRange(C,
10270                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10271                           MaxWidth, InConstantContext);
10272 
10273     // Otherwise, conservatively merge.
10274     IntRange L =
10275         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10276     IntRange R =
10277         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10278     return IntRange::join(L, R);
10279   }
10280 
10281   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10282     switch (BO->getOpcode()) {
10283     case BO_Cmp:
10284       llvm_unreachable("builtin <=> should have class type");
10285 
10286     // Boolean-valued operations are single-bit and positive.
10287     case BO_LAnd:
10288     case BO_LOr:
10289     case BO_LT:
10290     case BO_GT:
10291     case BO_LE:
10292     case BO_GE:
10293     case BO_EQ:
10294     case BO_NE:
10295       return IntRange::forBoolType();
10296 
10297     // The type of the assignments is the type of the LHS, so the RHS
10298     // is not necessarily the same type.
10299     case BO_MulAssign:
10300     case BO_DivAssign:
10301     case BO_RemAssign:
10302     case BO_AddAssign:
10303     case BO_SubAssign:
10304     case BO_XorAssign:
10305     case BO_OrAssign:
10306       // TODO: bitfields?
10307       return IntRange::forValueOfType(C, GetExprType(E));
10308 
10309     // Simple assignments just pass through the RHS, which will have
10310     // been coerced to the LHS type.
10311     case BO_Assign:
10312       // TODO: bitfields?
10313       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10314 
10315     // Operations with opaque sources are black-listed.
10316     case BO_PtrMemD:
10317     case BO_PtrMemI:
10318       return IntRange::forValueOfType(C, GetExprType(E));
10319 
10320     // Bitwise-and uses the *infinum* of the two source ranges.
10321     case BO_And:
10322     case BO_AndAssign:
10323       return IntRange::meet(
10324           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10325           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10326 
10327     // Left shift gets black-listed based on a judgement call.
10328     case BO_Shl:
10329       // ...except that we want to treat '1 << (blah)' as logically
10330       // positive.  It's an important idiom.
10331       if (IntegerLiteral *I
10332             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10333         if (I->getValue() == 1) {
10334           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10335           return IntRange(R.Width, /*NonNegative*/ true);
10336         }
10337       }
10338       LLVM_FALLTHROUGH;
10339 
10340     case BO_ShlAssign:
10341       return IntRange::forValueOfType(C, GetExprType(E));
10342 
10343     // Right shift by a constant can narrow its left argument.
10344     case BO_Shr:
10345     case BO_ShrAssign: {
10346       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10347 
10348       // If the shift amount is a positive constant, drop the width by
10349       // that much.
10350       llvm::APSInt shift;
10351       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10352           shift.isNonNegative()) {
10353         unsigned zext = shift.getZExtValue();
10354         if (zext >= L.Width)
10355           L.Width = (L.NonNegative ? 0 : 1);
10356         else
10357           L.Width -= zext;
10358       }
10359 
10360       return L;
10361     }
10362 
10363     // Comma acts as its right operand.
10364     case BO_Comma:
10365       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10366 
10367     // Black-list pointer subtractions.
10368     case BO_Sub:
10369       if (BO->getLHS()->getType()->isPointerType())
10370         return IntRange::forValueOfType(C, GetExprType(E));
10371       break;
10372 
10373     // The width of a division result is mostly determined by the size
10374     // of the LHS.
10375     case BO_Div: {
10376       // Don't 'pre-truncate' the operands.
10377       unsigned opWidth = C.getIntWidth(GetExprType(E));
10378       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10379 
10380       // If the divisor is constant, use that.
10381       llvm::APSInt divisor;
10382       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10383         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10384         if (log2 >= L.Width)
10385           L.Width = (L.NonNegative ? 0 : 1);
10386         else
10387           L.Width = std::min(L.Width - log2, MaxWidth);
10388         return L;
10389       }
10390 
10391       // Otherwise, just use the LHS's width.
10392       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10393       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10394     }
10395 
10396     // The result of a remainder can't be larger than the result of
10397     // either side.
10398     case BO_Rem: {
10399       // Don't 'pre-truncate' the operands.
10400       unsigned opWidth = C.getIntWidth(GetExprType(E));
10401       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10402       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10403 
10404       IntRange meet = IntRange::meet(L, R);
10405       meet.Width = std::min(meet.Width, MaxWidth);
10406       return meet;
10407     }
10408 
10409     // The default behavior is okay for these.
10410     case BO_Mul:
10411     case BO_Add:
10412     case BO_Xor:
10413     case BO_Or:
10414       break;
10415     }
10416 
10417     // The default case is to treat the operation as if it were closed
10418     // on the narrowest type that encompasses both operands.
10419     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10420     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10421     return IntRange::join(L, R);
10422   }
10423 
10424   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10425     switch (UO->getOpcode()) {
10426     // Boolean-valued operations are white-listed.
10427     case UO_LNot:
10428       return IntRange::forBoolType();
10429 
10430     // Operations with opaque sources are black-listed.
10431     case UO_Deref:
10432     case UO_AddrOf: // should be impossible
10433       return IntRange::forValueOfType(C, GetExprType(E));
10434 
10435     default:
10436       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10437     }
10438   }
10439 
10440   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10441     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10442 
10443   if (const auto *BitField = E->getSourceBitField())
10444     return IntRange(BitField->getBitWidthValue(C),
10445                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10446 
10447   return IntRange::forValueOfType(C, GetExprType(E));
10448 }
10449 
10450 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10451                              bool InConstantContext) {
10452   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10453 }
10454 
10455 /// Checks whether the given value, which currently has the given
10456 /// source semantics, has the same value when coerced through the
10457 /// target semantics.
10458 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10459                                  const llvm::fltSemantics &Src,
10460                                  const llvm::fltSemantics &Tgt) {
10461   llvm::APFloat truncated = value;
10462 
10463   bool ignored;
10464   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10465   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10466 
10467   return truncated.bitwiseIsEqual(value);
10468 }
10469 
10470 /// Checks whether the given value, which currently has the given
10471 /// source semantics, has the same value when coerced through the
10472 /// target semantics.
10473 ///
10474 /// The value might be a vector of floats (or a complex number).
10475 static bool IsSameFloatAfterCast(const APValue &value,
10476                                  const llvm::fltSemantics &Src,
10477                                  const llvm::fltSemantics &Tgt) {
10478   if (value.isFloat())
10479     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10480 
10481   if (value.isVector()) {
10482     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10483       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10484         return false;
10485     return true;
10486   }
10487 
10488   assert(value.isComplexFloat());
10489   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10490           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10491 }
10492 
10493 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10494                                        bool IsListInit = false);
10495 
10496 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10497   // Suppress cases where we are comparing against an enum constant.
10498   if (const DeclRefExpr *DR =
10499       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10500     if (isa<EnumConstantDecl>(DR->getDecl()))
10501       return true;
10502 
10503   // Suppress cases where the value is expanded from a macro, unless that macro
10504   // is how a language represents a boolean literal. This is the case in both C
10505   // and Objective-C.
10506   SourceLocation BeginLoc = E->getBeginLoc();
10507   if (BeginLoc.isMacroID()) {
10508     StringRef MacroName = Lexer::getImmediateMacroName(
10509         BeginLoc, S.getSourceManager(), S.getLangOpts());
10510     return MacroName != "YES" && MacroName != "NO" &&
10511            MacroName != "true" && MacroName != "false";
10512   }
10513 
10514   return false;
10515 }
10516 
10517 static bool isKnownToHaveUnsignedValue(Expr *E) {
10518   return E->getType()->isIntegerType() &&
10519          (!E->getType()->isSignedIntegerType() ||
10520           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10521 }
10522 
10523 namespace {
10524 /// The promoted range of values of a type. In general this has the
10525 /// following structure:
10526 ///
10527 ///     |-----------| . . . |-----------|
10528 ///     ^           ^       ^           ^
10529 ///    Min       HoleMin  HoleMax      Max
10530 ///
10531 /// ... where there is only a hole if a signed type is promoted to unsigned
10532 /// (in which case Min and Max are the smallest and largest representable
10533 /// values).
10534 struct PromotedRange {
10535   // Min, or HoleMax if there is a hole.
10536   llvm::APSInt PromotedMin;
10537   // Max, or HoleMin if there is a hole.
10538   llvm::APSInt PromotedMax;
10539 
10540   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10541     if (R.Width == 0)
10542       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10543     else if (R.Width >= BitWidth && !Unsigned) {
10544       // Promotion made the type *narrower*. This happens when promoting
10545       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10546       // Treat all values of 'signed int' as being in range for now.
10547       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10548       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10549     } else {
10550       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10551                         .extOrTrunc(BitWidth);
10552       PromotedMin.setIsUnsigned(Unsigned);
10553 
10554       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10555                         .extOrTrunc(BitWidth);
10556       PromotedMax.setIsUnsigned(Unsigned);
10557     }
10558   }
10559 
10560   // Determine whether this range is contiguous (has no hole).
10561   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10562 
10563   // Where a constant value is within the range.
10564   enum ComparisonResult {
10565     LT = 0x1,
10566     LE = 0x2,
10567     GT = 0x4,
10568     GE = 0x8,
10569     EQ = 0x10,
10570     NE = 0x20,
10571     InRangeFlag = 0x40,
10572 
10573     Less = LE | LT | NE,
10574     Min = LE | InRangeFlag,
10575     InRange = InRangeFlag,
10576     Max = GE | InRangeFlag,
10577     Greater = GE | GT | NE,
10578 
10579     OnlyValue = LE | GE | EQ | InRangeFlag,
10580     InHole = NE
10581   };
10582 
10583   ComparisonResult compare(const llvm::APSInt &Value) const {
10584     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10585            Value.isUnsigned() == PromotedMin.isUnsigned());
10586     if (!isContiguous()) {
10587       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10588       if (Value.isMinValue()) return Min;
10589       if (Value.isMaxValue()) return Max;
10590       if (Value >= PromotedMin) return InRange;
10591       if (Value <= PromotedMax) return InRange;
10592       return InHole;
10593     }
10594 
10595     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10596     case -1: return Less;
10597     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10598     case 1:
10599       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10600       case -1: return InRange;
10601       case 0: return Max;
10602       case 1: return Greater;
10603       }
10604     }
10605 
10606     llvm_unreachable("impossible compare result");
10607   }
10608 
10609   static llvm::Optional<StringRef>
10610   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10611     if (Op == BO_Cmp) {
10612       ComparisonResult LTFlag = LT, GTFlag = GT;
10613       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10614 
10615       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10616       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10617       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10618       return llvm::None;
10619     }
10620 
10621     ComparisonResult TrueFlag, FalseFlag;
10622     if (Op == BO_EQ) {
10623       TrueFlag = EQ;
10624       FalseFlag = NE;
10625     } else if (Op == BO_NE) {
10626       TrueFlag = NE;
10627       FalseFlag = EQ;
10628     } else {
10629       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10630         TrueFlag = LT;
10631         FalseFlag = GE;
10632       } else {
10633         TrueFlag = GT;
10634         FalseFlag = LE;
10635       }
10636       if (Op == BO_GE || Op == BO_LE)
10637         std::swap(TrueFlag, FalseFlag);
10638     }
10639     if (R & TrueFlag)
10640       return StringRef("true");
10641     if (R & FalseFlag)
10642       return StringRef("false");
10643     return llvm::None;
10644   }
10645 };
10646 }
10647 
10648 static bool HasEnumType(Expr *E) {
10649   // Strip off implicit integral promotions.
10650   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10651     if (ICE->getCastKind() != CK_IntegralCast &&
10652         ICE->getCastKind() != CK_NoOp)
10653       break;
10654     E = ICE->getSubExpr();
10655   }
10656 
10657   return E->getType()->isEnumeralType();
10658 }
10659 
10660 static int classifyConstantValue(Expr *Constant) {
10661   // The values of this enumeration are used in the diagnostics
10662   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10663   enum ConstantValueKind {
10664     Miscellaneous = 0,
10665     LiteralTrue,
10666     LiteralFalse
10667   };
10668   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10669     return BL->getValue() ? ConstantValueKind::LiteralTrue
10670                           : ConstantValueKind::LiteralFalse;
10671   return ConstantValueKind::Miscellaneous;
10672 }
10673 
10674 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10675                                         Expr *Constant, Expr *Other,
10676                                         const llvm::APSInt &Value,
10677                                         bool RhsConstant) {
10678   if (S.inTemplateInstantiation())
10679     return false;
10680 
10681   Expr *OriginalOther = Other;
10682 
10683   Constant = Constant->IgnoreParenImpCasts();
10684   Other = Other->IgnoreParenImpCasts();
10685 
10686   // Suppress warnings on tautological comparisons between values of the same
10687   // enumeration type. There are only two ways we could warn on this:
10688   //  - If the constant is outside the range of representable values of
10689   //    the enumeration. In such a case, we should warn about the cast
10690   //    to enumeration type, not about the comparison.
10691   //  - If the constant is the maximum / minimum in-range value. For an
10692   //    enumeratin type, such comparisons can be meaningful and useful.
10693   if (Constant->getType()->isEnumeralType() &&
10694       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10695     return false;
10696 
10697   // TODO: Investigate using GetExprRange() to get tighter bounds
10698   // on the bit ranges.
10699   QualType OtherT = Other->getType();
10700   if (const auto *AT = OtherT->getAs<AtomicType>())
10701     OtherT = AT->getValueType();
10702   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10703 
10704   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10705   // (Namely, macOS).
10706   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10707                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10708                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10709 
10710   // Whether we're treating Other as being a bool because of the form of
10711   // expression despite it having another type (typically 'int' in C).
10712   bool OtherIsBooleanDespiteType =
10713       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10714   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10715     OtherRange = IntRange::forBoolType();
10716 
10717   // Determine the promoted range of the other type and see if a comparison of
10718   // the constant against that range is tautological.
10719   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10720                                    Value.isUnsigned());
10721   auto Cmp = OtherPromotedRange.compare(Value);
10722   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10723   if (!Result)
10724     return false;
10725 
10726   // Suppress the diagnostic for an in-range comparison if the constant comes
10727   // from a macro or enumerator. We don't want to diagnose
10728   //
10729   //   some_long_value <= INT_MAX
10730   //
10731   // when sizeof(int) == sizeof(long).
10732   bool InRange = Cmp & PromotedRange::InRangeFlag;
10733   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10734     return false;
10735 
10736   // If this is a comparison to an enum constant, include that
10737   // constant in the diagnostic.
10738   const EnumConstantDecl *ED = nullptr;
10739   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10740     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10741 
10742   // Should be enough for uint128 (39 decimal digits)
10743   SmallString<64> PrettySourceValue;
10744   llvm::raw_svector_ostream OS(PrettySourceValue);
10745   if (ED) {
10746     OS << '\'' << *ED << "' (" << Value << ")";
10747   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10748                Constant->IgnoreParenImpCasts())) {
10749     OS << (BL->getValue() ? "YES" : "NO");
10750   } else {
10751     OS << Value;
10752   }
10753 
10754   if (IsObjCSignedCharBool) {
10755     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10756                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10757                               << OS.str() << *Result);
10758     return true;
10759   }
10760 
10761   // FIXME: We use a somewhat different formatting for the in-range cases and
10762   // cases involving boolean values for historical reasons. We should pick a
10763   // consistent way of presenting these diagnostics.
10764   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10765 
10766     S.DiagRuntimeBehavior(
10767         E->getOperatorLoc(), E,
10768         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10769                          : diag::warn_tautological_bool_compare)
10770             << OS.str() << classifyConstantValue(Constant) << OtherT
10771             << OtherIsBooleanDespiteType << *Result
10772             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10773   } else {
10774     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10775                         ? (HasEnumType(OriginalOther)
10776                                ? diag::warn_unsigned_enum_always_true_comparison
10777                                : diag::warn_unsigned_always_true_comparison)
10778                         : diag::warn_tautological_constant_compare;
10779 
10780     S.Diag(E->getOperatorLoc(), Diag)
10781         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10782         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10783   }
10784 
10785   return true;
10786 }
10787 
10788 /// Analyze the operands of the given comparison.  Implements the
10789 /// fallback case from AnalyzeComparison.
10790 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10791   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10792   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10793 }
10794 
10795 /// Implements -Wsign-compare.
10796 ///
10797 /// \param E the binary operator to check for warnings
10798 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10799   // The type the comparison is being performed in.
10800   QualType T = E->getLHS()->getType();
10801 
10802   // Only analyze comparison operators where both sides have been converted to
10803   // the same type.
10804   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10805     return AnalyzeImpConvsInComparison(S, E);
10806 
10807   // Don't analyze value-dependent comparisons directly.
10808   if (E->isValueDependent())
10809     return AnalyzeImpConvsInComparison(S, E);
10810 
10811   Expr *LHS = E->getLHS();
10812   Expr *RHS = E->getRHS();
10813 
10814   if (T->isIntegralType(S.Context)) {
10815     llvm::APSInt RHSValue;
10816     llvm::APSInt LHSValue;
10817 
10818     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10819     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10820 
10821     // We don't care about expressions whose result is a constant.
10822     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10823       return AnalyzeImpConvsInComparison(S, E);
10824 
10825     // We only care about expressions where just one side is literal
10826     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10827       // Is the constant on the RHS or LHS?
10828       const bool RhsConstant = IsRHSIntegralLiteral;
10829       Expr *Const = RhsConstant ? RHS : LHS;
10830       Expr *Other = RhsConstant ? LHS : RHS;
10831       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10832 
10833       // Check whether an integer constant comparison results in a value
10834       // of 'true' or 'false'.
10835       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10836         return AnalyzeImpConvsInComparison(S, E);
10837     }
10838   }
10839 
10840   if (!T->hasUnsignedIntegerRepresentation()) {
10841     // We don't do anything special if this isn't an unsigned integral
10842     // comparison:  we're only interested in integral comparisons, and
10843     // signed comparisons only happen in cases we don't care to warn about.
10844     return AnalyzeImpConvsInComparison(S, E);
10845   }
10846 
10847   LHS = LHS->IgnoreParenImpCasts();
10848   RHS = RHS->IgnoreParenImpCasts();
10849 
10850   if (!S.getLangOpts().CPlusPlus) {
10851     // Avoid warning about comparison of integers with different signs when
10852     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10853     // the type of `E`.
10854     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10855       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10856     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10857       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10858   }
10859 
10860   // Check to see if one of the (unmodified) operands is of different
10861   // signedness.
10862   Expr *signedOperand, *unsignedOperand;
10863   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10864     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10865            "unsigned comparison between two signed integer expressions?");
10866     signedOperand = LHS;
10867     unsignedOperand = RHS;
10868   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10869     signedOperand = RHS;
10870     unsignedOperand = LHS;
10871   } else {
10872     return AnalyzeImpConvsInComparison(S, E);
10873   }
10874 
10875   // Otherwise, calculate the effective range of the signed operand.
10876   IntRange signedRange =
10877       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10878 
10879   // Go ahead and analyze implicit conversions in the operands.  Note
10880   // that we skip the implicit conversions on both sides.
10881   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10882   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10883 
10884   // If the signed range is non-negative, -Wsign-compare won't fire.
10885   if (signedRange.NonNegative)
10886     return;
10887 
10888   // For (in)equality comparisons, if the unsigned operand is a
10889   // constant which cannot collide with a overflowed signed operand,
10890   // then reinterpreting the signed operand as unsigned will not
10891   // change the result of the comparison.
10892   if (E->isEqualityOp()) {
10893     unsigned comparisonWidth = S.Context.getIntWidth(T);
10894     IntRange unsignedRange =
10895         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10896 
10897     // We should never be unable to prove that the unsigned operand is
10898     // non-negative.
10899     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10900 
10901     if (unsignedRange.Width < comparisonWidth)
10902       return;
10903   }
10904 
10905   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10906                         S.PDiag(diag::warn_mixed_sign_comparison)
10907                             << LHS->getType() << RHS->getType()
10908                             << LHS->getSourceRange() << RHS->getSourceRange());
10909 }
10910 
10911 /// Analyzes an attempt to assign the given value to a bitfield.
10912 ///
10913 /// Returns true if there was something fishy about the attempt.
10914 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10915                                       SourceLocation InitLoc) {
10916   assert(Bitfield->isBitField());
10917   if (Bitfield->isInvalidDecl())
10918     return false;
10919 
10920   // White-list bool bitfields.
10921   QualType BitfieldType = Bitfield->getType();
10922   if (BitfieldType->isBooleanType())
10923      return false;
10924 
10925   if (BitfieldType->isEnumeralType()) {
10926     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10927     // If the underlying enum type was not explicitly specified as an unsigned
10928     // type and the enum contain only positive values, MSVC++ will cause an
10929     // inconsistency by storing this as a signed type.
10930     if (S.getLangOpts().CPlusPlus11 &&
10931         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10932         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10933         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10934       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10935         << BitfieldEnumDecl->getNameAsString();
10936     }
10937   }
10938 
10939   if (Bitfield->getType()->isBooleanType())
10940     return false;
10941 
10942   // Ignore value- or type-dependent expressions.
10943   if (Bitfield->getBitWidth()->isValueDependent() ||
10944       Bitfield->getBitWidth()->isTypeDependent() ||
10945       Init->isValueDependent() ||
10946       Init->isTypeDependent())
10947     return false;
10948 
10949   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10950   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10951 
10952   Expr::EvalResult Result;
10953   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10954                                    Expr::SE_AllowSideEffects)) {
10955     // The RHS is not constant.  If the RHS has an enum type, make sure the
10956     // bitfield is wide enough to hold all the values of the enum without
10957     // truncation.
10958     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10959       EnumDecl *ED = EnumTy->getDecl();
10960       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10961 
10962       // Enum types are implicitly signed on Windows, so check if there are any
10963       // negative enumerators to see if the enum was intended to be signed or
10964       // not.
10965       bool SignedEnum = ED->getNumNegativeBits() > 0;
10966 
10967       // Check for surprising sign changes when assigning enum values to a
10968       // bitfield of different signedness.  If the bitfield is signed and we
10969       // have exactly the right number of bits to store this unsigned enum,
10970       // suggest changing the enum to an unsigned type. This typically happens
10971       // on Windows where unfixed enums always use an underlying type of 'int'.
10972       unsigned DiagID = 0;
10973       if (SignedEnum && !SignedBitfield) {
10974         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10975       } else if (SignedBitfield && !SignedEnum &&
10976                  ED->getNumPositiveBits() == FieldWidth) {
10977         DiagID = diag::warn_signed_bitfield_enum_conversion;
10978       }
10979 
10980       if (DiagID) {
10981         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10982         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10983         SourceRange TypeRange =
10984             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10985         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10986             << SignedEnum << TypeRange;
10987       }
10988 
10989       // Compute the required bitwidth. If the enum has negative values, we need
10990       // one more bit than the normal number of positive bits to represent the
10991       // sign bit.
10992       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10993                                                   ED->getNumNegativeBits())
10994                                        : ED->getNumPositiveBits();
10995 
10996       // Check the bitwidth.
10997       if (BitsNeeded > FieldWidth) {
10998         Expr *WidthExpr = Bitfield->getBitWidth();
10999         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11000             << Bitfield << ED;
11001         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11002             << BitsNeeded << ED << WidthExpr->getSourceRange();
11003       }
11004     }
11005 
11006     return false;
11007   }
11008 
11009   llvm::APSInt Value = Result.Val.getInt();
11010 
11011   unsigned OriginalWidth = Value.getBitWidth();
11012 
11013   if (!Value.isSigned() || Value.isNegative())
11014     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11015       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11016         OriginalWidth = Value.getMinSignedBits();
11017 
11018   if (OriginalWidth <= FieldWidth)
11019     return false;
11020 
11021   // Compute the value which the bitfield will contain.
11022   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11023   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11024 
11025   // Check whether the stored value is equal to the original value.
11026   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11027   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11028     return false;
11029 
11030   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11031   // therefore don't strictly fit into a signed bitfield of width 1.
11032   if (FieldWidth == 1 && Value == 1)
11033     return false;
11034 
11035   std::string PrettyValue = Value.toString(10);
11036   std::string PrettyTrunc = TruncatedValue.toString(10);
11037 
11038   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11039     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11040     << Init->getSourceRange();
11041 
11042   return true;
11043 }
11044 
11045 /// Analyze the given simple or compound assignment for warning-worthy
11046 /// operations.
11047 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11048   // Just recurse on the LHS.
11049   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11050 
11051   // We want to recurse on the RHS as normal unless we're assigning to
11052   // a bitfield.
11053   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11054     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11055                                   E->getOperatorLoc())) {
11056       // Recurse, ignoring any implicit conversions on the RHS.
11057       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11058                                         E->getOperatorLoc());
11059     }
11060   }
11061 
11062   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11063 
11064   // Diagnose implicitly sequentially-consistent atomic assignment.
11065   if (E->getLHS()->getType()->isAtomicType())
11066     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11067 }
11068 
11069 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11070 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11071                             SourceLocation CContext, unsigned diag,
11072                             bool pruneControlFlow = false) {
11073   if (pruneControlFlow) {
11074     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11075                           S.PDiag(diag)
11076                               << SourceType << T << E->getSourceRange()
11077                               << SourceRange(CContext));
11078     return;
11079   }
11080   S.Diag(E->getExprLoc(), diag)
11081     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11082 }
11083 
11084 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11085 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11086                             SourceLocation CContext,
11087                             unsigned diag, bool pruneControlFlow = false) {
11088   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11089 }
11090 
11091 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11092   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11093       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11094 }
11095 
11096 static void adornObjCBoolConversionDiagWithTernaryFixit(
11097     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11098   Expr *Ignored = SourceExpr->IgnoreImplicit();
11099   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11100     Ignored = OVE->getSourceExpr();
11101   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11102                      isa<BinaryOperator>(Ignored) ||
11103                      isa<CXXOperatorCallExpr>(Ignored);
11104   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11105   if (NeedsParens)
11106     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11107             << FixItHint::CreateInsertion(EndLoc, ")");
11108   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11109 }
11110 
11111 /// Diagnose an implicit cast from a floating point value to an integer value.
11112 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11113                                     SourceLocation CContext) {
11114   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11115   const bool PruneWarnings = S.inTemplateInstantiation();
11116 
11117   Expr *InnerE = E->IgnoreParenImpCasts();
11118   // We also want to warn on, e.g., "int i = -1.234"
11119   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11120     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11121       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11122 
11123   const bool IsLiteral =
11124       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11125 
11126   llvm::APFloat Value(0.0);
11127   bool IsConstant =
11128     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11129   if (!IsConstant) {
11130     if (isObjCSignedCharBool(S, T)) {
11131       return adornObjCBoolConversionDiagWithTernaryFixit(
11132           S, E,
11133           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11134               << E->getType());
11135     }
11136 
11137     return DiagnoseImpCast(S, E, T, CContext,
11138                            diag::warn_impcast_float_integer, PruneWarnings);
11139   }
11140 
11141   bool isExact = false;
11142 
11143   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11144                             T->hasUnsignedIntegerRepresentation());
11145   llvm::APFloat::opStatus Result = Value.convertToInteger(
11146       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11147 
11148   // FIXME: Force the precision of the source value down so we don't print
11149   // digits which are usually useless (we don't really care here if we
11150   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11151   // would automatically print the shortest representation, but it's a bit
11152   // tricky to implement.
11153   SmallString<16> PrettySourceValue;
11154   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11155   precision = (precision * 59 + 195) / 196;
11156   Value.toString(PrettySourceValue, precision);
11157 
11158   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11159     return adornObjCBoolConversionDiagWithTernaryFixit(
11160         S, E,
11161         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11162             << PrettySourceValue);
11163   }
11164 
11165   if (Result == llvm::APFloat::opOK && isExact) {
11166     if (IsLiteral) return;
11167     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11168                            PruneWarnings);
11169   }
11170 
11171   // Conversion of a floating-point value to a non-bool integer where the
11172   // integral part cannot be represented by the integer type is undefined.
11173   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11174     return DiagnoseImpCast(
11175         S, E, T, CContext,
11176         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11177                   : diag::warn_impcast_float_to_integer_out_of_range,
11178         PruneWarnings);
11179 
11180   unsigned DiagID = 0;
11181   if (IsLiteral) {
11182     // Warn on floating point literal to integer.
11183     DiagID = diag::warn_impcast_literal_float_to_integer;
11184   } else if (IntegerValue == 0) {
11185     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11186       return DiagnoseImpCast(S, E, T, CContext,
11187                              diag::warn_impcast_float_integer, PruneWarnings);
11188     }
11189     // Warn on non-zero to zero conversion.
11190     DiagID = diag::warn_impcast_float_to_integer_zero;
11191   } else {
11192     if (IntegerValue.isUnsigned()) {
11193       if (!IntegerValue.isMaxValue()) {
11194         return DiagnoseImpCast(S, E, T, CContext,
11195                                diag::warn_impcast_float_integer, PruneWarnings);
11196       }
11197     } else {  // IntegerValue.isSigned()
11198       if (!IntegerValue.isMaxSignedValue() &&
11199           !IntegerValue.isMinSignedValue()) {
11200         return DiagnoseImpCast(S, E, T, CContext,
11201                                diag::warn_impcast_float_integer, PruneWarnings);
11202       }
11203     }
11204     // Warn on evaluatable floating point expression to integer conversion.
11205     DiagID = diag::warn_impcast_float_to_integer;
11206   }
11207 
11208   SmallString<16> PrettyTargetValue;
11209   if (IsBool)
11210     PrettyTargetValue = Value.isZero() ? "false" : "true";
11211   else
11212     IntegerValue.toString(PrettyTargetValue);
11213 
11214   if (PruneWarnings) {
11215     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11216                           S.PDiag(DiagID)
11217                               << E->getType() << T.getUnqualifiedType()
11218                               << PrettySourceValue << PrettyTargetValue
11219                               << E->getSourceRange() << SourceRange(CContext));
11220   } else {
11221     S.Diag(E->getExprLoc(), DiagID)
11222         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11223         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11224   }
11225 }
11226 
11227 /// Analyze the given compound assignment for the possible losing of
11228 /// floating-point precision.
11229 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11230   assert(isa<CompoundAssignOperator>(E) &&
11231          "Must be compound assignment operation");
11232   // Recurse on the LHS and RHS in here
11233   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11234   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11235 
11236   if (E->getLHS()->getType()->isAtomicType())
11237     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11238 
11239   // Now check the outermost expression
11240   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11241   const auto *RBT = cast<CompoundAssignOperator>(E)
11242                         ->getComputationResultType()
11243                         ->getAs<BuiltinType>();
11244 
11245   // The below checks assume source is floating point.
11246   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11247 
11248   // If source is floating point but target is an integer.
11249   if (ResultBT->isInteger())
11250     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11251                            E->getExprLoc(), diag::warn_impcast_float_integer);
11252 
11253   if (!ResultBT->isFloatingPoint())
11254     return;
11255 
11256   // If both source and target are floating points, warn about losing precision.
11257   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11258       QualType(ResultBT, 0), QualType(RBT, 0));
11259   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11260     // warn about dropping FP rank.
11261     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11262                     diag::warn_impcast_float_result_precision);
11263 }
11264 
11265 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11266                                       IntRange Range) {
11267   if (!Range.Width) return "0";
11268 
11269   llvm::APSInt ValueInRange = Value;
11270   ValueInRange.setIsSigned(!Range.NonNegative);
11271   ValueInRange = ValueInRange.trunc(Range.Width);
11272   return ValueInRange.toString(10);
11273 }
11274 
11275 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11276   if (!isa<ImplicitCastExpr>(Ex))
11277     return false;
11278 
11279   Expr *InnerE = Ex->IgnoreParenImpCasts();
11280   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11281   const Type *Source =
11282     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11283   if (Target->isDependentType())
11284     return false;
11285 
11286   const BuiltinType *FloatCandidateBT =
11287     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11288   const Type *BoolCandidateType = ToBool ? Target : Source;
11289 
11290   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11291           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11292 }
11293 
11294 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11295                                              SourceLocation CC) {
11296   unsigned NumArgs = TheCall->getNumArgs();
11297   for (unsigned i = 0; i < NumArgs; ++i) {
11298     Expr *CurrA = TheCall->getArg(i);
11299     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11300       continue;
11301 
11302     bool IsSwapped = ((i > 0) &&
11303         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11304     IsSwapped |= ((i < (NumArgs - 1)) &&
11305         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11306     if (IsSwapped) {
11307       // Warn on this floating-point to bool conversion.
11308       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11309                       CurrA->getType(), CC,
11310                       diag::warn_impcast_floating_point_to_bool);
11311     }
11312   }
11313 }
11314 
11315 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11316                                    SourceLocation CC) {
11317   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11318                         E->getExprLoc()))
11319     return;
11320 
11321   // Don't warn on functions which have return type nullptr_t.
11322   if (isa<CallExpr>(E))
11323     return;
11324 
11325   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11326   const Expr::NullPointerConstantKind NullKind =
11327       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11328   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11329     return;
11330 
11331   // Return if target type is a safe conversion.
11332   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11333       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11334     return;
11335 
11336   SourceLocation Loc = E->getSourceRange().getBegin();
11337 
11338   // Venture through the macro stacks to get to the source of macro arguments.
11339   // The new location is a better location than the complete location that was
11340   // passed in.
11341   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11342   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11343 
11344   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11345   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11346     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11347         Loc, S.SourceMgr, S.getLangOpts());
11348     if (MacroName == "NULL")
11349       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11350   }
11351 
11352   // Only warn if the null and context location are in the same macro expansion.
11353   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11354     return;
11355 
11356   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11357       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11358       << FixItHint::CreateReplacement(Loc,
11359                                       S.getFixItZeroLiteralForType(T, Loc));
11360 }
11361 
11362 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11363                                   ObjCArrayLiteral *ArrayLiteral);
11364 
11365 static void
11366 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11367                            ObjCDictionaryLiteral *DictionaryLiteral);
11368 
11369 /// Check a single element within a collection literal against the
11370 /// target element type.
11371 static void checkObjCCollectionLiteralElement(Sema &S,
11372                                               QualType TargetElementType,
11373                                               Expr *Element,
11374                                               unsigned ElementKind) {
11375   // Skip a bitcast to 'id' or qualified 'id'.
11376   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11377     if (ICE->getCastKind() == CK_BitCast &&
11378         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11379       Element = ICE->getSubExpr();
11380   }
11381 
11382   QualType ElementType = Element->getType();
11383   ExprResult ElementResult(Element);
11384   if (ElementType->getAs<ObjCObjectPointerType>() &&
11385       S.CheckSingleAssignmentConstraints(TargetElementType,
11386                                          ElementResult,
11387                                          false, false)
11388         != Sema::Compatible) {
11389     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11390         << ElementType << ElementKind << TargetElementType
11391         << Element->getSourceRange();
11392   }
11393 
11394   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11395     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11396   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11397     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11398 }
11399 
11400 /// Check an Objective-C array literal being converted to the given
11401 /// target type.
11402 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11403                                   ObjCArrayLiteral *ArrayLiteral) {
11404   if (!S.NSArrayDecl)
11405     return;
11406 
11407   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11408   if (!TargetObjCPtr)
11409     return;
11410 
11411   if (TargetObjCPtr->isUnspecialized() ||
11412       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11413         != S.NSArrayDecl->getCanonicalDecl())
11414     return;
11415 
11416   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11417   if (TypeArgs.size() != 1)
11418     return;
11419 
11420   QualType TargetElementType = TypeArgs[0];
11421   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11422     checkObjCCollectionLiteralElement(S, TargetElementType,
11423                                       ArrayLiteral->getElement(I),
11424                                       0);
11425   }
11426 }
11427 
11428 /// Check an Objective-C dictionary literal being converted to the given
11429 /// target type.
11430 static void
11431 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11432                            ObjCDictionaryLiteral *DictionaryLiteral) {
11433   if (!S.NSDictionaryDecl)
11434     return;
11435 
11436   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11437   if (!TargetObjCPtr)
11438     return;
11439 
11440   if (TargetObjCPtr->isUnspecialized() ||
11441       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11442         != S.NSDictionaryDecl->getCanonicalDecl())
11443     return;
11444 
11445   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11446   if (TypeArgs.size() != 2)
11447     return;
11448 
11449   QualType TargetKeyType = TypeArgs[0];
11450   QualType TargetObjectType = TypeArgs[1];
11451   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11452     auto Element = DictionaryLiteral->getKeyValueElement(I);
11453     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11454     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11455   }
11456 }
11457 
11458 // Helper function to filter out cases for constant width constant conversion.
11459 // Don't warn on char array initialization or for non-decimal values.
11460 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11461                                           SourceLocation CC) {
11462   // If initializing from a constant, and the constant starts with '0',
11463   // then it is a binary, octal, or hexadecimal.  Allow these constants
11464   // to fill all the bits, even if there is a sign change.
11465   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11466     const char FirstLiteralCharacter =
11467         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11468     if (FirstLiteralCharacter == '0')
11469       return false;
11470   }
11471 
11472   // If the CC location points to a '{', and the type is char, then assume
11473   // assume it is an array initialization.
11474   if (CC.isValid() && T->isCharType()) {
11475     const char FirstContextCharacter =
11476         S.getSourceManager().getCharacterData(CC)[0];
11477     if (FirstContextCharacter == '{')
11478       return false;
11479   }
11480 
11481   return true;
11482 }
11483 
11484 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11485   const auto *IL = dyn_cast<IntegerLiteral>(E);
11486   if (!IL) {
11487     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11488       if (UO->getOpcode() == UO_Minus)
11489         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11490     }
11491   }
11492 
11493   return IL;
11494 }
11495 
11496 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11497   E = E->IgnoreParenImpCasts();
11498   SourceLocation ExprLoc = E->getExprLoc();
11499 
11500   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11501     BinaryOperator::Opcode Opc = BO->getOpcode();
11502     Expr::EvalResult Result;
11503     // Do not diagnose unsigned shifts.
11504     if (Opc == BO_Shl) {
11505       const auto *LHS = getIntegerLiteral(BO->getLHS());
11506       const auto *RHS = getIntegerLiteral(BO->getRHS());
11507       if (LHS && LHS->getValue() == 0)
11508         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11509       else if (!E->isValueDependent() && LHS && RHS &&
11510                RHS->getValue().isNonNegative() &&
11511                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11512         S.Diag(ExprLoc, diag::warn_left_shift_always)
11513             << (Result.Val.getInt() != 0);
11514       else if (E->getType()->isSignedIntegerType())
11515         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11516     }
11517   }
11518 
11519   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11520     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11521     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11522     if (!LHS || !RHS)
11523       return;
11524     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11525         (RHS->getValue() == 0 || RHS->getValue() == 1))
11526       // Do not diagnose common idioms.
11527       return;
11528     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11529       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11530   }
11531 }
11532 
11533 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11534                                     SourceLocation CC,
11535                                     bool *ICContext = nullptr,
11536                                     bool IsListInit = false) {
11537   if (E->isTypeDependent() || E->isValueDependent()) return;
11538 
11539   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11540   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11541   if (Source == Target) return;
11542   if (Target->isDependentType()) return;
11543 
11544   // If the conversion context location is invalid don't complain. We also
11545   // don't want to emit a warning if the issue occurs from the expansion of
11546   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11547   // delay this check as long as possible. Once we detect we are in that
11548   // scenario, we just return.
11549   if (CC.isInvalid())
11550     return;
11551 
11552   if (Source->isAtomicType())
11553     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11554 
11555   // Diagnose implicit casts to bool.
11556   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11557     if (isa<StringLiteral>(E))
11558       // Warn on string literal to bool.  Checks for string literals in logical
11559       // and expressions, for instance, assert(0 && "error here"), are
11560       // prevented by a check in AnalyzeImplicitConversions().
11561       return DiagnoseImpCast(S, E, T, CC,
11562                              diag::warn_impcast_string_literal_to_bool);
11563     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11564         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11565       // This covers the literal expressions that evaluate to Objective-C
11566       // objects.
11567       return DiagnoseImpCast(S, E, T, CC,
11568                              diag::warn_impcast_objective_c_literal_to_bool);
11569     }
11570     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11571       // Warn on pointer to bool conversion that is always true.
11572       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11573                                      SourceRange(CC));
11574     }
11575   }
11576 
11577   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11578   // is a typedef for signed char (macOS), then that constant value has to be 1
11579   // or 0.
11580   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11581     Expr::EvalResult Result;
11582     if (E->EvaluateAsInt(Result, S.getASTContext(),
11583                          Expr::SE_AllowSideEffects)) {
11584       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11585         adornObjCBoolConversionDiagWithTernaryFixit(
11586             S, E,
11587             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11588                 << Result.Val.getInt().toString(10));
11589       }
11590       return;
11591     }
11592   }
11593 
11594   // Check implicit casts from Objective-C collection literals to specialized
11595   // collection types, e.g., NSArray<NSString *> *.
11596   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11597     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11598   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11599     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11600 
11601   // Strip vector types.
11602   if (isa<VectorType>(Source)) {
11603     if (!isa<VectorType>(Target)) {
11604       if (S.SourceMgr.isInSystemMacro(CC))
11605         return;
11606       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11607     }
11608 
11609     // If the vector cast is cast between two vectors of the same size, it is
11610     // a bitcast, not a conversion.
11611     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11612       return;
11613 
11614     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11615     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11616   }
11617   if (auto VecTy = dyn_cast<VectorType>(Target))
11618     Target = VecTy->getElementType().getTypePtr();
11619 
11620   // Strip complex types.
11621   if (isa<ComplexType>(Source)) {
11622     if (!isa<ComplexType>(Target)) {
11623       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11624         return;
11625 
11626       return DiagnoseImpCast(S, E, T, CC,
11627                              S.getLangOpts().CPlusPlus
11628                                  ? diag::err_impcast_complex_scalar
11629                                  : diag::warn_impcast_complex_scalar);
11630     }
11631 
11632     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11633     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11634   }
11635 
11636   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11637   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11638 
11639   // If the source is floating point...
11640   if (SourceBT && SourceBT->isFloatingPoint()) {
11641     // ...and the target is floating point...
11642     if (TargetBT && TargetBT->isFloatingPoint()) {
11643       // ...then warn if we're dropping FP rank.
11644 
11645       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11646           QualType(SourceBT, 0), QualType(TargetBT, 0));
11647       if (Order > 0) {
11648         // Don't warn about float constants that are precisely
11649         // representable in the target type.
11650         Expr::EvalResult result;
11651         if (E->EvaluateAsRValue(result, S.Context)) {
11652           // Value might be a float, a float vector, or a float complex.
11653           if (IsSameFloatAfterCast(result.Val,
11654                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11655                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11656             return;
11657         }
11658 
11659         if (S.SourceMgr.isInSystemMacro(CC))
11660           return;
11661 
11662         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11663       }
11664       // ... or possibly if we're increasing rank, too
11665       else if (Order < 0) {
11666         if (S.SourceMgr.isInSystemMacro(CC))
11667           return;
11668 
11669         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11670       }
11671       return;
11672     }
11673 
11674     // If the target is integral, always warn.
11675     if (TargetBT && TargetBT->isInteger()) {
11676       if (S.SourceMgr.isInSystemMacro(CC))
11677         return;
11678 
11679       DiagnoseFloatingImpCast(S, E, T, CC);
11680     }
11681 
11682     // Detect the case where a call result is converted from floating-point to
11683     // to bool, and the final argument to the call is converted from bool, to
11684     // discover this typo:
11685     //
11686     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11687     //
11688     // FIXME: This is an incredibly special case; is there some more general
11689     // way to detect this class of misplaced-parentheses bug?
11690     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11691       // Check last argument of function call to see if it is an
11692       // implicit cast from a type matching the type the result
11693       // is being cast to.
11694       CallExpr *CEx = cast<CallExpr>(E);
11695       if (unsigned NumArgs = CEx->getNumArgs()) {
11696         Expr *LastA = CEx->getArg(NumArgs - 1);
11697         Expr *InnerE = LastA->IgnoreParenImpCasts();
11698         if (isa<ImplicitCastExpr>(LastA) &&
11699             InnerE->getType()->isBooleanType()) {
11700           // Warn on this floating-point to bool conversion
11701           DiagnoseImpCast(S, E, T, CC,
11702                           diag::warn_impcast_floating_point_to_bool);
11703         }
11704       }
11705     }
11706     return;
11707   }
11708 
11709   // Valid casts involving fixed point types should be accounted for here.
11710   if (Source->isFixedPointType()) {
11711     if (Target->isUnsaturatedFixedPointType()) {
11712       Expr::EvalResult Result;
11713       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11714                                   S.isConstantEvaluated())) {
11715         APFixedPoint Value = Result.Val.getFixedPoint();
11716         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11717         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11718         if (Value > MaxVal || Value < MinVal) {
11719           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11720                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11721                                     << Value.toString() << T
11722                                     << E->getSourceRange()
11723                                     << clang::SourceRange(CC));
11724           return;
11725         }
11726       }
11727     } else if (Target->isIntegerType()) {
11728       Expr::EvalResult Result;
11729       if (!S.isConstantEvaluated() &&
11730           E->EvaluateAsFixedPoint(Result, S.Context,
11731                                   Expr::SE_AllowSideEffects)) {
11732         APFixedPoint FXResult = Result.Val.getFixedPoint();
11733 
11734         bool Overflowed;
11735         llvm::APSInt IntResult = FXResult.convertToInt(
11736             S.Context.getIntWidth(T),
11737             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11738 
11739         if (Overflowed) {
11740           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11741                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11742                                     << FXResult.toString() << T
11743                                     << E->getSourceRange()
11744                                     << clang::SourceRange(CC));
11745           return;
11746         }
11747       }
11748     }
11749   } else if (Target->isUnsaturatedFixedPointType()) {
11750     if (Source->isIntegerType()) {
11751       Expr::EvalResult Result;
11752       if (!S.isConstantEvaluated() &&
11753           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11754         llvm::APSInt Value = Result.Val.getInt();
11755 
11756         bool Overflowed;
11757         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11758             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11759 
11760         if (Overflowed) {
11761           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11762                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11763                                     << Value.toString(/*Radix=*/10) << T
11764                                     << E->getSourceRange()
11765                                     << clang::SourceRange(CC));
11766           return;
11767         }
11768       }
11769     }
11770   }
11771 
11772   // If we are casting an integer type to a floating point type without
11773   // initialization-list syntax, we might lose accuracy if the floating
11774   // point type has a narrower significand than the integer type.
11775   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11776       TargetBT->isFloatingType() && !IsListInit) {
11777     // Determine the number of precision bits in the source integer type.
11778     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11779     unsigned int SourcePrecision = SourceRange.Width;
11780 
11781     // Determine the number of precision bits in the
11782     // target floating point type.
11783     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11784         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11785 
11786     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11787         SourcePrecision > TargetPrecision) {
11788 
11789       llvm::APSInt SourceInt;
11790       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11791         // If the source integer is a constant, convert it to the target
11792         // floating point type. Issue a warning if the value changes
11793         // during the whole conversion.
11794         llvm::APFloat TargetFloatValue(
11795             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11796         llvm::APFloat::opStatus ConversionStatus =
11797             TargetFloatValue.convertFromAPInt(
11798                 SourceInt, SourceBT->isSignedInteger(),
11799                 llvm::APFloat::rmNearestTiesToEven);
11800 
11801         if (ConversionStatus != llvm::APFloat::opOK) {
11802           std::string PrettySourceValue = SourceInt.toString(10);
11803           SmallString<32> PrettyTargetValue;
11804           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11805 
11806           S.DiagRuntimeBehavior(
11807               E->getExprLoc(), E,
11808               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11809                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11810                   << E->getSourceRange() << clang::SourceRange(CC));
11811         }
11812       } else {
11813         // Otherwise, the implicit conversion may lose precision.
11814         DiagnoseImpCast(S, E, T, CC,
11815                         diag::warn_impcast_integer_float_precision);
11816       }
11817     }
11818   }
11819 
11820   DiagnoseNullConversion(S, E, T, CC);
11821 
11822   S.DiscardMisalignedMemberAddress(Target, E);
11823 
11824   if (Target->isBooleanType())
11825     DiagnoseIntInBoolContext(S, E);
11826 
11827   if (!Source->isIntegerType() || !Target->isIntegerType())
11828     return;
11829 
11830   // TODO: remove this early return once the false positives for constant->bool
11831   // in templates, macros, etc, are reduced or removed.
11832   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11833     return;
11834 
11835   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11836       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11837     return adornObjCBoolConversionDiagWithTernaryFixit(
11838         S, E,
11839         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11840             << E->getType());
11841   }
11842 
11843   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11844   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11845 
11846   if (SourceRange.Width > TargetRange.Width) {
11847     // If the source is a constant, use a default-on diagnostic.
11848     // TODO: this should happen for bitfield stores, too.
11849     Expr::EvalResult Result;
11850     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11851                          S.isConstantEvaluated())) {
11852       llvm::APSInt Value(32);
11853       Value = Result.Val.getInt();
11854 
11855       if (S.SourceMgr.isInSystemMacro(CC))
11856         return;
11857 
11858       std::string PrettySourceValue = Value.toString(10);
11859       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11860 
11861       S.DiagRuntimeBehavior(
11862           E->getExprLoc(), E,
11863           S.PDiag(diag::warn_impcast_integer_precision_constant)
11864               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11865               << E->getSourceRange() << clang::SourceRange(CC));
11866       return;
11867     }
11868 
11869     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11870     if (S.SourceMgr.isInSystemMacro(CC))
11871       return;
11872 
11873     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11874       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11875                              /* pruneControlFlow */ true);
11876     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11877   }
11878 
11879   if (TargetRange.Width > SourceRange.Width) {
11880     if (auto *UO = dyn_cast<UnaryOperator>(E))
11881       if (UO->getOpcode() == UO_Minus)
11882         if (Source->isUnsignedIntegerType()) {
11883           if (Target->isUnsignedIntegerType())
11884             return DiagnoseImpCast(S, E, T, CC,
11885                                    diag::warn_impcast_high_order_zero_bits);
11886           if (Target->isSignedIntegerType())
11887             return DiagnoseImpCast(S, E, T, CC,
11888                                    diag::warn_impcast_nonnegative_result);
11889         }
11890   }
11891 
11892   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11893       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11894     // Warn when doing a signed to signed conversion, warn if the positive
11895     // source value is exactly the width of the target type, which will
11896     // cause a negative value to be stored.
11897 
11898     Expr::EvalResult Result;
11899     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11900         !S.SourceMgr.isInSystemMacro(CC)) {
11901       llvm::APSInt Value = Result.Val.getInt();
11902       if (isSameWidthConstantConversion(S, E, T, CC)) {
11903         std::string PrettySourceValue = Value.toString(10);
11904         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11905 
11906         S.DiagRuntimeBehavior(
11907             E->getExprLoc(), E,
11908             S.PDiag(diag::warn_impcast_integer_precision_constant)
11909                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11910                 << E->getSourceRange() << clang::SourceRange(CC));
11911         return;
11912       }
11913     }
11914 
11915     // Fall through for non-constants to give a sign conversion warning.
11916   }
11917 
11918   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11919       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11920        SourceRange.Width == TargetRange.Width)) {
11921     if (S.SourceMgr.isInSystemMacro(CC))
11922       return;
11923 
11924     unsigned DiagID = diag::warn_impcast_integer_sign;
11925 
11926     // Traditionally, gcc has warned about this under -Wsign-compare.
11927     // We also want to warn about it in -Wconversion.
11928     // So if -Wconversion is off, use a completely identical diagnostic
11929     // in the sign-compare group.
11930     // The conditional-checking code will
11931     if (ICContext) {
11932       DiagID = diag::warn_impcast_integer_sign_conditional;
11933       *ICContext = true;
11934     }
11935 
11936     return DiagnoseImpCast(S, E, T, CC, DiagID);
11937   }
11938 
11939   // Diagnose conversions between different enumeration types.
11940   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11941   // type, to give us better diagnostics.
11942   QualType SourceType = E->getType();
11943   if (!S.getLangOpts().CPlusPlus) {
11944     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11945       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11946         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11947         SourceType = S.Context.getTypeDeclType(Enum);
11948         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11949       }
11950   }
11951 
11952   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11953     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11954       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11955           TargetEnum->getDecl()->hasNameForLinkage() &&
11956           SourceEnum != TargetEnum) {
11957         if (S.SourceMgr.isInSystemMacro(CC))
11958           return;
11959 
11960         return DiagnoseImpCast(S, E, SourceType, T, CC,
11961                                diag::warn_impcast_different_enum_types);
11962       }
11963 }
11964 
11965 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
11966                                      SourceLocation CC, QualType T);
11967 
11968 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11969                                     SourceLocation CC, bool &ICContext) {
11970   E = E->IgnoreParenImpCasts();
11971 
11972   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
11973     return CheckConditionalOperator(S, CO, CC, T);
11974 
11975   AnalyzeImplicitConversions(S, E, CC);
11976   if (E->getType() != T)
11977     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11978 }
11979 
11980 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
11981                                      SourceLocation CC, QualType T) {
11982   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11983 
11984   Expr *TrueExpr = E->getTrueExpr();
11985   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
11986     TrueExpr = BCO->getCommon();
11987 
11988   bool Suspicious = false;
11989   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
11990   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11991 
11992   if (T->isBooleanType())
11993     DiagnoseIntInBoolContext(S, E);
11994 
11995   // If -Wconversion would have warned about either of the candidates
11996   // for a signedness conversion to the context type...
11997   if (!Suspicious) return;
11998 
11999   // ...but it's currently ignored...
12000   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12001     return;
12002 
12003   // ...then check whether it would have warned about either of the
12004   // candidates for a signedness conversion to the condition type.
12005   if (E->getType() == T) return;
12006 
12007   Suspicious = false;
12008   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12009                           E->getType(), CC, &Suspicious);
12010   if (!Suspicious)
12011     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12012                             E->getType(), CC, &Suspicious);
12013 }
12014 
12015 /// Check conversion of given expression to boolean.
12016 /// Input argument E is a logical expression.
12017 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12018   if (S.getLangOpts().Bool)
12019     return;
12020   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12021     return;
12022   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12023 }
12024 
12025 namespace {
12026 struct AnalyzeImplicitConversionsWorkItem {
12027   Expr *E;
12028   SourceLocation CC;
12029   bool IsListInit;
12030 };
12031 }
12032 
12033 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12034 /// that should be visited are added to WorkList.
12035 static void AnalyzeImplicitConversions(
12036     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12037     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12038   Expr *OrigE = Item.E;
12039   SourceLocation CC = Item.CC;
12040 
12041   QualType T = OrigE->getType();
12042   Expr *E = OrigE->IgnoreParenImpCasts();
12043 
12044   // Propagate whether we are in a C++ list initialization expression.
12045   // If so, we do not issue warnings for implicit int-float conversion
12046   // precision loss, because C++11 narrowing already handles it.
12047   bool IsListInit = Item.IsListInit ||
12048                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12049 
12050   if (E->isTypeDependent() || E->isValueDependent())
12051     return;
12052 
12053   Expr *SourceExpr = E;
12054   // Examine, but don't traverse into the source expression of an
12055   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12056   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12057   // evaluate it in the context of checking the specific conversion to T though.
12058   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12059     if (auto *Src = OVE->getSourceExpr())
12060       SourceExpr = Src;
12061 
12062   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12063     if (UO->getOpcode() == UO_Not &&
12064         UO->getSubExpr()->isKnownToHaveBooleanValue())
12065       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12066           << OrigE->getSourceRange() << T->isBooleanType()
12067           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12068 
12069   // For conditional operators, we analyze the arguments as if they
12070   // were being fed directly into the output.
12071   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12072     CheckConditionalOperator(S, CO, CC, T);
12073     return;
12074   }
12075 
12076   // Check implicit argument conversions for function calls.
12077   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12078     CheckImplicitArgumentConversions(S, Call, CC);
12079 
12080   // Go ahead and check any implicit conversions we might have skipped.
12081   // The non-canonical typecheck is just an optimization;
12082   // CheckImplicitConversion will filter out dead implicit conversions.
12083   if (SourceExpr->getType() != T)
12084     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12085 
12086   // Now continue drilling into this expression.
12087 
12088   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12089     // The bound subexpressions in a PseudoObjectExpr are not reachable
12090     // as transitive children.
12091     // FIXME: Use a more uniform representation for this.
12092     for (auto *SE : POE->semantics())
12093       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12094         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12095   }
12096 
12097   // Skip past explicit casts.
12098   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12099     E = CE->getSubExpr()->IgnoreParenImpCasts();
12100     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12101       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12102     WorkList.push_back({E, CC, IsListInit});
12103     return;
12104   }
12105 
12106   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12107     // Do a somewhat different check with comparison operators.
12108     if (BO->isComparisonOp())
12109       return AnalyzeComparison(S, BO);
12110 
12111     // And with simple assignments.
12112     if (BO->getOpcode() == BO_Assign)
12113       return AnalyzeAssignment(S, BO);
12114     // And with compound assignments.
12115     if (BO->isAssignmentOp())
12116       return AnalyzeCompoundAssignment(S, BO);
12117   }
12118 
12119   // These break the otherwise-useful invariant below.  Fortunately,
12120   // we don't really need to recurse into them, because any internal
12121   // expressions should have been analyzed already when they were
12122   // built into statements.
12123   if (isa<StmtExpr>(E)) return;
12124 
12125   // Don't descend into unevaluated contexts.
12126   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12127 
12128   // Now just recurse over the expression's children.
12129   CC = E->getExprLoc();
12130   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12131   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12132   for (Stmt *SubStmt : E->children()) {
12133     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12134     if (!ChildExpr)
12135       continue;
12136 
12137     if (IsLogicalAndOperator &&
12138         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12139       // Ignore checking string literals that are in logical and operators.
12140       // This is a common pattern for asserts.
12141       continue;
12142     WorkList.push_back({ChildExpr, CC, IsListInit});
12143   }
12144 
12145   if (BO && BO->isLogicalOp()) {
12146     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12147     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12148       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12149 
12150     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12151     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12152       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12153   }
12154 
12155   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12156     if (U->getOpcode() == UO_LNot) {
12157       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12158     } else if (U->getOpcode() != UO_AddrOf) {
12159       if (U->getSubExpr()->getType()->isAtomicType())
12160         S.Diag(U->getSubExpr()->getBeginLoc(),
12161                diag::warn_atomic_implicit_seq_cst);
12162     }
12163   }
12164 }
12165 
12166 /// AnalyzeImplicitConversions - Find and report any interesting
12167 /// implicit conversions in the given expression.  There are a couple
12168 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12169 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12170                                        bool IsListInit/*= false*/) {
12171   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12172   WorkList.push_back({OrigE, CC, IsListInit});
12173   while (!WorkList.empty())
12174     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12175 }
12176 
12177 /// Diagnose integer type and any valid implicit conversion to it.
12178 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12179   // Taking into account implicit conversions,
12180   // allow any integer.
12181   if (!E->getType()->isIntegerType()) {
12182     S.Diag(E->getBeginLoc(),
12183            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12184     return true;
12185   }
12186   // Potentially emit standard warnings for implicit conversions if enabled
12187   // using -Wconversion.
12188   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12189   return false;
12190 }
12191 
12192 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12193 // Returns true when emitting a warning about taking the address of a reference.
12194 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12195                               const PartialDiagnostic &PD) {
12196   E = E->IgnoreParenImpCasts();
12197 
12198   const FunctionDecl *FD = nullptr;
12199 
12200   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12201     if (!DRE->getDecl()->getType()->isReferenceType())
12202       return false;
12203   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12204     if (!M->getMemberDecl()->getType()->isReferenceType())
12205       return false;
12206   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12207     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12208       return false;
12209     FD = Call->getDirectCallee();
12210   } else {
12211     return false;
12212   }
12213 
12214   SemaRef.Diag(E->getExprLoc(), PD);
12215 
12216   // If possible, point to location of function.
12217   if (FD) {
12218     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12219   }
12220 
12221   return true;
12222 }
12223 
12224 // Returns true if the SourceLocation is expanded from any macro body.
12225 // Returns false if the SourceLocation is invalid, is from not in a macro
12226 // expansion, or is from expanded from a top-level macro argument.
12227 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12228   if (Loc.isInvalid())
12229     return false;
12230 
12231   while (Loc.isMacroID()) {
12232     if (SM.isMacroBodyExpansion(Loc))
12233       return true;
12234     Loc = SM.getImmediateMacroCallerLoc(Loc);
12235   }
12236 
12237   return false;
12238 }
12239 
12240 /// Diagnose pointers that are always non-null.
12241 /// \param E the expression containing the pointer
12242 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12243 /// compared to a null pointer
12244 /// \param IsEqual True when the comparison is equal to a null pointer
12245 /// \param Range Extra SourceRange to highlight in the diagnostic
12246 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12247                                         Expr::NullPointerConstantKind NullKind,
12248                                         bool IsEqual, SourceRange Range) {
12249   if (!E)
12250     return;
12251 
12252   // Don't warn inside macros.
12253   if (E->getExprLoc().isMacroID()) {
12254     const SourceManager &SM = getSourceManager();
12255     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12256         IsInAnyMacroBody(SM, Range.getBegin()))
12257       return;
12258   }
12259   E = E->IgnoreImpCasts();
12260 
12261   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12262 
12263   if (isa<CXXThisExpr>(E)) {
12264     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12265                                 : diag::warn_this_bool_conversion;
12266     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12267     return;
12268   }
12269 
12270   bool IsAddressOf = false;
12271 
12272   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12273     if (UO->getOpcode() != UO_AddrOf)
12274       return;
12275     IsAddressOf = true;
12276     E = UO->getSubExpr();
12277   }
12278 
12279   if (IsAddressOf) {
12280     unsigned DiagID = IsCompare
12281                           ? diag::warn_address_of_reference_null_compare
12282                           : diag::warn_address_of_reference_bool_conversion;
12283     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12284                                          << IsEqual;
12285     if (CheckForReference(*this, E, PD)) {
12286       return;
12287     }
12288   }
12289 
12290   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12291     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12292     std::string Str;
12293     llvm::raw_string_ostream S(Str);
12294     E->printPretty(S, nullptr, getPrintingPolicy());
12295     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12296                                 : diag::warn_cast_nonnull_to_bool;
12297     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12298       << E->getSourceRange() << Range << IsEqual;
12299     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12300   };
12301 
12302   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12303   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12304     if (auto *Callee = Call->getDirectCallee()) {
12305       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12306         ComplainAboutNonnullParamOrCall(A);
12307         return;
12308       }
12309     }
12310   }
12311 
12312   // Expect to find a single Decl.  Skip anything more complicated.
12313   ValueDecl *D = nullptr;
12314   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12315     D = R->getDecl();
12316   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12317     D = M->getMemberDecl();
12318   }
12319 
12320   // Weak Decls can be null.
12321   if (!D || D->isWeak())
12322     return;
12323 
12324   // Check for parameter decl with nonnull attribute
12325   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12326     if (getCurFunction() &&
12327         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12328       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12329         ComplainAboutNonnullParamOrCall(A);
12330         return;
12331       }
12332 
12333       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12334         // Skip function template not specialized yet.
12335         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12336           return;
12337         auto ParamIter = llvm::find(FD->parameters(), PV);
12338         assert(ParamIter != FD->param_end());
12339         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12340 
12341         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12342           if (!NonNull->args_size()) {
12343               ComplainAboutNonnullParamOrCall(NonNull);
12344               return;
12345           }
12346 
12347           for (const ParamIdx &ArgNo : NonNull->args()) {
12348             if (ArgNo.getASTIndex() == ParamNo) {
12349               ComplainAboutNonnullParamOrCall(NonNull);
12350               return;
12351             }
12352           }
12353         }
12354       }
12355     }
12356   }
12357 
12358   QualType T = D->getType();
12359   const bool IsArray = T->isArrayType();
12360   const bool IsFunction = T->isFunctionType();
12361 
12362   // Address of function is used to silence the function warning.
12363   if (IsAddressOf && IsFunction) {
12364     return;
12365   }
12366 
12367   // Found nothing.
12368   if (!IsAddressOf && !IsFunction && !IsArray)
12369     return;
12370 
12371   // Pretty print the expression for the diagnostic.
12372   std::string Str;
12373   llvm::raw_string_ostream S(Str);
12374   E->printPretty(S, nullptr, getPrintingPolicy());
12375 
12376   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12377                               : diag::warn_impcast_pointer_to_bool;
12378   enum {
12379     AddressOf,
12380     FunctionPointer,
12381     ArrayPointer
12382   } DiagType;
12383   if (IsAddressOf)
12384     DiagType = AddressOf;
12385   else if (IsFunction)
12386     DiagType = FunctionPointer;
12387   else if (IsArray)
12388     DiagType = ArrayPointer;
12389   else
12390     llvm_unreachable("Could not determine diagnostic.");
12391   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12392                                 << Range << IsEqual;
12393 
12394   if (!IsFunction)
12395     return;
12396 
12397   // Suggest '&' to silence the function warning.
12398   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12399       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12400 
12401   // Check to see if '()' fixit should be emitted.
12402   QualType ReturnType;
12403   UnresolvedSet<4> NonTemplateOverloads;
12404   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12405   if (ReturnType.isNull())
12406     return;
12407 
12408   if (IsCompare) {
12409     // There are two cases here.  If there is null constant, the only suggest
12410     // for a pointer return type.  If the null is 0, then suggest if the return
12411     // type is a pointer or an integer type.
12412     if (!ReturnType->isPointerType()) {
12413       if (NullKind == Expr::NPCK_ZeroExpression ||
12414           NullKind == Expr::NPCK_ZeroLiteral) {
12415         if (!ReturnType->isIntegerType())
12416           return;
12417       } else {
12418         return;
12419       }
12420     }
12421   } else { // !IsCompare
12422     // For function to bool, only suggest if the function pointer has bool
12423     // return type.
12424     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12425       return;
12426   }
12427   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12428       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12429 }
12430 
12431 /// Diagnoses "dangerous" implicit conversions within the given
12432 /// expression (which is a full expression).  Implements -Wconversion
12433 /// and -Wsign-compare.
12434 ///
12435 /// \param CC the "context" location of the implicit conversion, i.e.
12436 ///   the most location of the syntactic entity requiring the implicit
12437 ///   conversion
12438 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12439   // Don't diagnose in unevaluated contexts.
12440   if (isUnevaluatedContext())
12441     return;
12442 
12443   // Don't diagnose for value- or type-dependent expressions.
12444   if (E->isTypeDependent() || E->isValueDependent())
12445     return;
12446 
12447   // Check for array bounds violations in cases where the check isn't triggered
12448   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12449   // ArraySubscriptExpr is on the RHS of a variable initialization.
12450   CheckArrayAccess(E);
12451 
12452   // This is not the right CC for (e.g.) a variable initialization.
12453   AnalyzeImplicitConversions(*this, E, CC);
12454 }
12455 
12456 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12457 /// Input argument E is a logical expression.
12458 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12459   ::CheckBoolLikeConversion(*this, E, CC);
12460 }
12461 
12462 /// Diagnose when expression is an integer constant expression and its evaluation
12463 /// results in integer overflow
12464 void Sema::CheckForIntOverflow (Expr *E) {
12465   // Use a work list to deal with nested struct initializers.
12466   SmallVector<Expr *, 2> Exprs(1, E);
12467 
12468   do {
12469     Expr *OriginalE = Exprs.pop_back_val();
12470     Expr *E = OriginalE->IgnoreParenCasts();
12471 
12472     if (isa<BinaryOperator>(E)) {
12473       E->EvaluateForOverflow(Context);
12474       continue;
12475     }
12476 
12477     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12478       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12479     else if (isa<ObjCBoxedExpr>(OriginalE))
12480       E->EvaluateForOverflow(Context);
12481     else if (auto Call = dyn_cast<CallExpr>(E))
12482       Exprs.append(Call->arg_begin(), Call->arg_end());
12483     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12484       Exprs.append(Message->arg_begin(), Message->arg_end());
12485   } while (!Exprs.empty());
12486 }
12487 
12488 namespace {
12489 
12490 /// Visitor for expressions which looks for unsequenced operations on the
12491 /// same object.
12492 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12493   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12494 
12495   /// A tree of sequenced regions within an expression. Two regions are
12496   /// unsequenced if one is an ancestor or a descendent of the other. When we
12497   /// finish processing an expression with sequencing, such as a comma
12498   /// expression, we fold its tree nodes into its parent, since they are
12499   /// unsequenced with respect to nodes we will visit later.
12500   class SequenceTree {
12501     struct Value {
12502       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12503       unsigned Parent : 31;
12504       unsigned Merged : 1;
12505     };
12506     SmallVector<Value, 8> Values;
12507 
12508   public:
12509     /// A region within an expression which may be sequenced with respect
12510     /// to some other region.
12511     class Seq {
12512       friend class SequenceTree;
12513 
12514       unsigned Index;
12515 
12516       explicit Seq(unsigned N) : Index(N) {}
12517 
12518     public:
12519       Seq() : Index(0) {}
12520     };
12521 
12522     SequenceTree() { Values.push_back(Value(0)); }
12523     Seq root() const { return Seq(0); }
12524 
12525     /// Create a new sequence of operations, which is an unsequenced
12526     /// subset of \p Parent. This sequence of operations is sequenced with
12527     /// respect to other children of \p Parent.
12528     Seq allocate(Seq Parent) {
12529       Values.push_back(Value(Parent.Index));
12530       return Seq(Values.size() - 1);
12531     }
12532 
12533     /// Merge a sequence of operations into its parent.
12534     void merge(Seq S) {
12535       Values[S.Index].Merged = true;
12536     }
12537 
12538     /// Determine whether two operations are unsequenced. This operation
12539     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12540     /// should have been merged into its parent as appropriate.
12541     bool isUnsequenced(Seq Cur, Seq Old) {
12542       unsigned C = representative(Cur.Index);
12543       unsigned Target = representative(Old.Index);
12544       while (C >= Target) {
12545         if (C == Target)
12546           return true;
12547         C = Values[C].Parent;
12548       }
12549       return false;
12550     }
12551 
12552   private:
12553     /// Pick a representative for a sequence.
12554     unsigned representative(unsigned K) {
12555       if (Values[K].Merged)
12556         // Perform path compression as we go.
12557         return Values[K].Parent = representative(Values[K].Parent);
12558       return K;
12559     }
12560   };
12561 
12562   /// An object for which we can track unsequenced uses.
12563   using Object = const NamedDecl *;
12564 
12565   /// Different flavors of object usage which we track. We only track the
12566   /// least-sequenced usage of each kind.
12567   enum UsageKind {
12568     /// A read of an object. Multiple unsequenced reads are OK.
12569     UK_Use,
12570 
12571     /// A modification of an object which is sequenced before the value
12572     /// computation of the expression, such as ++n in C++.
12573     UK_ModAsValue,
12574 
12575     /// A modification of an object which is not sequenced before the value
12576     /// computation of the expression, such as n++.
12577     UK_ModAsSideEffect,
12578 
12579     UK_Count = UK_ModAsSideEffect + 1
12580   };
12581 
12582   /// Bundle together a sequencing region and the expression corresponding
12583   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12584   struct Usage {
12585     const Expr *UsageExpr;
12586     SequenceTree::Seq Seq;
12587 
12588     Usage() : UsageExpr(nullptr), Seq() {}
12589   };
12590 
12591   struct UsageInfo {
12592     Usage Uses[UK_Count];
12593 
12594     /// Have we issued a diagnostic for this object already?
12595     bool Diagnosed;
12596 
12597     UsageInfo() : Uses(), Diagnosed(false) {}
12598   };
12599   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12600 
12601   Sema &SemaRef;
12602 
12603   /// Sequenced regions within the expression.
12604   SequenceTree Tree;
12605 
12606   /// Declaration modifications and references which we have seen.
12607   UsageInfoMap UsageMap;
12608 
12609   /// The region we are currently within.
12610   SequenceTree::Seq Region;
12611 
12612   /// Filled in with declarations which were modified as a side-effect
12613   /// (that is, post-increment operations).
12614   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12615 
12616   /// Expressions to check later. We defer checking these to reduce
12617   /// stack usage.
12618   SmallVectorImpl<const Expr *> &WorkList;
12619 
12620   /// RAII object wrapping the visitation of a sequenced subexpression of an
12621   /// expression. At the end of this process, the side-effects of the evaluation
12622   /// become sequenced with respect to the value computation of the result, so
12623   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12624   /// UK_ModAsValue.
12625   struct SequencedSubexpression {
12626     SequencedSubexpression(SequenceChecker &Self)
12627       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12628       Self.ModAsSideEffect = &ModAsSideEffect;
12629     }
12630 
12631     ~SequencedSubexpression() {
12632       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12633         // Add a new usage with usage kind UK_ModAsValue, and then restore
12634         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12635         // the previous one was empty).
12636         UsageInfo &UI = Self.UsageMap[M.first];
12637         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12638         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12639         SideEffectUsage = M.second;
12640       }
12641       Self.ModAsSideEffect = OldModAsSideEffect;
12642     }
12643 
12644     SequenceChecker &Self;
12645     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12646     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12647   };
12648 
12649   /// RAII object wrapping the visitation of a subexpression which we might
12650   /// choose to evaluate as a constant. If any subexpression is evaluated and
12651   /// found to be non-constant, this allows us to suppress the evaluation of
12652   /// the outer expression.
12653   class EvaluationTracker {
12654   public:
12655     EvaluationTracker(SequenceChecker &Self)
12656         : Self(Self), Prev(Self.EvalTracker) {
12657       Self.EvalTracker = this;
12658     }
12659 
12660     ~EvaluationTracker() {
12661       Self.EvalTracker = Prev;
12662       if (Prev)
12663         Prev->EvalOK &= EvalOK;
12664     }
12665 
12666     bool evaluate(const Expr *E, bool &Result) {
12667       if (!EvalOK || E->isValueDependent())
12668         return false;
12669       EvalOK = E->EvaluateAsBooleanCondition(
12670           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12671       return EvalOK;
12672     }
12673 
12674   private:
12675     SequenceChecker &Self;
12676     EvaluationTracker *Prev;
12677     bool EvalOK = true;
12678   } *EvalTracker = nullptr;
12679 
12680   /// Find the object which is produced by the specified expression,
12681   /// if any.
12682   Object getObject(const Expr *E, bool Mod) const {
12683     E = E->IgnoreParenCasts();
12684     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12685       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12686         return getObject(UO->getSubExpr(), Mod);
12687     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12688       if (BO->getOpcode() == BO_Comma)
12689         return getObject(BO->getRHS(), Mod);
12690       if (Mod && BO->isAssignmentOp())
12691         return getObject(BO->getLHS(), Mod);
12692     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12693       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12694       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12695         return ME->getMemberDecl();
12696     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12697       // FIXME: If this is a reference, map through to its value.
12698       return DRE->getDecl();
12699     return nullptr;
12700   }
12701 
12702   /// Note that an object \p O was modified or used by an expression
12703   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12704   /// the object \p O as obtained via the \p UsageMap.
12705   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12706     // Get the old usage for the given object and usage kind.
12707     Usage &U = UI.Uses[UK];
12708     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12709       // If we have a modification as side effect and are in a sequenced
12710       // subexpression, save the old Usage so that we can restore it later
12711       // in SequencedSubexpression::~SequencedSubexpression.
12712       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12713         ModAsSideEffect->push_back(std::make_pair(O, U));
12714       // Then record the new usage with the current sequencing region.
12715       U.UsageExpr = UsageExpr;
12716       U.Seq = Region;
12717     }
12718   }
12719 
12720   /// Check whether a modification or use of an object \p O in an expression
12721   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12722   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12723   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12724   /// usage and false we are checking for a mod-use unsequenced usage.
12725   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12726                   UsageKind OtherKind, bool IsModMod) {
12727     if (UI.Diagnosed)
12728       return;
12729 
12730     const Usage &U = UI.Uses[OtherKind];
12731     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12732       return;
12733 
12734     const Expr *Mod = U.UsageExpr;
12735     const Expr *ModOrUse = UsageExpr;
12736     if (OtherKind == UK_Use)
12737       std::swap(Mod, ModOrUse);
12738 
12739     SemaRef.DiagRuntimeBehavior(
12740         Mod->getExprLoc(), {Mod, ModOrUse},
12741         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12742                                : diag::warn_unsequenced_mod_use)
12743             << O << SourceRange(ModOrUse->getExprLoc()));
12744     UI.Diagnosed = true;
12745   }
12746 
12747   // A note on note{Pre, Post}{Use, Mod}:
12748   //
12749   // (It helps to follow the algorithm with an expression such as
12750   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12751   //  operations before C++17 and both are well-defined in C++17).
12752   //
12753   // When visiting a node which uses/modify an object we first call notePreUse
12754   // or notePreMod before visiting its sub-expression(s). At this point the
12755   // children of the current node have not yet been visited and so the eventual
12756   // uses/modifications resulting from the children of the current node have not
12757   // been recorded yet.
12758   //
12759   // We then visit the children of the current node. After that notePostUse or
12760   // notePostMod is called. These will 1) detect an unsequenced modification
12761   // as side effect (as in "k++ + k") and 2) add a new usage with the
12762   // appropriate usage kind.
12763   //
12764   // We also have to be careful that some operation sequences modification as
12765   // side effect as well (for example: || or ,). To account for this we wrap
12766   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12767   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12768   // which record usages which are modifications as side effect, and then
12769   // downgrade them (or more accurately restore the previous usage which was a
12770   // modification as side effect) when exiting the scope of the sequenced
12771   // subexpression.
12772 
12773   void notePreUse(Object O, const Expr *UseExpr) {
12774     UsageInfo &UI = UsageMap[O];
12775     // Uses conflict with other modifications.
12776     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12777   }
12778 
12779   void notePostUse(Object O, const Expr *UseExpr) {
12780     UsageInfo &UI = UsageMap[O];
12781     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12782                /*IsModMod=*/false);
12783     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12784   }
12785 
12786   void notePreMod(Object O, const Expr *ModExpr) {
12787     UsageInfo &UI = UsageMap[O];
12788     // Modifications conflict with other modifications and with uses.
12789     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12790     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12791   }
12792 
12793   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12794     UsageInfo &UI = UsageMap[O];
12795     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12796                /*IsModMod=*/true);
12797     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12798   }
12799 
12800 public:
12801   SequenceChecker(Sema &S, const Expr *E,
12802                   SmallVectorImpl<const Expr *> &WorkList)
12803       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12804     Visit(E);
12805     // Silence a -Wunused-private-field since WorkList is now unused.
12806     // TODO: Evaluate if it can be used, and if not remove it.
12807     (void)this->WorkList;
12808   }
12809 
12810   void VisitStmt(const Stmt *S) {
12811     // Skip all statements which aren't expressions for now.
12812   }
12813 
12814   void VisitExpr(const Expr *E) {
12815     // By default, just recurse to evaluated subexpressions.
12816     Base::VisitStmt(E);
12817   }
12818 
12819   void VisitCastExpr(const CastExpr *E) {
12820     Object O = Object();
12821     if (E->getCastKind() == CK_LValueToRValue)
12822       O = getObject(E->getSubExpr(), false);
12823 
12824     if (O)
12825       notePreUse(O, E);
12826     VisitExpr(E);
12827     if (O)
12828       notePostUse(O, E);
12829   }
12830 
12831   void VisitSequencedExpressions(const Expr *SequencedBefore,
12832                                  const Expr *SequencedAfter) {
12833     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12834     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12835     SequenceTree::Seq OldRegion = Region;
12836 
12837     {
12838       SequencedSubexpression SeqBefore(*this);
12839       Region = BeforeRegion;
12840       Visit(SequencedBefore);
12841     }
12842 
12843     Region = AfterRegion;
12844     Visit(SequencedAfter);
12845 
12846     Region = OldRegion;
12847 
12848     Tree.merge(BeforeRegion);
12849     Tree.merge(AfterRegion);
12850   }
12851 
12852   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12853     // C++17 [expr.sub]p1:
12854     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12855     //   expression E1 is sequenced before the expression E2.
12856     if (SemaRef.getLangOpts().CPlusPlus17)
12857       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12858     else {
12859       Visit(ASE->getLHS());
12860       Visit(ASE->getRHS());
12861     }
12862   }
12863 
12864   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12865   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12866   void VisitBinPtrMem(const BinaryOperator *BO) {
12867     // C++17 [expr.mptr.oper]p4:
12868     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12869     //  the expression E1 is sequenced before the expression E2.
12870     if (SemaRef.getLangOpts().CPlusPlus17)
12871       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12872     else {
12873       Visit(BO->getLHS());
12874       Visit(BO->getRHS());
12875     }
12876   }
12877 
12878   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12879   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12880   void VisitBinShlShr(const BinaryOperator *BO) {
12881     // C++17 [expr.shift]p4:
12882     //  The expression E1 is sequenced before the expression E2.
12883     if (SemaRef.getLangOpts().CPlusPlus17)
12884       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12885     else {
12886       Visit(BO->getLHS());
12887       Visit(BO->getRHS());
12888     }
12889   }
12890 
12891   void VisitBinComma(const BinaryOperator *BO) {
12892     // C++11 [expr.comma]p1:
12893     //   Every value computation and side effect associated with the left
12894     //   expression is sequenced before every value computation and side
12895     //   effect associated with the right expression.
12896     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12897   }
12898 
12899   void VisitBinAssign(const BinaryOperator *BO) {
12900     SequenceTree::Seq RHSRegion;
12901     SequenceTree::Seq LHSRegion;
12902     if (SemaRef.getLangOpts().CPlusPlus17) {
12903       RHSRegion = Tree.allocate(Region);
12904       LHSRegion = Tree.allocate(Region);
12905     } else {
12906       RHSRegion = Region;
12907       LHSRegion = Region;
12908     }
12909     SequenceTree::Seq OldRegion = Region;
12910 
12911     // C++11 [expr.ass]p1:
12912     //  [...] the assignment is sequenced after the value computation
12913     //  of the right and left operands, [...]
12914     //
12915     // so check it before inspecting the operands and update the
12916     // map afterwards.
12917     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12918     if (O)
12919       notePreMod(O, BO);
12920 
12921     if (SemaRef.getLangOpts().CPlusPlus17) {
12922       // C++17 [expr.ass]p1:
12923       //  [...] The right operand is sequenced before the left operand. [...]
12924       {
12925         SequencedSubexpression SeqBefore(*this);
12926         Region = RHSRegion;
12927         Visit(BO->getRHS());
12928       }
12929 
12930       Region = LHSRegion;
12931       Visit(BO->getLHS());
12932 
12933       if (O && isa<CompoundAssignOperator>(BO))
12934         notePostUse(O, BO);
12935 
12936     } else {
12937       // C++11 does not specify any sequencing between the LHS and RHS.
12938       Region = LHSRegion;
12939       Visit(BO->getLHS());
12940 
12941       if (O && isa<CompoundAssignOperator>(BO))
12942         notePostUse(O, BO);
12943 
12944       Region = RHSRegion;
12945       Visit(BO->getRHS());
12946     }
12947 
12948     // C++11 [expr.ass]p1:
12949     //  the assignment is sequenced [...] before the value computation of the
12950     //  assignment expression.
12951     // C11 6.5.16/3 has no such rule.
12952     Region = OldRegion;
12953     if (O)
12954       notePostMod(O, BO,
12955                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12956                                                   : UK_ModAsSideEffect);
12957     if (SemaRef.getLangOpts().CPlusPlus17) {
12958       Tree.merge(RHSRegion);
12959       Tree.merge(LHSRegion);
12960     }
12961   }
12962 
12963   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12964     VisitBinAssign(CAO);
12965   }
12966 
12967   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12968   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12969   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12970     Object O = getObject(UO->getSubExpr(), true);
12971     if (!O)
12972       return VisitExpr(UO);
12973 
12974     notePreMod(O, UO);
12975     Visit(UO->getSubExpr());
12976     // C++11 [expr.pre.incr]p1:
12977     //   the expression ++x is equivalent to x+=1
12978     notePostMod(O, UO,
12979                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12980                                                 : UK_ModAsSideEffect);
12981   }
12982 
12983   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12984   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12985   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12986     Object O = getObject(UO->getSubExpr(), true);
12987     if (!O)
12988       return VisitExpr(UO);
12989 
12990     notePreMod(O, UO);
12991     Visit(UO->getSubExpr());
12992     notePostMod(O, UO, UK_ModAsSideEffect);
12993   }
12994 
12995   void VisitBinLOr(const BinaryOperator *BO) {
12996     // C++11 [expr.log.or]p2:
12997     //  If the second expression is evaluated, every value computation and
12998     //  side effect associated with the first expression is sequenced before
12999     //  every value computation and side effect associated with the
13000     //  second expression.
13001     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13002     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13003     SequenceTree::Seq OldRegion = Region;
13004 
13005     EvaluationTracker Eval(*this);
13006     {
13007       SequencedSubexpression Sequenced(*this);
13008       Region = LHSRegion;
13009       Visit(BO->getLHS());
13010     }
13011 
13012     // C++11 [expr.log.or]p1:
13013     //  [...] the second operand is not evaluated if the first operand
13014     //  evaluates to true.
13015     bool EvalResult = false;
13016     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13017     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13018     if (ShouldVisitRHS) {
13019       Region = RHSRegion;
13020       Visit(BO->getRHS());
13021     }
13022 
13023     Region = OldRegion;
13024     Tree.merge(LHSRegion);
13025     Tree.merge(RHSRegion);
13026   }
13027 
13028   void VisitBinLAnd(const BinaryOperator *BO) {
13029     // C++11 [expr.log.and]p2:
13030     //  If the second expression is evaluated, every value computation and
13031     //  side effect associated with the first expression is sequenced before
13032     //  every value computation and side effect associated with the
13033     //  second expression.
13034     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13035     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13036     SequenceTree::Seq OldRegion = Region;
13037 
13038     EvaluationTracker Eval(*this);
13039     {
13040       SequencedSubexpression Sequenced(*this);
13041       Region = LHSRegion;
13042       Visit(BO->getLHS());
13043     }
13044 
13045     // C++11 [expr.log.and]p1:
13046     //  [...] the second operand is not evaluated if the first operand is false.
13047     bool EvalResult = false;
13048     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13049     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13050     if (ShouldVisitRHS) {
13051       Region = RHSRegion;
13052       Visit(BO->getRHS());
13053     }
13054 
13055     Region = OldRegion;
13056     Tree.merge(LHSRegion);
13057     Tree.merge(RHSRegion);
13058   }
13059 
13060   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13061     // C++11 [expr.cond]p1:
13062     //  [...] Every value computation and side effect associated with the first
13063     //  expression is sequenced before every value computation and side effect
13064     //  associated with the second or third expression.
13065     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13066 
13067     // No sequencing is specified between the true and false expression.
13068     // However since exactly one of both is going to be evaluated we can
13069     // consider them to be sequenced. This is needed to avoid warning on
13070     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13071     // both the true and false expressions because we can't evaluate x.
13072     // This will still allow us to detect an expression like (pre C++17)
13073     // "(x ? y += 1 : y += 2) = y".
13074     //
13075     // We don't wrap the visitation of the true and false expression with
13076     // SequencedSubexpression because we don't want to downgrade modifications
13077     // as side effect in the true and false expressions after the visition
13078     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13079     // not warn between the two "y++", but we should warn between the "y++"
13080     // and the "y".
13081     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13082     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13083     SequenceTree::Seq OldRegion = Region;
13084 
13085     EvaluationTracker Eval(*this);
13086     {
13087       SequencedSubexpression Sequenced(*this);
13088       Region = ConditionRegion;
13089       Visit(CO->getCond());
13090     }
13091 
13092     // C++11 [expr.cond]p1:
13093     // [...] The first expression is contextually converted to bool (Clause 4).
13094     // It is evaluated and if it is true, the result of the conditional
13095     // expression is the value of the second expression, otherwise that of the
13096     // third expression. Only one of the second and third expressions is
13097     // evaluated. [...]
13098     bool EvalResult = false;
13099     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13100     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13101     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13102     if (ShouldVisitTrueExpr) {
13103       Region = TrueRegion;
13104       Visit(CO->getTrueExpr());
13105     }
13106     if (ShouldVisitFalseExpr) {
13107       Region = FalseRegion;
13108       Visit(CO->getFalseExpr());
13109     }
13110 
13111     Region = OldRegion;
13112     Tree.merge(ConditionRegion);
13113     Tree.merge(TrueRegion);
13114     Tree.merge(FalseRegion);
13115   }
13116 
13117   void VisitCallExpr(const CallExpr *CE) {
13118     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13119 
13120     if (CE->isUnevaluatedBuiltinCall(Context))
13121       return;
13122 
13123     // C++11 [intro.execution]p15:
13124     //   When calling a function [...], every value computation and side effect
13125     //   associated with any argument expression, or with the postfix expression
13126     //   designating the called function, is sequenced before execution of every
13127     //   expression or statement in the body of the function [and thus before
13128     //   the value computation of its result].
13129     SequencedSubexpression Sequenced(*this);
13130     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13131       // C++17 [expr.call]p5
13132       //   The postfix-expression is sequenced before each expression in the
13133       //   expression-list and any default argument. [...]
13134       SequenceTree::Seq CalleeRegion;
13135       SequenceTree::Seq OtherRegion;
13136       if (SemaRef.getLangOpts().CPlusPlus17) {
13137         CalleeRegion = Tree.allocate(Region);
13138         OtherRegion = Tree.allocate(Region);
13139       } else {
13140         CalleeRegion = Region;
13141         OtherRegion = Region;
13142       }
13143       SequenceTree::Seq OldRegion = Region;
13144 
13145       // Visit the callee expression first.
13146       Region = CalleeRegion;
13147       if (SemaRef.getLangOpts().CPlusPlus17) {
13148         SequencedSubexpression Sequenced(*this);
13149         Visit(CE->getCallee());
13150       } else {
13151         Visit(CE->getCallee());
13152       }
13153 
13154       // Then visit the argument expressions.
13155       Region = OtherRegion;
13156       for (const Expr *Argument : CE->arguments())
13157         Visit(Argument);
13158 
13159       Region = OldRegion;
13160       if (SemaRef.getLangOpts().CPlusPlus17) {
13161         Tree.merge(CalleeRegion);
13162         Tree.merge(OtherRegion);
13163       }
13164     });
13165   }
13166 
13167   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13168     // C++17 [over.match.oper]p2:
13169     //   [...] the operator notation is first transformed to the equivalent
13170     //   function-call notation as summarized in Table 12 (where @ denotes one
13171     //   of the operators covered in the specified subclause). However, the
13172     //   operands are sequenced in the order prescribed for the built-in
13173     //   operator (Clause 8).
13174     //
13175     // From the above only overloaded binary operators and overloaded call
13176     // operators have sequencing rules in C++17 that we need to handle
13177     // separately.
13178     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13179         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13180       return VisitCallExpr(CXXOCE);
13181 
13182     enum {
13183       NoSequencing,
13184       LHSBeforeRHS,
13185       RHSBeforeLHS,
13186       LHSBeforeRest
13187     } SequencingKind;
13188     switch (CXXOCE->getOperator()) {
13189     case OO_Equal:
13190     case OO_PlusEqual:
13191     case OO_MinusEqual:
13192     case OO_StarEqual:
13193     case OO_SlashEqual:
13194     case OO_PercentEqual:
13195     case OO_CaretEqual:
13196     case OO_AmpEqual:
13197     case OO_PipeEqual:
13198     case OO_LessLessEqual:
13199     case OO_GreaterGreaterEqual:
13200       SequencingKind = RHSBeforeLHS;
13201       break;
13202 
13203     case OO_LessLess:
13204     case OO_GreaterGreater:
13205     case OO_AmpAmp:
13206     case OO_PipePipe:
13207     case OO_Comma:
13208     case OO_ArrowStar:
13209     case OO_Subscript:
13210       SequencingKind = LHSBeforeRHS;
13211       break;
13212 
13213     case OO_Call:
13214       SequencingKind = LHSBeforeRest;
13215       break;
13216 
13217     default:
13218       SequencingKind = NoSequencing;
13219       break;
13220     }
13221 
13222     if (SequencingKind == NoSequencing)
13223       return VisitCallExpr(CXXOCE);
13224 
13225     // This is a call, so all subexpressions are sequenced before the result.
13226     SequencedSubexpression Sequenced(*this);
13227 
13228     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13229       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13230              "Should only get there with C++17 and above!");
13231       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13232              "Should only get there with an overloaded binary operator"
13233              " or an overloaded call operator!");
13234 
13235       if (SequencingKind == LHSBeforeRest) {
13236         assert(CXXOCE->getOperator() == OO_Call &&
13237                "We should only have an overloaded call operator here!");
13238 
13239         // This is very similar to VisitCallExpr, except that we only have the
13240         // C++17 case. The postfix-expression is the first argument of the
13241         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13242         // are in the following arguments.
13243         //
13244         // Note that we intentionally do not visit the callee expression since
13245         // it is just a decayed reference to a function.
13246         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13247         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13248         SequenceTree::Seq OldRegion = Region;
13249 
13250         assert(CXXOCE->getNumArgs() >= 1 &&
13251                "An overloaded call operator must have at least one argument"
13252                " for the postfix-expression!");
13253         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13254         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13255                                           CXXOCE->getNumArgs() - 1);
13256 
13257         // Visit the postfix-expression first.
13258         {
13259           Region = PostfixExprRegion;
13260           SequencedSubexpression Sequenced(*this);
13261           Visit(PostfixExpr);
13262         }
13263 
13264         // Then visit the argument expressions.
13265         Region = ArgsRegion;
13266         for (const Expr *Arg : Args)
13267           Visit(Arg);
13268 
13269         Region = OldRegion;
13270         Tree.merge(PostfixExprRegion);
13271         Tree.merge(ArgsRegion);
13272       } else {
13273         assert(CXXOCE->getNumArgs() == 2 &&
13274                "Should only have two arguments here!");
13275         assert((SequencingKind == LHSBeforeRHS ||
13276                 SequencingKind == RHSBeforeLHS) &&
13277                "Unexpected sequencing kind!");
13278 
13279         // We do not visit the callee expression since it is just a decayed
13280         // reference to a function.
13281         const Expr *E1 = CXXOCE->getArg(0);
13282         const Expr *E2 = CXXOCE->getArg(1);
13283         if (SequencingKind == RHSBeforeLHS)
13284           std::swap(E1, E2);
13285 
13286         return VisitSequencedExpressions(E1, E2);
13287       }
13288     });
13289   }
13290 
13291   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13292     // This is a call, so all subexpressions are sequenced before the result.
13293     SequencedSubexpression Sequenced(*this);
13294 
13295     if (!CCE->isListInitialization())
13296       return VisitExpr(CCE);
13297 
13298     // In C++11, list initializations are sequenced.
13299     SmallVector<SequenceTree::Seq, 32> Elts;
13300     SequenceTree::Seq Parent = Region;
13301     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13302                                               E = CCE->arg_end();
13303          I != E; ++I) {
13304       Region = Tree.allocate(Parent);
13305       Elts.push_back(Region);
13306       Visit(*I);
13307     }
13308 
13309     // Forget that the initializers are sequenced.
13310     Region = Parent;
13311     for (unsigned I = 0; I < Elts.size(); ++I)
13312       Tree.merge(Elts[I]);
13313   }
13314 
13315   void VisitInitListExpr(const InitListExpr *ILE) {
13316     if (!SemaRef.getLangOpts().CPlusPlus11)
13317       return VisitExpr(ILE);
13318 
13319     // In C++11, list initializations are sequenced.
13320     SmallVector<SequenceTree::Seq, 32> Elts;
13321     SequenceTree::Seq Parent = Region;
13322     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13323       const Expr *E = ILE->getInit(I);
13324       if (!E)
13325         continue;
13326       Region = Tree.allocate(Parent);
13327       Elts.push_back(Region);
13328       Visit(E);
13329     }
13330 
13331     // Forget that the initializers are sequenced.
13332     Region = Parent;
13333     for (unsigned I = 0; I < Elts.size(); ++I)
13334       Tree.merge(Elts[I]);
13335   }
13336 };
13337 
13338 } // namespace
13339 
13340 void Sema::CheckUnsequencedOperations(const Expr *E) {
13341   SmallVector<const Expr *, 8> WorkList;
13342   WorkList.push_back(E);
13343   while (!WorkList.empty()) {
13344     const Expr *Item = WorkList.pop_back_val();
13345     SequenceChecker(*this, Item, WorkList);
13346   }
13347 }
13348 
13349 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13350                               bool IsConstexpr) {
13351   llvm::SaveAndRestore<bool> ConstantContext(
13352       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13353   CheckImplicitConversions(E, CheckLoc);
13354   if (!E->isInstantiationDependent())
13355     CheckUnsequencedOperations(E);
13356   if (!IsConstexpr && !E->isValueDependent())
13357     CheckForIntOverflow(E);
13358   DiagnoseMisalignedMembers();
13359 }
13360 
13361 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13362                                        FieldDecl *BitField,
13363                                        Expr *Init) {
13364   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13365 }
13366 
13367 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13368                                          SourceLocation Loc) {
13369   if (!PType->isVariablyModifiedType())
13370     return;
13371   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13372     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13373     return;
13374   }
13375   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13376     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13377     return;
13378   }
13379   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13380     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13381     return;
13382   }
13383 
13384   const ArrayType *AT = S.Context.getAsArrayType(PType);
13385   if (!AT)
13386     return;
13387 
13388   if (AT->getSizeModifier() != ArrayType::Star) {
13389     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13390     return;
13391   }
13392 
13393   S.Diag(Loc, diag::err_array_star_in_function_definition);
13394 }
13395 
13396 /// CheckParmsForFunctionDef - Check that the parameters of the given
13397 /// function are appropriate for the definition of a function. This
13398 /// takes care of any checks that cannot be performed on the
13399 /// declaration itself, e.g., that the types of each of the function
13400 /// parameters are complete.
13401 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13402                                     bool CheckParameterNames) {
13403   bool HasInvalidParm = false;
13404   for (ParmVarDecl *Param : Parameters) {
13405     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13406     // function declarator that is part of a function definition of
13407     // that function shall not have incomplete type.
13408     //
13409     // This is also C++ [dcl.fct]p6.
13410     if (!Param->isInvalidDecl() &&
13411         RequireCompleteType(Param->getLocation(), Param->getType(),
13412                             diag::err_typecheck_decl_incomplete_type)) {
13413       Param->setInvalidDecl();
13414       HasInvalidParm = true;
13415     }
13416 
13417     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13418     // declaration of each parameter shall include an identifier.
13419     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13420         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13421       // Diagnose this as an extension in C17 and earlier.
13422       if (!getLangOpts().C2x)
13423         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13424     }
13425 
13426     // C99 6.7.5.3p12:
13427     //   If the function declarator is not part of a definition of that
13428     //   function, parameters may have incomplete type and may use the [*]
13429     //   notation in their sequences of declarator specifiers to specify
13430     //   variable length array types.
13431     QualType PType = Param->getOriginalType();
13432     // FIXME: This diagnostic should point the '[*]' if source-location
13433     // information is added for it.
13434     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13435 
13436     // If the parameter is a c++ class type and it has to be destructed in the
13437     // callee function, declare the destructor so that it can be called by the
13438     // callee function. Do not perform any direct access check on the dtor here.
13439     if (!Param->isInvalidDecl()) {
13440       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13441         if (!ClassDecl->isInvalidDecl() &&
13442             !ClassDecl->hasIrrelevantDestructor() &&
13443             !ClassDecl->isDependentContext() &&
13444             ClassDecl->isParamDestroyedInCallee()) {
13445           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13446           MarkFunctionReferenced(Param->getLocation(), Destructor);
13447           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13448         }
13449       }
13450     }
13451 
13452     // Parameters with the pass_object_size attribute only need to be marked
13453     // constant at function definitions. Because we lack information about
13454     // whether we're on a declaration or definition when we're instantiating the
13455     // attribute, we need to check for constness here.
13456     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13457       if (!Param->getType().isConstQualified())
13458         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13459             << Attr->getSpelling() << 1;
13460 
13461     // Check for parameter names shadowing fields from the class.
13462     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13463       // The owning context for the parameter should be the function, but we
13464       // want to see if this function's declaration context is a record.
13465       DeclContext *DC = Param->getDeclContext();
13466       if (DC && DC->isFunctionOrMethod()) {
13467         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13468           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13469                                      RD, /*DeclIsField*/ false);
13470       }
13471     }
13472   }
13473 
13474   return HasInvalidParm;
13475 }
13476 
13477 Optional<std::pair<CharUnits, CharUnits>>
13478 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13479 
13480 /// Compute the alignment and offset of the base class object given the
13481 /// derived-to-base cast expression and the alignment and offset of the derived
13482 /// class object.
13483 static std::pair<CharUnits, CharUnits>
13484 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13485                                    CharUnits BaseAlignment, CharUnits Offset,
13486                                    ASTContext &Ctx) {
13487   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13488        ++PathI) {
13489     const CXXBaseSpecifier *Base = *PathI;
13490     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13491     if (Base->isVirtual()) {
13492       // The complete object may have a lower alignment than the non-virtual
13493       // alignment of the base, in which case the base may be misaligned. Choose
13494       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13495       // conservative lower bound of the complete object alignment.
13496       CharUnits NonVirtualAlignment =
13497           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13498       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13499       Offset = CharUnits::Zero();
13500     } else {
13501       const ASTRecordLayout &RL =
13502           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13503       Offset += RL.getBaseClassOffset(BaseDecl);
13504     }
13505     DerivedType = Base->getType();
13506   }
13507 
13508   return std::make_pair(BaseAlignment, Offset);
13509 }
13510 
13511 /// Compute the alignment and offset of a binary additive operator.
13512 static Optional<std::pair<CharUnits, CharUnits>>
13513 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13514                                      bool IsSub, ASTContext &Ctx) {
13515   QualType PointeeType = PtrE->getType()->getPointeeType();
13516 
13517   if (!PointeeType->isConstantSizeType())
13518     return llvm::None;
13519 
13520   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13521 
13522   if (!P)
13523     return llvm::None;
13524 
13525   llvm::APSInt IdxRes;
13526   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13527   if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) {
13528     CharUnits Offset = EltSize * IdxRes.getExtValue();
13529     if (IsSub)
13530       Offset = -Offset;
13531     return std::make_pair(P->first, P->second + Offset);
13532   }
13533 
13534   // If the integer expression isn't a constant expression, compute the lower
13535   // bound of the alignment using the alignment and offset of the pointer
13536   // expression and the element size.
13537   return std::make_pair(
13538       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13539       CharUnits::Zero());
13540 }
13541 
13542 /// This helper function takes an lvalue expression and returns the alignment of
13543 /// a VarDecl and a constant offset from the VarDecl.
13544 Optional<std::pair<CharUnits, CharUnits>>
13545 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13546   E = E->IgnoreParens();
13547   switch (E->getStmtClass()) {
13548   default:
13549     break;
13550   case Stmt::CStyleCastExprClass:
13551   case Stmt::CXXStaticCastExprClass:
13552   case Stmt::ImplicitCastExprClass: {
13553     auto *CE = cast<CastExpr>(E);
13554     const Expr *From = CE->getSubExpr();
13555     switch (CE->getCastKind()) {
13556     default:
13557       break;
13558     case CK_NoOp:
13559       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13560     case CK_UncheckedDerivedToBase:
13561     case CK_DerivedToBase: {
13562       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13563       if (!P)
13564         break;
13565       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13566                                                 P->second, Ctx);
13567     }
13568     }
13569     break;
13570   }
13571   case Stmt::ArraySubscriptExprClass: {
13572     auto *ASE = cast<ArraySubscriptExpr>(E);
13573     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13574                                                 false, Ctx);
13575   }
13576   case Stmt::DeclRefExprClass: {
13577     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13578       // FIXME: If VD is captured by copy or is an escaping __block variable,
13579       // use the alignment of VD's type.
13580       if (!VD->getType()->isReferenceType())
13581         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13582       if (VD->hasInit())
13583         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13584     }
13585     break;
13586   }
13587   case Stmt::MemberExprClass: {
13588     auto *ME = cast<MemberExpr>(E);
13589     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13590     if (!FD || FD->getType()->isReferenceType())
13591       break;
13592     Optional<std::pair<CharUnits, CharUnits>> P;
13593     if (ME->isArrow())
13594       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
13595     else
13596       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13597     if (!P)
13598       break;
13599     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13600     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13601     return std::make_pair(P->first,
13602                           P->second + CharUnits::fromQuantity(Offset));
13603   }
13604   case Stmt::UnaryOperatorClass: {
13605     auto *UO = cast<UnaryOperator>(E);
13606     switch (UO->getOpcode()) {
13607     default:
13608       break;
13609     case UO_Deref:
13610       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13611     }
13612     break;
13613   }
13614   case Stmt::BinaryOperatorClass: {
13615     auto *BO = cast<BinaryOperator>(E);
13616     auto Opcode = BO->getOpcode();
13617     switch (Opcode) {
13618     default:
13619       break;
13620     case BO_Comma:
13621       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13622     }
13623     break;
13624   }
13625   }
13626   return llvm::None;
13627 }
13628 
13629 /// This helper function takes a pointer expression and returns the alignment of
13630 /// a VarDecl and a constant offset from the VarDecl.
13631 Optional<std::pair<CharUnits, CharUnits>>
13632 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13633   E = E->IgnoreParens();
13634   switch (E->getStmtClass()) {
13635   default:
13636     break;
13637   case Stmt::CStyleCastExprClass:
13638   case Stmt::CXXStaticCastExprClass:
13639   case Stmt::ImplicitCastExprClass: {
13640     auto *CE = cast<CastExpr>(E);
13641     const Expr *From = CE->getSubExpr();
13642     switch (CE->getCastKind()) {
13643     default:
13644       break;
13645     case CK_NoOp:
13646       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13647     case CK_ArrayToPointerDecay:
13648       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13649     case CK_UncheckedDerivedToBase:
13650     case CK_DerivedToBase: {
13651       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13652       if (!P)
13653         break;
13654       return getDerivedToBaseAlignmentAndOffset(
13655           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13656     }
13657     }
13658     break;
13659   }
13660   case Stmt::CXXThisExprClass: {
13661     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13662     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
13663     return std::make_pair(Alignment, CharUnits::Zero());
13664   }
13665   case Stmt::UnaryOperatorClass: {
13666     auto *UO = cast<UnaryOperator>(E);
13667     if (UO->getOpcode() == UO_AddrOf)
13668       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13669     break;
13670   }
13671   case Stmt::BinaryOperatorClass: {
13672     auto *BO = cast<BinaryOperator>(E);
13673     auto Opcode = BO->getOpcode();
13674     switch (Opcode) {
13675     default:
13676       break;
13677     case BO_Add:
13678     case BO_Sub: {
13679       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13680       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13681         std::swap(LHS, RHS);
13682       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13683                                                   Ctx);
13684     }
13685     case BO_Comma:
13686       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13687     }
13688     break;
13689   }
13690   }
13691   return llvm::None;
13692 }
13693 
13694 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13695   // See if we can compute the alignment of a VarDecl and an offset from it.
13696   Optional<std::pair<CharUnits, CharUnits>> P =
13697       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13698 
13699   if (P)
13700     return P->first.alignmentAtOffset(P->second);
13701 
13702   // If that failed, return the type's alignment.
13703   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13704 }
13705 
13706 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13707 /// pointer cast increases the alignment requirements.
13708 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13709   // This is actually a lot of work to potentially be doing on every
13710   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13711   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13712     return;
13713 
13714   // Ignore dependent types.
13715   if (T->isDependentType() || Op->getType()->isDependentType())
13716     return;
13717 
13718   // Require that the destination be a pointer type.
13719   const PointerType *DestPtr = T->getAs<PointerType>();
13720   if (!DestPtr) return;
13721 
13722   // If the destination has alignment 1, we're done.
13723   QualType DestPointee = DestPtr->getPointeeType();
13724   if (DestPointee->isIncompleteType()) return;
13725   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13726   if (DestAlign.isOne()) return;
13727 
13728   // Require that the source be a pointer type.
13729   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13730   if (!SrcPtr) return;
13731   QualType SrcPointee = SrcPtr->getPointeeType();
13732 
13733   // Explicitly allow casts from cv void*.  We already implicitly
13734   // allowed casts to cv void*, since they have alignment 1.
13735   // Also allow casts involving incomplete types, which implicitly
13736   // includes 'void'.
13737   if (SrcPointee->isIncompleteType()) return;
13738 
13739   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13740 
13741   if (SrcAlign >= DestAlign) return;
13742 
13743   Diag(TRange.getBegin(), diag::warn_cast_align)
13744     << Op->getType() << T
13745     << static_cast<unsigned>(SrcAlign.getQuantity())
13746     << static_cast<unsigned>(DestAlign.getQuantity())
13747     << TRange << Op->getSourceRange();
13748 }
13749 
13750 /// Check whether this array fits the idiom of a size-one tail padded
13751 /// array member of a struct.
13752 ///
13753 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13754 /// commonly used to emulate flexible arrays in C89 code.
13755 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13756                                     const NamedDecl *ND) {
13757   if (Size != 1 || !ND) return false;
13758 
13759   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13760   if (!FD) return false;
13761 
13762   // Don't consider sizes resulting from macro expansions or template argument
13763   // substitution to form C89 tail-padded arrays.
13764 
13765   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13766   while (TInfo) {
13767     TypeLoc TL = TInfo->getTypeLoc();
13768     // Look through typedefs.
13769     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13770       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13771       TInfo = TDL->getTypeSourceInfo();
13772       continue;
13773     }
13774     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13775       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13776       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13777         return false;
13778     }
13779     break;
13780   }
13781 
13782   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13783   if (!RD) return false;
13784   if (RD->isUnion()) return false;
13785   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13786     if (!CRD->isStandardLayout()) return false;
13787   }
13788 
13789   // See if this is the last field decl in the record.
13790   const Decl *D = FD;
13791   while ((D = D->getNextDeclInContext()))
13792     if (isa<FieldDecl>(D))
13793       return false;
13794   return true;
13795 }
13796 
13797 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13798                             const ArraySubscriptExpr *ASE,
13799                             bool AllowOnePastEnd, bool IndexNegated) {
13800   // Already diagnosed by the constant evaluator.
13801   if (isConstantEvaluated())
13802     return;
13803 
13804   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13805   if (IndexExpr->isValueDependent())
13806     return;
13807 
13808   const Type *EffectiveType =
13809       BaseExpr->getType()->getPointeeOrArrayElementType();
13810   BaseExpr = BaseExpr->IgnoreParenCasts();
13811   const ConstantArrayType *ArrayTy =
13812       Context.getAsConstantArrayType(BaseExpr->getType());
13813 
13814   if (!ArrayTy)
13815     return;
13816 
13817   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13818   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13819     return;
13820 
13821   Expr::EvalResult Result;
13822   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13823     return;
13824 
13825   llvm::APSInt index = Result.Val.getInt();
13826   if (IndexNegated)
13827     index = -index;
13828 
13829   const NamedDecl *ND = nullptr;
13830   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13831     ND = DRE->getDecl();
13832   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13833     ND = ME->getMemberDecl();
13834 
13835   if (index.isUnsigned() || !index.isNegative()) {
13836     // It is possible that the type of the base expression after
13837     // IgnoreParenCasts is incomplete, even though the type of the base
13838     // expression before IgnoreParenCasts is complete (see PR39746 for an
13839     // example). In this case we have no information about whether the array
13840     // access exceeds the array bounds. However we can still diagnose an array
13841     // access which precedes the array bounds.
13842     if (BaseType->isIncompleteType())
13843       return;
13844 
13845     llvm::APInt size = ArrayTy->getSize();
13846     if (!size.isStrictlyPositive())
13847       return;
13848 
13849     if (BaseType != EffectiveType) {
13850       // Make sure we're comparing apples to apples when comparing index to size
13851       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13852       uint64_t array_typesize = Context.getTypeSize(BaseType);
13853       // Handle ptrarith_typesize being zero, such as when casting to void*
13854       if (!ptrarith_typesize) ptrarith_typesize = 1;
13855       if (ptrarith_typesize != array_typesize) {
13856         // There's a cast to a different size type involved
13857         uint64_t ratio = array_typesize / ptrarith_typesize;
13858         // TODO: Be smarter about handling cases where array_typesize is not a
13859         // multiple of ptrarith_typesize
13860         if (ptrarith_typesize * ratio == array_typesize)
13861           size *= llvm::APInt(size.getBitWidth(), ratio);
13862       }
13863     }
13864 
13865     if (size.getBitWidth() > index.getBitWidth())
13866       index = index.zext(size.getBitWidth());
13867     else if (size.getBitWidth() < index.getBitWidth())
13868       size = size.zext(index.getBitWidth());
13869 
13870     // For array subscripting the index must be less than size, but for pointer
13871     // arithmetic also allow the index (offset) to be equal to size since
13872     // computing the next address after the end of the array is legal and
13873     // commonly done e.g. in C++ iterators and range-based for loops.
13874     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13875       return;
13876 
13877     // Also don't warn for arrays of size 1 which are members of some
13878     // structure. These are often used to approximate flexible arrays in C89
13879     // code.
13880     if (IsTailPaddedMemberArray(*this, size, ND))
13881       return;
13882 
13883     // Suppress the warning if the subscript expression (as identified by the
13884     // ']' location) and the index expression are both from macro expansions
13885     // within a system header.
13886     if (ASE) {
13887       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13888           ASE->getRBracketLoc());
13889       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13890         SourceLocation IndexLoc =
13891             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13892         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13893           return;
13894       }
13895     }
13896 
13897     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13898     if (ASE)
13899       DiagID = diag::warn_array_index_exceeds_bounds;
13900 
13901     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13902                         PDiag(DiagID) << index.toString(10, true)
13903                                       << size.toString(10, true)
13904                                       << (unsigned)size.getLimitedValue(~0U)
13905                                       << IndexExpr->getSourceRange());
13906   } else {
13907     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13908     if (!ASE) {
13909       DiagID = diag::warn_ptr_arith_precedes_bounds;
13910       if (index.isNegative()) index = -index;
13911     }
13912 
13913     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13914                         PDiag(DiagID) << index.toString(10, true)
13915                                       << IndexExpr->getSourceRange());
13916   }
13917 
13918   if (!ND) {
13919     // Try harder to find a NamedDecl to point at in the note.
13920     while (const ArraySubscriptExpr *ASE =
13921            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13922       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13923     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13924       ND = DRE->getDecl();
13925     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13926       ND = ME->getMemberDecl();
13927   }
13928 
13929   if (ND)
13930     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13931                         PDiag(diag::note_array_declared_here)
13932                             << ND->getDeclName());
13933 }
13934 
13935 void Sema::CheckArrayAccess(const Expr *expr) {
13936   int AllowOnePastEnd = 0;
13937   while (expr) {
13938     expr = expr->IgnoreParenImpCasts();
13939     switch (expr->getStmtClass()) {
13940       case Stmt::ArraySubscriptExprClass: {
13941         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13942         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13943                          AllowOnePastEnd > 0);
13944         expr = ASE->getBase();
13945         break;
13946       }
13947       case Stmt::MemberExprClass: {
13948         expr = cast<MemberExpr>(expr)->getBase();
13949         break;
13950       }
13951       case Stmt::OMPArraySectionExprClass: {
13952         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13953         if (ASE->getLowerBound())
13954           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13955                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13956         return;
13957       }
13958       case Stmt::UnaryOperatorClass: {
13959         // Only unwrap the * and & unary operators
13960         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13961         expr = UO->getSubExpr();
13962         switch (UO->getOpcode()) {
13963           case UO_AddrOf:
13964             AllowOnePastEnd++;
13965             break;
13966           case UO_Deref:
13967             AllowOnePastEnd--;
13968             break;
13969           default:
13970             return;
13971         }
13972         break;
13973       }
13974       case Stmt::ConditionalOperatorClass: {
13975         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13976         if (const Expr *lhs = cond->getLHS())
13977           CheckArrayAccess(lhs);
13978         if (const Expr *rhs = cond->getRHS())
13979           CheckArrayAccess(rhs);
13980         return;
13981       }
13982       case Stmt::CXXOperatorCallExprClass: {
13983         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13984         for (const auto *Arg : OCE->arguments())
13985           CheckArrayAccess(Arg);
13986         return;
13987       }
13988       default:
13989         return;
13990     }
13991   }
13992 }
13993 
13994 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13995 
13996 namespace {
13997 
13998 struct RetainCycleOwner {
13999   VarDecl *Variable = nullptr;
14000   SourceRange Range;
14001   SourceLocation Loc;
14002   bool Indirect = false;
14003 
14004   RetainCycleOwner() = default;
14005 
14006   void setLocsFrom(Expr *e) {
14007     Loc = e->getExprLoc();
14008     Range = e->getSourceRange();
14009   }
14010 };
14011 
14012 } // namespace
14013 
14014 /// Consider whether capturing the given variable can possibly lead to
14015 /// a retain cycle.
14016 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14017   // In ARC, it's captured strongly iff the variable has __strong
14018   // lifetime.  In MRR, it's captured strongly if the variable is
14019   // __block and has an appropriate type.
14020   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14021     return false;
14022 
14023   owner.Variable = var;
14024   if (ref)
14025     owner.setLocsFrom(ref);
14026   return true;
14027 }
14028 
14029 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14030   while (true) {
14031     e = e->IgnoreParens();
14032     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14033       switch (cast->getCastKind()) {
14034       case CK_BitCast:
14035       case CK_LValueBitCast:
14036       case CK_LValueToRValue:
14037       case CK_ARCReclaimReturnedObject:
14038         e = cast->getSubExpr();
14039         continue;
14040 
14041       default:
14042         return false;
14043       }
14044     }
14045 
14046     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14047       ObjCIvarDecl *ivar = ref->getDecl();
14048       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14049         return false;
14050 
14051       // Try to find a retain cycle in the base.
14052       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14053         return false;
14054 
14055       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14056       owner.Indirect = true;
14057       return true;
14058     }
14059 
14060     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14061       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14062       if (!var) return false;
14063       return considerVariable(var, ref, owner);
14064     }
14065 
14066     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14067       if (member->isArrow()) return false;
14068 
14069       // Don't count this as an indirect ownership.
14070       e = member->getBase();
14071       continue;
14072     }
14073 
14074     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14075       // Only pay attention to pseudo-objects on property references.
14076       ObjCPropertyRefExpr *pre
14077         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14078                                               ->IgnoreParens());
14079       if (!pre) return false;
14080       if (pre->isImplicitProperty()) return false;
14081       ObjCPropertyDecl *property = pre->getExplicitProperty();
14082       if (!property->isRetaining() &&
14083           !(property->getPropertyIvarDecl() &&
14084             property->getPropertyIvarDecl()->getType()
14085               .getObjCLifetime() == Qualifiers::OCL_Strong))
14086           return false;
14087 
14088       owner.Indirect = true;
14089       if (pre->isSuperReceiver()) {
14090         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14091         if (!owner.Variable)
14092           return false;
14093         owner.Loc = pre->getLocation();
14094         owner.Range = pre->getSourceRange();
14095         return true;
14096       }
14097       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14098                               ->getSourceExpr());
14099       continue;
14100     }
14101 
14102     // Array ivars?
14103 
14104     return false;
14105   }
14106 }
14107 
14108 namespace {
14109 
14110   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14111     ASTContext &Context;
14112     VarDecl *Variable;
14113     Expr *Capturer = nullptr;
14114     bool VarWillBeReased = false;
14115 
14116     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14117         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14118           Context(Context), Variable(variable) {}
14119 
14120     void VisitDeclRefExpr(DeclRefExpr *ref) {
14121       if (ref->getDecl() == Variable && !Capturer)
14122         Capturer = ref;
14123     }
14124 
14125     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14126       if (Capturer) return;
14127       Visit(ref->getBase());
14128       if (Capturer && ref->isFreeIvar())
14129         Capturer = ref;
14130     }
14131 
14132     void VisitBlockExpr(BlockExpr *block) {
14133       // Look inside nested blocks
14134       if (block->getBlockDecl()->capturesVariable(Variable))
14135         Visit(block->getBlockDecl()->getBody());
14136     }
14137 
14138     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14139       if (Capturer) return;
14140       if (OVE->getSourceExpr())
14141         Visit(OVE->getSourceExpr());
14142     }
14143 
14144     void VisitBinaryOperator(BinaryOperator *BinOp) {
14145       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14146         return;
14147       Expr *LHS = BinOp->getLHS();
14148       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14149         if (DRE->getDecl() != Variable)
14150           return;
14151         if (Expr *RHS = BinOp->getRHS()) {
14152           RHS = RHS->IgnoreParenCasts();
14153           llvm::APSInt Value;
14154           VarWillBeReased =
14155             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
14156         }
14157       }
14158     }
14159   };
14160 
14161 } // namespace
14162 
14163 /// Check whether the given argument is a block which captures a
14164 /// variable.
14165 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14166   assert(owner.Variable && owner.Loc.isValid());
14167 
14168   e = e->IgnoreParenCasts();
14169 
14170   // Look through [^{...} copy] and Block_copy(^{...}).
14171   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14172     Selector Cmd = ME->getSelector();
14173     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14174       e = ME->getInstanceReceiver();
14175       if (!e)
14176         return nullptr;
14177       e = e->IgnoreParenCasts();
14178     }
14179   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14180     if (CE->getNumArgs() == 1) {
14181       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14182       if (Fn) {
14183         const IdentifierInfo *FnI = Fn->getIdentifier();
14184         if (FnI && FnI->isStr("_Block_copy")) {
14185           e = CE->getArg(0)->IgnoreParenCasts();
14186         }
14187       }
14188     }
14189   }
14190 
14191   BlockExpr *block = dyn_cast<BlockExpr>(e);
14192   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14193     return nullptr;
14194 
14195   FindCaptureVisitor visitor(S.Context, owner.Variable);
14196   visitor.Visit(block->getBlockDecl()->getBody());
14197   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14198 }
14199 
14200 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14201                                 RetainCycleOwner &owner) {
14202   assert(capturer);
14203   assert(owner.Variable && owner.Loc.isValid());
14204 
14205   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14206     << owner.Variable << capturer->getSourceRange();
14207   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14208     << owner.Indirect << owner.Range;
14209 }
14210 
14211 /// Check for a keyword selector that starts with the word 'add' or
14212 /// 'set'.
14213 static bool isSetterLikeSelector(Selector sel) {
14214   if (sel.isUnarySelector()) return false;
14215 
14216   StringRef str = sel.getNameForSlot(0);
14217   while (!str.empty() && str.front() == '_') str = str.substr(1);
14218   if (str.startswith("set"))
14219     str = str.substr(3);
14220   else if (str.startswith("add")) {
14221     // Specially allow 'addOperationWithBlock:'.
14222     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14223       return false;
14224     str = str.substr(3);
14225   }
14226   else
14227     return false;
14228 
14229   if (str.empty()) return true;
14230   return !isLowercase(str.front());
14231 }
14232 
14233 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14234                                                     ObjCMessageExpr *Message) {
14235   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14236                                                 Message->getReceiverInterface(),
14237                                                 NSAPI::ClassId_NSMutableArray);
14238   if (!IsMutableArray) {
14239     return None;
14240   }
14241 
14242   Selector Sel = Message->getSelector();
14243 
14244   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14245     S.NSAPIObj->getNSArrayMethodKind(Sel);
14246   if (!MKOpt) {
14247     return None;
14248   }
14249 
14250   NSAPI::NSArrayMethodKind MK = *MKOpt;
14251 
14252   switch (MK) {
14253     case NSAPI::NSMutableArr_addObject:
14254     case NSAPI::NSMutableArr_insertObjectAtIndex:
14255     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14256       return 0;
14257     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14258       return 1;
14259 
14260     default:
14261       return None;
14262   }
14263 
14264   return None;
14265 }
14266 
14267 static
14268 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14269                                                   ObjCMessageExpr *Message) {
14270   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14271                                             Message->getReceiverInterface(),
14272                                             NSAPI::ClassId_NSMutableDictionary);
14273   if (!IsMutableDictionary) {
14274     return None;
14275   }
14276 
14277   Selector Sel = Message->getSelector();
14278 
14279   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14280     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14281   if (!MKOpt) {
14282     return None;
14283   }
14284 
14285   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14286 
14287   switch (MK) {
14288     case NSAPI::NSMutableDict_setObjectForKey:
14289     case NSAPI::NSMutableDict_setValueForKey:
14290     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14291       return 0;
14292 
14293     default:
14294       return None;
14295   }
14296 
14297   return None;
14298 }
14299 
14300 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14301   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14302                                                 Message->getReceiverInterface(),
14303                                                 NSAPI::ClassId_NSMutableSet);
14304 
14305   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14306                                             Message->getReceiverInterface(),
14307                                             NSAPI::ClassId_NSMutableOrderedSet);
14308   if (!IsMutableSet && !IsMutableOrderedSet) {
14309     return None;
14310   }
14311 
14312   Selector Sel = Message->getSelector();
14313 
14314   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14315   if (!MKOpt) {
14316     return None;
14317   }
14318 
14319   NSAPI::NSSetMethodKind MK = *MKOpt;
14320 
14321   switch (MK) {
14322     case NSAPI::NSMutableSet_addObject:
14323     case NSAPI::NSOrderedSet_setObjectAtIndex:
14324     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14325     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14326       return 0;
14327     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14328       return 1;
14329   }
14330 
14331   return None;
14332 }
14333 
14334 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14335   if (!Message->isInstanceMessage()) {
14336     return;
14337   }
14338 
14339   Optional<int> ArgOpt;
14340 
14341   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14342       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14343       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14344     return;
14345   }
14346 
14347   int ArgIndex = *ArgOpt;
14348 
14349   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14350   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14351     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14352   }
14353 
14354   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14355     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14356       if (ArgRE->isObjCSelfExpr()) {
14357         Diag(Message->getSourceRange().getBegin(),
14358              diag::warn_objc_circular_container)
14359           << ArgRE->getDecl() << StringRef("'super'");
14360       }
14361     }
14362   } else {
14363     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14364 
14365     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14366       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14367     }
14368 
14369     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14370       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14371         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14372           ValueDecl *Decl = ReceiverRE->getDecl();
14373           Diag(Message->getSourceRange().getBegin(),
14374                diag::warn_objc_circular_container)
14375             << Decl << Decl;
14376           if (!ArgRE->isObjCSelfExpr()) {
14377             Diag(Decl->getLocation(),
14378                  diag::note_objc_circular_container_declared_here)
14379               << Decl;
14380           }
14381         }
14382       }
14383     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14384       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14385         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14386           ObjCIvarDecl *Decl = IvarRE->getDecl();
14387           Diag(Message->getSourceRange().getBegin(),
14388                diag::warn_objc_circular_container)
14389             << Decl << Decl;
14390           Diag(Decl->getLocation(),
14391                diag::note_objc_circular_container_declared_here)
14392             << Decl;
14393         }
14394       }
14395     }
14396   }
14397 }
14398 
14399 /// Check a message send to see if it's likely to cause a retain cycle.
14400 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14401   // Only check instance methods whose selector looks like a setter.
14402   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14403     return;
14404 
14405   // Try to find a variable that the receiver is strongly owned by.
14406   RetainCycleOwner owner;
14407   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14408     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14409       return;
14410   } else {
14411     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14412     owner.Variable = getCurMethodDecl()->getSelfDecl();
14413     owner.Loc = msg->getSuperLoc();
14414     owner.Range = msg->getSuperLoc();
14415   }
14416 
14417   // Check whether the receiver is captured by any of the arguments.
14418   const ObjCMethodDecl *MD = msg->getMethodDecl();
14419   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14420     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14421       // noescape blocks should not be retained by the method.
14422       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14423         continue;
14424       return diagnoseRetainCycle(*this, capturer, owner);
14425     }
14426   }
14427 }
14428 
14429 /// Check a property assign to see if it's likely to cause a retain cycle.
14430 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14431   RetainCycleOwner owner;
14432   if (!findRetainCycleOwner(*this, receiver, owner))
14433     return;
14434 
14435   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14436     diagnoseRetainCycle(*this, capturer, owner);
14437 }
14438 
14439 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14440   RetainCycleOwner Owner;
14441   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14442     return;
14443 
14444   // Because we don't have an expression for the variable, we have to set the
14445   // location explicitly here.
14446   Owner.Loc = Var->getLocation();
14447   Owner.Range = Var->getSourceRange();
14448 
14449   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14450     diagnoseRetainCycle(*this, Capturer, Owner);
14451 }
14452 
14453 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14454                                      Expr *RHS, bool isProperty) {
14455   // Check if RHS is an Objective-C object literal, which also can get
14456   // immediately zapped in a weak reference.  Note that we explicitly
14457   // allow ObjCStringLiterals, since those are designed to never really die.
14458   RHS = RHS->IgnoreParenImpCasts();
14459 
14460   // This enum needs to match with the 'select' in
14461   // warn_objc_arc_literal_assign (off-by-1).
14462   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14463   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14464     return false;
14465 
14466   S.Diag(Loc, diag::warn_arc_literal_assign)
14467     << (unsigned) Kind
14468     << (isProperty ? 0 : 1)
14469     << RHS->getSourceRange();
14470 
14471   return true;
14472 }
14473 
14474 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14475                                     Qualifiers::ObjCLifetime LT,
14476                                     Expr *RHS, bool isProperty) {
14477   // Strip off any implicit cast added to get to the one ARC-specific.
14478   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14479     if (cast->getCastKind() == CK_ARCConsumeObject) {
14480       S.Diag(Loc, diag::warn_arc_retained_assign)
14481         << (LT == Qualifiers::OCL_ExplicitNone)
14482         << (isProperty ? 0 : 1)
14483         << RHS->getSourceRange();
14484       return true;
14485     }
14486     RHS = cast->getSubExpr();
14487   }
14488 
14489   if (LT == Qualifiers::OCL_Weak &&
14490       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14491     return true;
14492 
14493   return false;
14494 }
14495 
14496 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14497                               QualType LHS, Expr *RHS) {
14498   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14499 
14500   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14501     return false;
14502 
14503   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14504     return true;
14505 
14506   return false;
14507 }
14508 
14509 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14510                               Expr *LHS, Expr *RHS) {
14511   QualType LHSType;
14512   // PropertyRef on LHS type need be directly obtained from
14513   // its declaration as it has a PseudoType.
14514   ObjCPropertyRefExpr *PRE
14515     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14516   if (PRE && !PRE->isImplicitProperty()) {
14517     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14518     if (PD)
14519       LHSType = PD->getType();
14520   }
14521 
14522   if (LHSType.isNull())
14523     LHSType = LHS->getType();
14524 
14525   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14526 
14527   if (LT == Qualifiers::OCL_Weak) {
14528     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14529       getCurFunction()->markSafeWeakUse(LHS);
14530   }
14531 
14532   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14533     return;
14534 
14535   // FIXME. Check for other life times.
14536   if (LT != Qualifiers::OCL_None)
14537     return;
14538 
14539   if (PRE) {
14540     if (PRE->isImplicitProperty())
14541       return;
14542     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14543     if (!PD)
14544       return;
14545 
14546     unsigned Attributes = PD->getPropertyAttributes();
14547     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14548       // when 'assign' attribute was not explicitly specified
14549       // by user, ignore it and rely on property type itself
14550       // for lifetime info.
14551       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14552       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14553           LHSType->isObjCRetainableType())
14554         return;
14555 
14556       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14557         if (cast->getCastKind() == CK_ARCConsumeObject) {
14558           Diag(Loc, diag::warn_arc_retained_property_assign)
14559           << RHS->getSourceRange();
14560           return;
14561         }
14562         RHS = cast->getSubExpr();
14563       }
14564     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14565       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14566         return;
14567     }
14568   }
14569 }
14570 
14571 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14572 
14573 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14574                                         SourceLocation StmtLoc,
14575                                         const NullStmt *Body) {
14576   // Do not warn if the body is a macro that expands to nothing, e.g:
14577   //
14578   // #define CALL(x)
14579   // if (condition)
14580   //   CALL(0);
14581   if (Body->hasLeadingEmptyMacro())
14582     return false;
14583 
14584   // Get line numbers of statement and body.
14585   bool StmtLineInvalid;
14586   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14587                                                       &StmtLineInvalid);
14588   if (StmtLineInvalid)
14589     return false;
14590 
14591   bool BodyLineInvalid;
14592   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14593                                                       &BodyLineInvalid);
14594   if (BodyLineInvalid)
14595     return false;
14596 
14597   // Warn if null statement and body are on the same line.
14598   if (StmtLine != BodyLine)
14599     return false;
14600 
14601   return true;
14602 }
14603 
14604 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14605                                  const Stmt *Body,
14606                                  unsigned DiagID) {
14607   // Since this is a syntactic check, don't emit diagnostic for template
14608   // instantiations, this just adds noise.
14609   if (CurrentInstantiationScope)
14610     return;
14611 
14612   // The body should be a null statement.
14613   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14614   if (!NBody)
14615     return;
14616 
14617   // Do the usual checks.
14618   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14619     return;
14620 
14621   Diag(NBody->getSemiLoc(), DiagID);
14622   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14623 }
14624 
14625 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14626                                  const Stmt *PossibleBody) {
14627   assert(!CurrentInstantiationScope); // Ensured by caller
14628 
14629   SourceLocation StmtLoc;
14630   const Stmt *Body;
14631   unsigned DiagID;
14632   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14633     StmtLoc = FS->getRParenLoc();
14634     Body = FS->getBody();
14635     DiagID = diag::warn_empty_for_body;
14636   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14637     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14638     Body = WS->getBody();
14639     DiagID = diag::warn_empty_while_body;
14640   } else
14641     return; // Neither `for' nor `while'.
14642 
14643   // The body should be a null statement.
14644   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14645   if (!NBody)
14646     return;
14647 
14648   // Skip expensive checks if diagnostic is disabled.
14649   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14650     return;
14651 
14652   // Do the usual checks.
14653   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14654     return;
14655 
14656   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14657   // noise level low, emit diagnostics only if for/while is followed by a
14658   // CompoundStmt, e.g.:
14659   //    for (int i = 0; i < n; i++);
14660   //    {
14661   //      a(i);
14662   //    }
14663   // or if for/while is followed by a statement with more indentation
14664   // than for/while itself:
14665   //    for (int i = 0; i < n; i++);
14666   //      a(i);
14667   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14668   if (!ProbableTypo) {
14669     bool BodyColInvalid;
14670     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14671         PossibleBody->getBeginLoc(), &BodyColInvalid);
14672     if (BodyColInvalid)
14673       return;
14674 
14675     bool StmtColInvalid;
14676     unsigned StmtCol =
14677         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14678     if (StmtColInvalid)
14679       return;
14680 
14681     if (BodyCol > StmtCol)
14682       ProbableTypo = true;
14683   }
14684 
14685   if (ProbableTypo) {
14686     Diag(NBody->getSemiLoc(), DiagID);
14687     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14688   }
14689 }
14690 
14691 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14692 
14693 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14694 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14695                              SourceLocation OpLoc) {
14696   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14697     return;
14698 
14699   if (inTemplateInstantiation())
14700     return;
14701 
14702   // Strip parens and casts away.
14703   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14704   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14705 
14706   // Check for a call expression
14707   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14708   if (!CE || CE->getNumArgs() != 1)
14709     return;
14710 
14711   // Check for a call to std::move
14712   if (!CE->isCallToStdMove())
14713     return;
14714 
14715   // Get argument from std::move
14716   RHSExpr = CE->getArg(0);
14717 
14718   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14719   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14720 
14721   // Two DeclRefExpr's, check that the decls are the same.
14722   if (LHSDeclRef && RHSDeclRef) {
14723     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14724       return;
14725     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14726         RHSDeclRef->getDecl()->getCanonicalDecl())
14727       return;
14728 
14729     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14730                                         << LHSExpr->getSourceRange()
14731                                         << RHSExpr->getSourceRange();
14732     return;
14733   }
14734 
14735   // Member variables require a different approach to check for self moves.
14736   // MemberExpr's are the same if every nested MemberExpr refers to the same
14737   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14738   // the base Expr's are CXXThisExpr's.
14739   const Expr *LHSBase = LHSExpr;
14740   const Expr *RHSBase = RHSExpr;
14741   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14742   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14743   if (!LHSME || !RHSME)
14744     return;
14745 
14746   while (LHSME && RHSME) {
14747     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14748         RHSME->getMemberDecl()->getCanonicalDecl())
14749       return;
14750 
14751     LHSBase = LHSME->getBase();
14752     RHSBase = RHSME->getBase();
14753     LHSME = dyn_cast<MemberExpr>(LHSBase);
14754     RHSME = dyn_cast<MemberExpr>(RHSBase);
14755   }
14756 
14757   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14758   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14759   if (LHSDeclRef && RHSDeclRef) {
14760     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14761       return;
14762     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14763         RHSDeclRef->getDecl()->getCanonicalDecl())
14764       return;
14765 
14766     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14767                                         << LHSExpr->getSourceRange()
14768                                         << RHSExpr->getSourceRange();
14769     return;
14770   }
14771 
14772   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14773     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14774                                         << LHSExpr->getSourceRange()
14775                                         << RHSExpr->getSourceRange();
14776 }
14777 
14778 //===--- Layout compatibility ----------------------------------------------//
14779 
14780 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14781 
14782 /// Check if two enumeration types are layout-compatible.
14783 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14784   // C++11 [dcl.enum] p8:
14785   // Two enumeration types are layout-compatible if they have the same
14786   // underlying type.
14787   return ED1->isComplete() && ED2->isComplete() &&
14788          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14789 }
14790 
14791 /// Check if two fields are layout-compatible.
14792 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14793                                FieldDecl *Field2) {
14794   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14795     return false;
14796 
14797   if (Field1->isBitField() != Field2->isBitField())
14798     return false;
14799 
14800   if (Field1->isBitField()) {
14801     // Make sure that the bit-fields are the same length.
14802     unsigned Bits1 = Field1->getBitWidthValue(C);
14803     unsigned Bits2 = Field2->getBitWidthValue(C);
14804 
14805     if (Bits1 != Bits2)
14806       return false;
14807   }
14808 
14809   return true;
14810 }
14811 
14812 /// Check if two standard-layout structs are layout-compatible.
14813 /// (C++11 [class.mem] p17)
14814 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14815                                      RecordDecl *RD2) {
14816   // If both records are C++ classes, check that base classes match.
14817   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14818     // If one of records is a CXXRecordDecl we are in C++ mode,
14819     // thus the other one is a CXXRecordDecl, too.
14820     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14821     // Check number of base classes.
14822     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14823       return false;
14824 
14825     // Check the base classes.
14826     for (CXXRecordDecl::base_class_const_iterator
14827                Base1 = D1CXX->bases_begin(),
14828            BaseEnd1 = D1CXX->bases_end(),
14829               Base2 = D2CXX->bases_begin();
14830          Base1 != BaseEnd1;
14831          ++Base1, ++Base2) {
14832       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14833         return false;
14834     }
14835   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14836     // If only RD2 is a C++ class, it should have zero base classes.
14837     if (D2CXX->getNumBases() > 0)
14838       return false;
14839   }
14840 
14841   // Check the fields.
14842   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14843                              Field2End = RD2->field_end(),
14844                              Field1 = RD1->field_begin(),
14845                              Field1End = RD1->field_end();
14846   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14847     if (!isLayoutCompatible(C, *Field1, *Field2))
14848       return false;
14849   }
14850   if (Field1 != Field1End || Field2 != Field2End)
14851     return false;
14852 
14853   return true;
14854 }
14855 
14856 /// Check if two standard-layout unions are layout-compatible.
14857 /// (C++11 [class.mem] p18)
14858 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14859                                     RecordDecl *RD2) {
14860   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14861   for (auto *Field2 : RD2->fields())
14862     UnmatchedFields.insert(Field2);
14863 
14864   for (auto *Field1 : RD1->fields()) {
14865     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14866         I = UnmatchedFields.begin(),
14867         E = UnmatchedFields.end();
14868 
14869     for ( ; I != E; ++I) {
14870       if (isLayoutCompatible(C, Field1, *I)) {
14871         bool Result = UnmatchedFields.erase(*I);
14872         (void) Result;
14873         assert(Result);
14874         break;
14875       }
14876     }
14877     if (I == E)
14878       return false;
14879   }
14880 
14881   return UnmatchedFields.empty();
14882 }
14883 
14884 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14885                                RecordDecl *RD2) {
14886   if (RD1->isUnion() != RD2->isUnion())
14887     return false;
14888 
14889   if (RD1->isUnion())
14890     return isLayoutCompatibleUnion(C, RD1, RD2);
14891   else
14892     return isLayoutCompatibleStruct(C, RD1, RD2);
14893 }
14894 
14895 /// Check if two types are layout-compatible in C++11 sense.
14896 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14897   if (T1.isNull() || T2.isNull())
14898     return false;
14899 
14900   // C++11 [basic.types] p11:
14901   // If two types T1 and T2 are the same type, then T1 and T2 are
14902   // layout-compatible types.
14903   if (C.hasSameType(T1, T2))
14904     return true;
14905 
14906   T1 = T1.getCanonicalType().getUnqualifiedType();
14907   T2 = T2.getCanonicalType().getUnqualifiedType();
14908 
14909   const Type::TypeClass TC1 = T1->getTypeClass();
14910   const Type::TypeClass TC2 = T2->getTypeClass();
14911 
14912   if (TC1 != TC2)
14913     return false;
14914 
14915   if (TC1 == Type::Enum) {
14916     return isLayoutCompatible(C,
14917                               cast<EnumType>(T1)->getDecl(),
14918                               cast<EnumType>(T2)->getDecl());
14919   } else if (TC1 == Type::Record) {
14920     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14921       return false;
14922 
14923     return isLayoutCompatible(C,
14924                               cast<RecordType>(T1)->getDecl(),
14925                               cast<RecordType>(T2)->getDecl());
14926   }
14927 
14928   return false;
14929 }
14930 
14931 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14932 
14933 /// Given a type tag expression find the type tag itself.
14934 ///
14935 /// \param TypeExpr Type tag expression, as it appears in user's code.
14936 ///
14937 /// \param VD Declaration of an identifier that appears in a type tag.
14938 ///
14939 /// \param MagicValue Type tag magic value.
14940 ///
14941 /// \param isConstantEvaluated wether the evalaution should be performed in
14942 
14943 /// constant context.
14944 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14945                             const ValueDecl **VD, uint64_t *MagicValue,
14946                             bool isConstantEvaluated) {
14947   while(true) {
14948     if (!TypeExpr)
14949       return false;
14950 
14951     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14952 
14953     switch (TypeExpr->getStmtClass()) {
14954     case Stmt::UnaryOperatorClass: {
14955       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14956       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14957         TypeExpr = UO->getSubExpr();
14958         continue;
14959       }
14960       return false;
14961     }
14962 
14963     case Stmt::DeclRefExprClass: {
14964       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14965       *VD = DRE->getDecl();
14966       return true;
14967     }
14968 
14969     case Stmt::IntegerLiteralClass: {
14970       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14971       llvm::APInt MagicValueAPInt = IL->getValue();
14972       if (MagicValueAPInt.getActiveBits() <= 64) {
14973         *MagicValue = MagicValueAPInt.getZExtValue();
14974         return true;
14975       } else
14976         return false;
14977     }
14978 
14979     case Stmt::BinaryConditionalOperatorClass:
14980     case Stmt::ConditionalOperatorClass: {
14981       const AbstractConditionalOperator *ACO =
14982           cast<AbstractConditionalOperator>(TypeExpr);
14983       bool Result;
14984       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14985                                                      isConstantEvaluated)) {
14986         if (Result)
14987           TypeExpr = ACO->getTrueExpr();
14988         else
14989           TypeExpr = ACO->getFalseExpr();
14990         continue;
14991       }
14992       return false;
14993     }
14994 
14995     case Stmt::BinaryOperatorClass: {
14996       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14997       if (BO->getOpcode() == BO_Comma) {
14998         TypeExpr = BO->getRHS();
14999         continue;
15000       }
15001       return false;
15002     }
15003 
15004     default:
15005       return false;
15006     }
15007   }
15008 }
15009 
15010 /// Retrieve the C type corresponding to type tag TypeExpr.
15011 ///
15012 /// \param TypeExpr Expression that specifies a type tag.
15013 ///
15014 /// \param MagicValues Registered magic values.
15015 ///
15016 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15017 ///        kind.
15018 ///
15019 /// \param TypeInfo Information about the corresponding C type.
15020 ///
15021 /// \param isConstantEvaluated wether the evalaution should be performed in
15022 /// constant context.
15023 ///
15024 /// \returns true if the corresponding C type was found.
15025 static bool GetMatchingCType(
15026     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15027     const ASTContext &Ctx,
15028     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15029         *MagicValues,
15030     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15031     bool isConstantEvaluated) {
15032   FoundWrongKind = false;
15033 
15034   // Variable declaration that has type_tag_for_datatype attribute.
15035   const ValueDecl *VD = nullptr;
15036 
15037   uint64_t MagicValue;
15038 
15039   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15040     return false;
15041 
15042   if (VD) {
15043     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15044       if (I->getArgumentKind() != ArgumentKind) {
15045         FoundWrongKind = true;
15046         return false;
15047       }
15048       TypeInfo.Type = I->getMatchingCType();
15049       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15050       TypeInfo.MustBeNull = I->getMustBeNull();
15051       return true;
15052     }
15053     return false;
15054   }
15055 
15056   if (!MagicValues)
15057     return false;
15058 
15059   llvm::DenseMap<Sema::TypeTagMagicValue,
15060                  Sema::TypeTagData>::const_iterator I =
15061       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15062   if (I == MagicValues->end())
15063     return false;
15064 
15065   TypeInfo = I->second;
15066   return true;
15067 }
15068 
15069 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15070                                       uint64_t MagicValue, QualType Type,
15071                                       bool LayoutCompatible,
15072                                       bool MustBeNull) {
15073   if (!TypeTagForDatatypeMagicValues)
15074     TypeTagForDatatypeMagicValues.reset(
15075         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15076 
15077   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15078   (*TypeTagForDatatypeMagicValues)[Magic] =
15079       TypeTagData(Type, LayoutCompatible, MustBeNull);
15080 }
15081 
15082 static bool IsSameCharType(QualType T1, QualType T2) {
15083   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15084   if (!BT1)
15085     return false;
15086 
15087   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15088   if (!BT2)
15089     return false;
15090 
15091   BuiltinType::Kind T1Kind = BT1->getKind();
15092   BuiltinType::Kind T2Kind = BT2->getKind();
15093 
15094   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15095          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15096          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15097          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15098 }
15099 
15100 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15101                                     const ArrayRef<const Expr *> ExprArgs,
15102                                     SourceLocation CallSiteLoc) {
15103   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15104   bool IsPointerAttr = Attr->getIsPointer();
15105 
15106   // Retrieve the argument representing the 'type_tag'.
15107   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15108   if (TypeTagIdxAST >= ExprArgs.size()) {
15109     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15110         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15111     return;
15112   }
15113   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15114   bool FoundWrongKind;
15115   TypeTagData TypeInfo;
15116   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15117                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15118                         TypeInfo, isConstantEvaluated())) {
15119     if (FoundWrongKind)
15120       Diag(TypeTagExpr->getExprLoc(),
15121            diag::warn_type_tag_for_datatype_wrong_kind)
15122         << TypeTagExpr->getSourceRange();
15123     return;
15124   }
15125 
15126   // Retrieve the argument representing the 'arg_idx'.
15127   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15128   if (ArgumentIdxAST >= ExprArgs.size()) {
15129     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15130         << 1 << Attr->getArgumentIdx().getSourceIndex();
15131     return;
15132   }
15133   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15134   if (IsPointerAttr) {
15135     // Skip implicit cast of pointer to `void *' (as a function argument).
15136     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15137       if (ICE->getType()->isVoidPointerType() &&
15138           ICE->getCastKind() == CK_BitCast)
15139         ArgumentExpr = ICE->getSubExpr();
15140   }
15141   QualType ArgumentType = ArgumentExpr->getType();
15142 
15143   // Passing a `void*' pointer shouldn't trigger a warning.
15144   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15145     return;
15146 
15147   if (TypeInfo.MustBeNull) {
15148     // Type tag with matching void type requires a null pointer.
15149     if (!ArgumentExpr->isNullPointerConstant(Context,
15150                                              Expr::NPC_ValueDependentIsNotNull)) {
15151       Diag(ArgumentExpr->getExprLoc(),
15152            diag::warn_type_safety_null_pointer_required)
15153           << ArgumentKind->getName()
15154           << ArgumentExpr->getSourceRange()
15155           << TypeTagExpr->getSourceRange();
15156     }
15157     return;
15158   }
15159 
15160   QualType RequiredType = TypeInfo.Type;
15161   if (IsPointerAttr)
15162     RequiredType = Context.getPointerType(RequiredType);
15163 
15164   bool mismatch = false;
15165   if (!TypeInfo.LayoutCompatible) {
15166     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15167 
15168     // C++11 [basic.fundamental] p1:
15169     // Plain char, signed char, and unsigned char are three distinct types.
15170     //
15171     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15172     // char' depending on the current char signedness mode.
15173     if (mismatch)
15174       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15175                                            RequiredType->getPointeeType())) ||
15176           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15177         mismatch = false;
15178   } else
15179     if (IsPointerAttr)
15180       mismatch = !isLayoutCompatible(Context,
15181                                      ArgumentType->getPointeeType(),
15182                                      RequiredType->getPointeeType());
15183     else
15184       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15185 
15186   if (mismatch)
15187     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15188         << ArgumentType << ArgumentKind
15189         << TypeInfo.LayoutCompatible << RequiredType
15190         << ArgumentExpr->getSourceRange()
15191         << TypeTagExpr->getSourceRange();
15192 }
15193 
15194 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15195                                          CharUnits Alignment) {
15196   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15197 }
15198 
15199 void Sema::DiagnoseMisalignedMembers() {
15200   for (MisalignedMember &m : MisalignedMembers) {
15201     const NamedDecl *ND = m.RD;
15202     if (ND->getName().empty()) {
15203       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15204         ND = TD;
15205     }
15206     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15207         << m.MD << ND << m.E->getSourceRange();
15208   }
15209   MisalignedMembers.clear();
15210 }
15211 
15212 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15213   E = E->IgnoreParens();
15214   if (!T->isPointerType() && !T->isIntegerType())
15215     return;
15216   if (isa<UnaryOperator>(E) &&
15217       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15218     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15219     if (isa<MemberExpr>(Op)) {
15220       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15221       if (MA != MisalignedMembers.end() &&
15222           (T->isIntegerType() ||
15223            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15224                                    Context.getTypeAlignInChars(
15225                                        T->getPointeeType()) <= MA->Alignment))))
15226         MisalignedMembers.erase(MA);
15227     }
15228   }
15229 }
15230 
15231 void Sema::RefersToMemberWithReducedAlignment(
15232     Expr *E,
15233     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15234         Action) {
15235   const auto *ME = dyn_cast<MemberExpr>(E);
15236   if (!ME)
15237     return;
15238 
15239   // No need to check expressions with an __unaligned-qualified type.
15240   if (E->getType().getQualifiers().hasUnaligned())
15241     return;
15242 
15243   // For a chain of MemberExpr like "a.b.c.d" this list
15244   // will keep FieldDecl's like [d, c, b].
15245   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15246   const MemberExpr *TopME = nullptr;
15247   bool AnyIsPacked = false;
15248   do {
15249     QualType BaseType = ME->getBase()->getType();
15250     if (BaseType->isDependentType())
15251       return;
15252     if (ME->isArrow())
15253       BaseType = BaseType->getPointeeType();
15254     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15255     if (RD->isInvalidDecl())
15256       return;
15257 
15258     ValueDecl *MD = ME->getMemberDecl();
15259     auto *FD = dyn_cast<FieldDecl>(MD);
15260     // We do not care about non-data members.
15261     if (!FD || FD->isInvalidDecl())
15262       return;
15263 
15264     AnyIsPacked =
15265         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15266     ReverseMemberChain.push_back(FD);
15267 
15268     TopME = ME;
15269     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15270   } while (ME);
15271   assert(TopME && "We did not compute a topmost MemberExpr!");
15272 
15273   // Not the scope of this diagnostic.
15274   if (!AnyIsPacked)
15275     return;
15276 
15277   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15278   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15279   // TODO: The innermost base of the member expression may be too complicated.
15280   // For now, just disregard these cases. This is left for future
15281   // improvement.
15282   if (!DRE && !isa<CXXThisExpr>(TopBase))
15283       return;
15284 
15285   // Alignment expected by the whole expression.
15286   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15287 
15288   // No need to do anything else with this case.
15289   if (ExpectedAlignment.isOne())
15290     return;
15291 
15292   // Synthesize offset of the whole access.
15293   CharUnits Offset;
15294   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15295        I++) {
15296     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15297   }
15298 
15299   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15300   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15301       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15302 
15303   // The base expression of the innermost MemberExpr may give
15304   // stronger guarantees than the class containing the member.
15305   if (DRE && !TopME->isArrow()) {
15306     const ValueDecl *VD = DRE->getDecl();
15307     if (!VD->getType()->isReferenceType())
15308       CompleteObjectAlignment =
15309           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15310   }
15311 
15312   // Check if the synthesized offset fulfills the alignment.
15313   if (Offset % ExpectedAlignment != 0 ||
15314       // It may fulfill the offset it but the effective alignment may still be
15315       // lower than the expected expression alignment.
15316       CompleteObjectAlignment < ExpectedAlignment) {
15317     // If this happens, we want to determine a sensible culprit of this.
15318     // Intuitively, watching the chain of member expressions from right to
15319     // left, we start with the required alignment (as required by the field
15320     // type) but some packed attribute in that chain has reduced the alignment.
15321     // It may happen that another packed structure increases it again. But if
15322     // we are here such increase has not been enough. So pointing the first
15323     // FieldDecl that either is packed or else its RecordDecl is,
15324     // seems reasonable.
15325     FieldDecl *FD = nullptr;
15326     CharUnits Alignment;
15327     for (FieldDecl *FDI : ReverseMemberChain) {
15328       if (FDI->hasAttr<PackedAttr>() ||
15329           FDI->getParent()->hasAttr<PackedAttr>()) {
15330         FD = FDI;
15331         Alignment = std::min(
15332             Context.getTypeAlignInChars(FD->getType()),
15333             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15334         break;
15335       }
15336     }
15337     assert(FD && "We did not find a packed FieldDecl!");
15338     Action(E, FD->getParent(), FD, Alignment);
15339   }
15340 }
15341 
15342 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15343   using namespace std::placeholders;
15344 
15345   RefersToMemberWithReducedAlignment(
15346       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15347                      _2, _3, _4));
15348 }
15349 
15350 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15351                                             ExprResult CallResult) {
15352   if (checkArgCount(*this, TheCall, 1))
15353     return ExprError();
15354 
15355   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15356   if (MatrixArg.isInvalid())
15357     return MatrixArg;
15358   Expr *Matrix = MatrixArg.get();
15359 
15360   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15361   if (!MType) {
15362     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15363     return ExprError();
15364   }
15365 
15366   // Create returned matrix type by swapping rows and columns of the argument
15367   // matrix type.
15368   QualType ResultType = Context.getConstantMatrixType(
15369       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15370 
15371   // Change the return type to the type of the returned matrix.
15372   TheCall->setType(ResultType);
15373 
15374   // Update call argument to use the possibly converted matrix argument.
15375   TheCall->setArg(0, Matrix);
15376   return CallResult;
15377 }
15378 
15379 // Get and verify the matrix dimensions.
15380 static llvm::Optional<unsigned>
15381 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15382   llvm::APSInt Value(64);
15383   SourceLocation ErrorPos;
15384   if (!Expr->isIntegerConstantExpr(Value, S.Context, &ErrorPos)) {
15385     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15386         << Name;
15387     return {};
15388   }
15389   uint64_t Dim = Value.getZExtValue();
15390   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15391     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15392         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15393     return {};
15394   }
15395   return Dim;
15396 }
15397 
15398 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15399                                                   ExprResult CallResult) {
15400   if (!getLangOpts().MatrixTypes) {
15401     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15402     return ExprError();
15403   }
15404 
15405   if (checkArgCount(*this, TheCall, 4))
15406     return ExprError();
15407 
15408   unsigned PtrArgIdx = 0;
15409   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15410   Expr *RowsExpr = TheCall->getArg(1);
15411   Expr *ColumnsExpr = TheCall->getArg(2);
15412   Expr *StrideExpr = TheCall->getArg(3);
15413 
15414   bool ArgError = false;
15415 
15416   // Check pointer argument.
15417   {
15418     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15419     if (PtrConv.isInvalid())
15420       return PtrConv;
15421     PtrExpr = PtrConv.get();
15422     TheCall->setArg(0, PtrExpr);
15423     if (PtrExpr->isTypeDependent()) {
15424       TheCall->setType(Context.DependentTy);
15425       return TheCall;
15426     }
15427   }
15428 
15429   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15430   QualType ElementTy;
15431   if (!PtrTy) {
15432     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15433         << PtrArgIdx + 1;
15434     ArgError = true;
15435   } else {
15436     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15437 
15438     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15439       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15440           << PtrArgIdx + 1;
15441       ArgError = true;
15442     }
15443   }
15444 
15445   // Apply default Lvalue conversions and convert the expression to size_t.
15446   auto ApplyArgumentConversions = [this](Expr *E) {
15447     ExprResult Conv = DefaultLvalueConversion(E);
15448     if (Conv.isInvalid())
15449       return Conv;
15450 
15451     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15452   };
15453 
15454   // Apply conversion to row and column expressions.
15455   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15456   if (!RowsConv.isInvalid()) {
15457     RowsExpr = RowsConv.get();
15458     TheCall->setArg(1, RowsExpr);
15459   } else
15460     RowsExpr = nullptr;
15461 
15462   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15463   if (!ColumnsConv.isInvalid()) {
15464     ColumnsExpr = ColumnsConv.get();
15465     TheCall->setArg(2, ColumnsExpr);
15466   } else
15467     ColumnsExpr = nullptr;
15468 
15469   // If any any part of the result matrix type is still pending, just use
15470   // Context.DependentTy, until all parts are resolved.
15471   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15472       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15473     TheCall->setType(Context.DependentTy);
15474     return CallResult;
15475   }
15476 
15477   // Check row and column dimenions.
15478   llvm::Optional<unsigned> MaybeRows;
15479   if (RowsExpr)
15480     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15481 
15482   llvm::Optional<unsigned> MaybeColumns;
15483   if (ColumnsExpr)
15484     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15485 
15486   // Check stride argument.
15487   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15488   if (StrideConv.isInvalid())
15489     return ExprError();
15490   StrideExpr = StrideConv.get();
15491   TheCall->setArg(3, StrideExpr);
15492 
15493   llvm::APSInt Value(64);
15494   if (MaybeRows && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15495     uint64_t Stride = Value.getZExtValue();
15496     if (Stride < *MaybeRows) {
15497       Diag(StrideExpr->getBeginLoc(),
15498            diag::err_builtin_matrix_stride_too_small);
15499       ArgError = true;
15500     }
15501   }
15502 
15503   if (ArgError || !MaybeRows || !MaybeColumns)
15504     return ExprError();
15505 
15506   TheCall->setType(
15507       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15508   return CallResult;
15509 }
15510 
15511 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15512                                                    ExprResult CallResult) {
15513   if (checkArgCount(*this, TheCall, 3))
15514     return ExprError();
15515 
15516   unsigned PtrArgIdx = 1;
15517   Expr *MatrixExpr = TheCall->getArg(0);
15518   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15519   Expr *StrideExpr = TheCall->getArg(2);
15520 
15521   bool ArgError = false;
15522 
15523   {
15524     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15525     if (MatrixConv.isInvalid())
15526       return MatrixConv;
15527     MatrixExpr = MatrixConv.get();
15528     TheCall->setArg(0, MatrixExpr);
15529   }
15530   if (MatrixExpr->isTypeDependent()) {
15531     TheCall->setType(Context.DependentTy);
15532     return TheCall;
15533   }
15534 
15535   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15536   if (!MatrixTy) {
15537     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15538     ArgError = true;
15539   }
15540 
15541   {
15542     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15543     if (PtrConv.isInvalid())
15544       return PtrConv;
15545     PtrExpr = PtrConv.get();
15546     TheCall->setArg(1, PtrExpr);
15547     if (PtrExpr->isTypeDependent()) {
15548       TheCall->setType(Context.DependentTy);
15549       return TheCall;
15550     }
15551   }
15552 
15553   // Check pointer argument.
15554   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15555   if (!PtrTy) {
15556     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15557         << PtrArgIdx + 1;
15558     ArgError = true;
15559   } else {
15560     QualType ElementTy = PtrTy->getPointeeType();
15561     if (ElementTy.isConstQualified()) {
15562       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15563       ArgError = true;
15564     }
15565     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15566     if (MatrixTy &&
15567         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15568       Diag(PtrExpr->getBeginLoc(),
15569            diag::err_builtin_matrix_pointer_arg_mismatch)
15570           << ElementTy << MatrixTy->getElementType();
15571       ArgError = true;
15572     }
15573   }
15574 
15575   // Apply default Lvalue conversions and convert the stride expression to
15576   // size_t.
15577   {
15578     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15579     if (StrideConv.isInvalid())
15580       return StrideConv;
15581 
15582     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15583     if (StrideConv.isInvalid())
15584       return StrideConv;
15585     StrideExpr = StrideConv.get();
15586     TheCall->setArg(2, StrideExpr);
15587   }
15588 
15589   // Check stride argument.
15590   llvm::APSInt Value(64);
15591   if (MatrixTy && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15592     uint64_t Stride = Value.getZExtValue();
15593     if (Stride < MatrixTy->getNumRows()) {
15594       Diag(StrideExpr->getBeginLoc(),
15595            diag::err_builtin_matrix_stride_too_small);
15596       ArgError = true;
15597     }
15598   }
15599 
15600   if (ArgError)
15601     return ExprError();
15602 
15603   return CallResult;
15604 }
15605