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/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/SaveAndRestore.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116            << 0 /*function call*/ << desiredArgCount << argCount
117            << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121                     call->getArg(argCount - 1)->getEndLoc());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139         << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148         << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 /// Check the number of arguments and set the result type to
195 /// the argument type.
196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197   if (checkArgCount(S, TheCall, 1))
198     return true;
199 
200   TheCall->setType(TheCall->getArg(0)->getType());
201   return false;
202 }
203 
204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
206 /// type (but not a function pointer) and that the alignment is a power-of-two.
207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
208   if (checkArgCount(S, TheCall, 2))
209     return true;
210 
211   clang::Expr *Source = TheCall->getArg(0);
212   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
213 
214   auto IsValidIntegerType = [](QualType Ty) {
215     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
216   };
217   QualType SrcTy = Source->getType();
218   // We should also be able to use it with arrays (but not functions!).
219   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
220     SrcTy = S.Context.getDecayedType(SrcTy);
221   }
222   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
223       SrcTy->isFunctionPointerType()) {
224     // FIXME: this is not quite the right error message since we don't allow
225     // floating point types, or member pointers.
226     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
227         << SrcTy;
228     return true;
229   }
230 
231   clang::Expr *AlignOp = TheCall->getArg(1);
232   if (!IsValidIntegerType(AlignOp->getType())) {
233     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
234         << AlignOp->getType();
235     return true;
236   }
237   Expr::EvalResult AlignResult;
238   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
239   // We can't check validity of alignment if it is type dependent.
240   if (!AlignOp->isInstantiationDependent() &&
241       AlignOp->EvaluateAsInt(AlignResult, S.Context,
242                              Expr::SE_AllowSideEffects)) {
243     llvm::APSInt AlignValue = AlignResult.Val.getInt();
244     llvm::APSInt MaxValue(
245         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
246     if (AlignValue < 1) {
247       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
248       return true;
249     }
250     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
252           << MaxValue.toString(10);
253       return true;
254     }
255     if (!AlignValue.isPowerOf2()) {
256       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
257       return true;
258     }
259     if (AlignValue == 1) {
260       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
261           << IsBooleanAlignBuiltin;
262     }
263   }
264 
265   ExprResult SrcArg = S.PerformCopyInitialization(
266       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
267       SourceLocation(), Source);
268   if (SrcArg.isInvalid())
269     return true;
270   TheCall->setArg(0, SrcArg.get());
271   ExprResult AlignArg =
272       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
273                                       S.Context, AlignOp->getType(), false),
274                                   SourceLocation(), AlignOp);
275   if (AlignArg.isInvalid())
276     return true;
277   TheCall->setArg(1, AlignArg.get());
278   // For align_up/align_down, the return type is the same as the (potentially
279   // decayed) argument type including qualifiers. For is_aligned(), the result
280   // is always bool.
281   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
282   return false;
283 }
284 
285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
286   if (checkArgCount(S, TheCall, 3))
287     return true;
288 
289   // First two arguments should be integers.
290   for (unsigned I = 0; I < 2; ++I) {
291     ExprResult Arg = TheCall->getArg(I);
292     QualType Ty = Arg.get()->getType();
293     if (!Ty->isIntegerType()) {
294       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
295           << Ty << Arg.get()->getSourceRange();
296       return true;
297     }
298     InitializedEntity Entity = InitializedEntity::InitializeParameter(
299         S.getASTContext(), Ty, /*consume*/ false);
300     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
301     if (Arg.isInvalid())
302       return true;
303     TheCall->setArg(I, Arg.get());
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 = TheCall->getArg(2);
311     QualType Ty = Arg.get()->getType();
312     const auto *PtrTy = Ty->getAs<PointerType>();
313     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
314           !PtrTy->getPointeeType().isConstQualified())) {
315       S.Diag(Arg.get()->getBeginLoc(),
316              diag::err_overflow_builtin_must_be_ptr_int)
317           << Ty << Arg.get()->getSourceRange();
318       return true;
319     }
320     InitializedEntity Entity = InitializedEntity::InitializeParameter(
321         S.getASTContext(), Ty, /*consume*/ false);
322     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
323     if (Arg.isInvalid())
324       return true;
325     TheCall->setArg(2, Arg.get());
326   }
327   return false;
328 }
329 
330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
331   if (checkArgCount(S, BuiltinCall, 2))
332     return true;
333 
334   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
335   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
336   Expr *Call = BuiltinCall->getArg(0);
337   Expr *Chain = BuiltinCall->getArg(1);
338 
339   if (Call->getStmtClass() != Stmt::CallExprClass) {
340     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
341         << Call->getSourceRange();
342     return true;
343   }
344 
345   auto CE = cast<CallExpr>(Call);
346   if (CE->getCallee()->getType()->isBlockPointerType()) {
347     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
348         << Call->getSourceRange();
349     return true;
350   }
351 
352   const Decl *TargetDecl = CE->getCalleeDecl();
353   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
354     if (FD->getBuiltinID()) {
355       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
356           << Call->getSourceRange();
357       return true;
358     }
359 
360   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
361     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
362         << Call->getSourceRange();
363     return true;
364   }
365 
366   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
367   if (ChainResult.isInvalid())
368     return true;
369   if (!ChainResult.get()->getType()->isPointerType()) {
370     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
371         << Chain->getSourceRange();
372     return true;
373   }
374 
375   QualType ReturnTy = CE->getCallReturnType(S.Context);
376   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
377   QualType BuiltinTy = S.Context.getFunctionType(
378       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
379   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
380 
381   Builtin =
382       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
383 
384   BuiltinCall->setType(CE->getType());
385   BuiltinCall->setValueKind(CE->getValueKind());
386   BuiltinCall->setObjectKind(CE->getObjectKind());
387   BuiltinCall->setCallee(Builtin);
388   BuiltinCall->setArg(1, ChainResult.get());
389 
390   return false;
391 }
392 
393 namespace {
394 
395 class EstimateSizeFormatHandler
396     : public analyze_format_string::FormatStringHandler {
397   size_t Size;
398 
399 public:
400   EstimateSizeFormatHandler(StringRef Format)
401       : Size(std::min(Format.find(0), Format.size()) +
402              1 /* null byte always written by sprintf */) {}
403 
404   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
405                              const char *, unsigned SpecifierLen) override {
406 
407     const size_t FieldWidth = computeFieldWidth(FS);
408     const size_t Precision = computePrecision(FS);
409 
410     // The actual format.
411     switch (FS.getConversionSpecifier().getKind()) {
412     // Just a char.
413     case analyze_format_string::ConversionSpecifier::cArg:
414     case analyze_format_string::ConversionSpecifier::CArg:
415       Size += std::max(FieldWidth, (size_t)1);
416       break;
417     // Just an integer.
418     case analyze_format_string::ConversionSpecifier::dArg:
419     case analyze_format_string::ConversionSpecifier::DArg:
420     case analyze_format_string::ConversionSpecifier::iArg:
421     case analyze_format_string::ConversionSpecifier::oArg:
422     case analyze_format_string::ConversionSpecifier::OArg:
423     case analyze_format_string::ConversionSpecifier::uArg:
424     case analyze_format_string::ConversionSpecifier::UArg:
425     case analyze_format_string::ConversionSpecifier::xArg:
426     case analyze_format_string::ConversionSpecifier::XArg:
427       Size += std::max(FieldWidth, Precision);
428       break;
429 
430     // %g style conversion switches between %f or %e style dynamically.
431     // %f always takes less space, so default to it.
432     case analyze_format_string::ConversionSpecifier::gArg:
433     case analyze_format_string::ConversionSpecifier::GArg:
434 
435     // Floating point number in the form '[+]ddd.ddd'.
436     case analyze_format_string::ConversionSpecifier::fArg:
437     case analyze_format_string::ConversionSpecifier::FArg:
438       Size += std::max(FieldWidth, 1 /* integer part */ +
439                                        (Precision ? 1 + Precision
440                                                   : 0) /* period + decimal */);
441       break;
442 
443     // Floating point number in the form '[-]d.ddde[+-]dd'.
444     case analyze_format_string::ConversionSpecifier::eArg:
445     case analyze_format_string::ConversionSpecifier::EArg:
446       Size +=
447           std::max(FieldWidth,
448                    1 /* integer part */ +
449                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
450                        1 /* e or E letter */ + 2 /* exponent */);
451       break;
452 
453     // Floating point number in the form '[-]0xh.hhhhp±dd'.
454     case analyze_format_string::ConversionSpecifier::aArg:
455     case analyze_format_string::ConversionSpecifier::AArg:
456       Size +=
457           std::max(FieldWidth,
458                    2 /* 0x */ + 1 /* integer part */ +
459                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
460                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
461       break;
462 
463     // Just a string.
464     case analyze_format_string::ConversionSpecifier::sArg:
465     case analyze_format_string::ConversionSpecifier::SArg:
466       Size += FieldWidth;
467       break;
468 
469     // Just a pointer in the form '0xddd'.
470     case analyze_format_string::ConversionSpecifier::pArg:
471       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
472       break;
473 
474     // A plain percent.
475     case analyze_format_string::ConversionSpecifier::PercentArg:
476       Size += 1;
477       break;
478 
479     default:
480       break;
481     }
482 
483     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
484 
485     if (FS.hasAlternativeForm()) {
486       switch (FS.getConversionSpecifier().getKind()) {
487       default:
488         break;
489       // Force a leading '0'.
490       case analyze_format_string::ConversionSpecifier::oArg:
491         Size += 1;
492         break;
493       // Force a leading '0x'.
494       case analyze_format_string::ConversionSpecifier::xArg:
495       case analyze_format_string::ConversionSpecifier::XArg:
496         Size += 2;
497         break;
498       // Force a period '.' before decimal, even if precision is 0.
499       case analyze_format_string::ConversionSpecifier::aArg:
500       case analyze_format_string::ConversionSpecifier::AArg:
501       case analyze_format_string::ConversionSpecifier::eArg:
502       case analyze_format_string::ConversionSpecifier::EArg:
503       case analyze_format_string::ConversionSpecifier::fArg:
504       case analyze_format_string::ConversionSpecifier::FArg:
505       case analyze_format_string::ConversionSpecifier::gArg:
506       case analyze_format_string::ConversionSpecifier::GArg:
507         Size += (Precision ? 0 : 1);
508         break;
509       }
510     }
511     assert(SpecifierLen <= Size && "no underflow");
512     Size -= SpecifierLen;
513     return true;
514   }
515 
516   size_t getSizeLowerBound() const { return Size; }
517 
518 private:
519   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
520     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
521     size_t FieldWidth = 0;
522     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
523       FieldWidth = FW.getConstantAmount();
524     return FieldWidth;
525   }
526 
527   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
528     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
529     size_t Precision = 0;
530 
531     // See man 3 printf for default precision value based on the specifier.
532     switch (FW.getHowSpecified()) {
533     case analyze_format_string::OptionalAmount::NotSpecified:
534       switch (FS.getConversionSpecifier().getKind()) {
535       default:
536         break;
537       case analyze_format_string::ConversionSpecifier::dArg: // %d
538       case analyze_format_string::ConversionSpecifier::DArg: // %D
539       case analyze_format_string::ConversionSpecifier::iArg: // %i
540         Precision = 1;
541         break;
542       case analyze_format_string::ConversionSpecifier::oArg: // %d
543       case analyze_format_string::ConversionSpecifier::OArg: // %D
544       case analyze_format_string::ConversionSpecifier::uArg: // %d
545       case analyze_format_string::ConversionSpecifier::UArg: // %D
546       case analyze_format_string::ConversionSpecifier::xArg: // %d
547       case analyze_format_string::ConversionSpecifier::XArg: // %D
548         Precision = 1;
549         break;
550       case analyze_format_string::ConversionSpecifier::fArg: // %f
551       case analyze_format_string::ConversionSpecifier::FArg: // %F
552       case analyze_format_string::ConversionSpecifier::eArg: // %e
553       case analyze_format_string::ConversionSpecifier::EArg: // %E
554       case analyze_format_string::ConversionSpecifier::gArg: // %g
555       case analyze_format_string::ConversionSpecifier::GArg: // %G
556         Precision = 6;
557         break;
558       case analyze_format_string::ConversionSpecifier::pArg: // %d
559         Precision = 1;
560         break;
561       }
562       break;
563     case analyze_format_string::OptionalAmount::Constant:
564       Precision = FW.getConstantAmount();
565       break;
566     default:
567       break;
568     }
569     return Precision;
570   }
571 };
572 
573 } // namespace
574 
575 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
576 /// __builtin_*_chk function, then use the object size argument specified in the
577 /// source. Otherwise, infer the object size using __builtin_object_size.
578 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
579                                                CallExpr *TheCall) {
580   // FIXME: There are some more useful checks we could be doing here:
581   //  - Evaluate strlen of strcpy arguments, use as object size.
582 
583   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
584       isConstantEvaluated())
585     return;
586 
587   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
588   if (!BuiltinID)
589     return;
590 
591   const TargetInfo &TI = getASTContext().getTargetInfo();
592   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
593 
594   unsigned DiagID = 0;
595   bool IsChkVariant = false;
596   Optional<llvm::APSInt> UsedSize;
597   unsigned SizeIndex, ObjectIndex;
598   switch (BuiltinID) {
599   default:
600     return;
601   case Builtin::BIsprintf:
602   case Builtin::BI__builtin___sprintf_chk: {
603     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
604     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
605 
606     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
607 
608       if (!Format->isAscii() && !Format->isUTF8())
609         return;
610 
611       StringRef FormatStrRef = Format->getString();
612       EstimateSizeFormatHandler H(FormatStrRef);
613       const char *FormatBytes = FormatStrRef.data();
614       const ConstantArrayType *T =
615           Context.getAsConstantArrayType(Format->getType());
616       assert(T && "String literal not of constant array type!");
617       size_t TypeSize = T->getSize().getZExtValue();
618 
619       // In case there's a null byte somewhere.
620       size_t StrLen =
621           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
622       if (!analyze_format_string::ParsePrintfString(
623               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
624               Context.getTargetInfo(), false)) {
625         DiagID = diag::warn_fortify_source_format_overflow;
626         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
627                        .extOrTrunc(SizeTypeWidth);
628         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
629           IsChkVariant = true;
630           ObjectIndex = 2;
631         } else {
632           IsChkVariant = false;
633           ObjectIndex = 0;
634         }
635         break;
636       }
637     }
638     return;
639   }
640   case Builtin::BI__builtin___memcpy_chk:
641   case Builtin::BI__builtin___memmove_chk:
642   case Builtin::BI__builtin___memset_chk:
643   case Builtin::BI__builtin___strlcat_chk:
644   case Builtin::BI__builtin___strlcpy_chk:
645   case Builtin::BI__builtin___strncat_chk:
646   case Builtin::BI__builtin___strncpy_chk:
647   case Builtin::BI__builtin___stpncpy_chk:
648   case Builtin::BI__builtin___memccpy_chk:
649   case Builtin::BI__builtin___mempcpy_chk: {
650     DiagID = diag::warn_builtin_chk_overflow;
651     IsChkVariant = true;
652     SizeIndex = TheCall->getNumArgs() - 2;
653     ObjectIndex = TheCall->getNumArgs() - 1;
654     break;
655   }
656 
657   case Builtin::BI__builtin___snprintf_chk:
658   case Builtin::BI__builtin___vsnprintf_chk: {
659     DiagID = diag::warn_builtin_chk_overflow;
660     IsChkVariant = true;
661     SizeIndex = 1;
662     ObjectIndex = 3;
663     break;
664   }
665 
666   case Builtin::BIstrncat:
667   case Builtin::BI__builtin_strncat:
668   case Builtin::BIstrncpy:
669   case Builtin::BI__builtin_strncpy:
670   case Builtin::BIstpncpy:
671   case Builtin::BI__builtin_stpncpy: {
672     // Whether these functions overflow depends on the runtime strlen of the
673     // string, not just the buffer size, so emitting the "always overflow"
674     // diagnostic isn't quite right. We should still diagnose passing a buffer
675     // size larger than the destination buffer though; this is a runtime abort
676     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
677     DiagID = diag::warn_fortify_source_size_mismatch;
678     SizeIndex = TheCall->getNumArgs() - 1;
679     ObjectIndex = 0;
680     break;
681   }
682 
683   case Builtin::BImemcpy:
684   case Builtin::BI__builtin_memcpy:
685   case Builtin::BImemmove:
686   case Builtin::BI__builtin_memmove:
687   case Builtin::BImemset:
688   case Builtin::BI__builtin_memset:
689   case Builtin::BImempcpy:
690   case Builtin::BI__builtin_mempcpy: {
691     DiagID = diag::warn_fortify_source_overflow;
692     SizeIndex = TheCall->getNumArgs() - 1;
693     ObjectIndex = 0;
694     break;
695   }
696   case Builtin::BIsnprintf:
697   case Builtin::BI__builtin_snprintf:
698   case Builtin::BIvsnprintf:
699   case Builtin::BI__builtin_vsnprintf: {
700     DiagID = diag::warn_fortify_source_size_mismatch;
701     SizeIndex = 1;
702     ObjectIndex = 0;
703     break;
704   }
705   }
706 
707   llvm::APSInt ObjectSize;
708   // For __builtin___*_chk, the object size is explicitly provided by the caller
709   // (usually using __builtin_object_size). Use that value to check this call.
710   if (IsChkVariant) {
711     Expr::EvalResult Result;
712     Expr *SizeArg = TheCall->getArg(ObjectIndex);
713     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
714       return;
715     ObjectSize = Result.Val.getInt();
716 
717   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
718   } else {
719     // If the parameter has a pass_object_size attribute, then we should use its
720     // (potentially) more strict checking mode. Otherwise, conservatively assume
721     // type 0.
722     int BOSType = 0;
723     if (const auto *POS =
724             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
725       BOSType = POS->getType();
726 
727     Expr *ObjArg = TheCall->getArg(ObjectIndex);
728     uint64_t Result;
729     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
730       return;
731     // Get the object size in the target's size_t width.
732     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
733   }
734 
735   // Evaluate the number of bytes of the object that this call will use.
736   if (!UsedSize) {
737     Expr::EvalResult Result;
738     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
739     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
740       return;
741     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
742   }
743 
744   if (UsedSize.getValue().ule(ObjectSize))
745     return;
746 
747   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
748   // Skim off the details of whichever builtin was called to produce a better
749   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
750   if (IsChkVariant) {
751     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
752     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
753   } else if (FunctionName.startswith("__builtin_")) {
754     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
755   }
756 
757   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
758                       PDiag(DiagID)
759                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
760                           << UsedSize.getValue().toString(/*Radix=*/10));
761 }
762 
763 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
764                                      Scope::ScopeFlags NeededScopeFlags,
765                                      unsigned DiagID) {
766   // Scopes aren't available during instantiation. Fortunately, builtin
767   // functions cannot be template args so they cannot be formed through template
768   // instantiation. Therefore checking once during the parse is sufficient.
769   if (SemaRef.inTemplateInstantiation())
770     return false;
771 
772   Scope *S = SemaRef.getCurScope();
773   while (S && !S->isSEHExceptScope())
774     S = S->getParent();
775   if (!S || !(S->getFlags() & NeededScopeFlags)) {
776     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
777     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
778         << DRE->getDecl()->getIdentifier();
779     return true;
780   }
781 
782   return false;
783 }
784 
785 static inline bool isBlockPointer(Expr *Arg) {
786   return Arg->getType()->isBlockPointerType();
787 }
788 
789 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
790 /// void*, which is a requirement of device side enqueue.
791 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
792   const BlockPointerType *BPT =
793       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
794   ArrayRef<QualType> Params =
795       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
796   unsigned ArgCounter = 0;
797   bool IllegalParams = false;
798   // Iterate through the block parameters until either one is found that is not
799   // a local void*, or the block is valid.
800   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
801        I != E; ++I, ++ArgCounter) {
802     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
803         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
804             LangAS::opencl_local) {
805       // Get the location of the error. If a block literal has been passed
806       // (BlockExpr) then we can point straight to the offending argument,
807       // else we just point to the variable reference.
808       SourceLocation ErrorLoc;
809       if (isa<BlockExpr>(BlockArg)) {
810         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
811         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
812       } else if (isa<DeclRefExpr>(BlockArg)) {
813         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
814       }
815       S.Diag(ErrorLoc,
816              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
817       IllegalParams = true;
818     }
819   }
820 
821   return IllegalParams;
822 }
823 
824 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
825   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
826     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
827         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
828     return true;
829   }
830   return false;
831 }
832 
833 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
834   if (checkArgCount(S, TheCall, 2))
835     return true;
836 
837   if (checkOpenCLSubgroupExt(S, TheCall))
838     return true;
839 
840   // First argument is an ndrange_t type.
841   Expr *NDRangeArg = TheCall->getArg(0);
842   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
843     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
844         << TheCall->getDirectCallee() << "'ndrange_t'";
845     return true;
846   }
847 
848   Expr *BlockArg = TheCall->getArg(1);
849   if (!isBlockPointer(BlockArg)) {
850     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
851         << TheCall->getDirectCallee() << "block";
852     return true;
853   }
854   return checkOpenCLBlockArgs(S, BlockArg);
855 }
856 
857 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
858 /// get_kernel_work_group_size
859 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
860 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
861   if (checkArgCount(S, TheCall, 1))
862     return true;
863 
864   Expr *BlockArg = TheCall->getArg(0);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// Diagnose integer type and any valid implicit conversion to it.
874 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
875                                       const QualType &IntType);
876 
877 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
878                                             unsigned Start, unsigned End) {
879   bool IllegalParams = false;
880   for (unsigned I = Start; I <= End; ++I)
881     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
882                                               S.Context.getSizeType());
883   return IllegalParams;
884 }
885 
886 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
887 /// 'local void*' parameter of passed block.
888 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
889                                            Expr *BlockArg,
890                                            unsigned NumNonVarArgs) {
891   const BlockPointerType *BPT =
892       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
893   unsigned NumBlockParams =
894       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
895   unsigned TotalNumArgs = TheCall->getNumArgs();
896 
897   // For each argument passed to the block, a corresponding uint needs to
898   // be passed to describe the size of the local memory.
899   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
900     S.Diag(TheCall->getBeginLoc(),
901            diag::err_opencl_enqueue_kernel_local_size_args);
902     return true;
903   }
904 
905   // Check that the sizes of the local memory are specified by integers.
906   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
907                                          TotalNumArgs - 1);
908 }
909 
910 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
911 /// overload formats specified in Table 6.13.17.1.
912 /// int enqueue_kernel(queue_t queue,
913 ///                    kernel_enqueue_flags_t flags,
914 ///                    const ndrange_t ndrange,
915 ///                    void (^block)(void))
916 /// int enqueue_kernel(queue_t queue,
917 ///                    kernel_enqueue_flags_t flags,
918 ///                    const ndrange_t ndrange,
919 ///                    uint num_events_in_wait_list,
920 ///                    clk_event_t *event_wait_list,
921 ///                    clk_event_t *event_ret,
922 ///                    void (^block)(void))
923 /// int enqueue_kernel(queue_t queue,
924 ///                    kernel_enqueue_flags_t flags,
925 ///                    const ndrange_t ndrange,
926 ///                    void (^block)(local void*, ...),
927 ///                    uint size0, ...)
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    uint num_events_in_wait_list,
932 ///                    clk_event_t *event_wait_list,
933 ///                    clk_event_t *event_ret,
934 ///                    void (^block)(local void*, ...),
935 ///                    uint size0, ...)
936 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
937   unsigned NumArgs = TheCall->getNumArgs();
938 
939   if (NumArgs < 4) {
940     S.Diag(TheCall->getBeginLoc(),
941            diag::err_typecheck_call_too_few_args_at_least)
942         << 0 << 4 << NumArgs;
943     return true;
944   }
945 
946   Expr *Arg0 = TheCall->getArg(0);
947   Expr *Arg1 = TheCall->getArg(1);
948   Expr *Arg2 = TheCall->getArg(2);
949   Expr *Arg3 = TheCall->getArg(3);
950 
951   // First argument always needs to be a queue_t type.
952   if (!Arg0->getType()->isQueueT()) {
953     S.Diag(TheCall->getArg(0)->getBeginLoc(),
954            diag::err_opencl_builtin_expected_type)
955         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
956     return true;
957   }
958 
959   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
960   if (!Arg1->getType()->isIntegerType()) {
961     S.Diag(TheCall->getArg(1)->getBeginLoc(),
962            diag::err_opencl_builtin_expected_type)
963         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
964     return true;
965   }
966 
967   // Third argument is always an ndrange_t type.
968   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
969     S.Diag(TheCall->getArg(2)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << "'ndrange_t'";
972     return true;
973   }
974 
975   // With four arguments, there is only one form that the function could be
976   // called in: no events and no variable arguments.
977   if (NumArgs == 4) {
978     // check that the last argument is the right block type.
979     if (!isBlockPointer(Arg3)) {
980       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
981           << TheCall->getDirectCallee() << "block";
982       return true;
983     }
984     // we have a block type, check the prototype
985     const BlockPointerType *BPT =
986         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
987     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
988       S.Diag(Arg3->getBeginLoc(),
989              diag::err_opencl_enqueue_kernel_blocks_no_args);
990       return true;
991     }
992     return false;
993   }
994   // we can have block + varargs.
995   if (isBlockPointer(Arg3))
996     return (checkOpenCLBlockArgs(S, Arg3) ||
997             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
998   // last two cases with either exactly 7 args or 7 args and varargs.
999   if (NumArgs >= 7) {
1000     // check common block argument.
1001     Expr *Arg6 = TheCall->getArg(6);
1002     if (!isBlockPointer(Arg6)) {
1003       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1004           << TheCall->getDirectCallee() << "block";
1005       return true;
1006     }
1007     if (checkOpenCLBlockArgs(S, Arg6))
1008       return true;
1009 
1010     // Forth argument has to be any integer type.
1011     if (!Arg3->getType()->isIntegerType()) {
1012       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1013              diag::err_opencl_builtin_expected_type)
1014           << TheCall->getDirectCallee() << "integer";
1015       return true;
1016     }
1017     // check remaining common arguments.
1018     Expr *Arg4 = TheCall->getArg(4);
1019     Expr *Arg5 = TheCall->getArg(5);
1020 
1021     // Fifth argument is always passed as a pointer to clk_event_t.
1022     if (!Arg4->isNullPointerConstant(S.Context,
1023                                      Expr::NPC_ValueDependentIsNotNull) &&
1024         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1025       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1026              diag::err_opencl_builtin_expected_type)
1027           << TheCall->getDirectCallee()
1028           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1029       return true;
1030     }
1031 
1032     // Sixth argument is always passed as a pointer to clk_event_t.
1033     if (!Arg5->isNullPointerConstant(S.Context,
1034                                      Expr::NPC_ValueDependentIsNotNull) &&
1035         !(Arg5->getType()->isPointerType() &&
1036           Arg5->getType()->getPointeeType()->isClkEventT())) {
1037       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1038              diag::err_opencl_builtin_expected_type)
1039           << TheCall->getDirectCallee()
1040           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1041       return true;
1042     }
1043 
1044     if (NumArgs == 7)
1045       return false;
1046 
1047     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1048   }
1049 
1050   // None of the specific case has been detected, give generic error
1051   S.Diag(TheCall->getBeginLoc(),
1052          diag::err_opencl_enqueue_kernel_incorrect_args);
1053   return true;
1054 }
1055 
1056 /// Returns OpenCL access qual.
1057 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1058     return D->getAttr<OpenCLAccessAttr>();
1059 }
1060 
1061 /// Returns true if pipe element type is different from the pointer.
1062 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1063   const Expr *Arg0 = Call->getArg(0);
1064   // First argument type should always be pipe.
1065   if (!Arg0->getType()->isPipeType()) {
1066     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1067         << Call->getDirectCallee() << Arg0->getSourceRange();
1068     return true;
1069   }
1070   OpenCLAccessAttr *AccessQual =
1071       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1072   // Validates the access qualifier is compatible with the call.
1073   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1074   // read_only and write_only, and assumed to be read_only if no qualifier is
1075   // specified.
1076   switch (Call->getDirectCallee()->getBuiltinID()) {
1077   case Builtin::BIread_pipe:
1078   case Builtin::BIreserve_read_pipe:
1079   case Builtin::BIcommit_read_pipe:
1080   case Builtin::BIwork_group_reserve_read_pipe:
1081   case Builtin::BIsub_group_reserve_read_pipe:
1082   case Builtin::BIwork_group_commit_read_pipe:
1083   case Builtin::BIsub_group_commit_read_pipe:
1084     if (!(!AccessQual || AccessQual->isReadOnly())) {
1085       S.Diag(Arg0->getBeginLoc(),
1086              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1087           << "read_only" << Arg0->getSourceRange();
1088       return true;
1089     }
1090     break;
1091   case Builtin::BIwrite_pipe:
1092   case Builtin::BIreserve_write_pipe:
1093   case Builtin::BIcommit_write_pipe:
1094   case Builtin::BIwork_group_reserve_write_pipe:
1095   case Builtin::BIsub_group_reserve_write_pipe:
1096   case Builtin::BIwork_group_commit_write_pipe:
1097   case Builtin::BIsub_group_commit_write_pipe:
1098     if (!(AccessQual && AccessQual->isWriteOnly())) {
1099       S.Diag(Arg0->getBeginLoc(),
1100              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101           << "write_only" << Arg0->getSourceRange();
1102       return true;
1103     }
1104     break;
1105   default:
1106     break;
1107   }
1108   return false;
1109 }
1110 
1111 /// Returns true if pipe element type is different from the pointer.
1112 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1113   const Expr *Arg0 = Call->getArg(0);
1114   const Expr *ArgIdx = Call->getArg(Idx);
1115   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1116   const QualType EltTy = PipeTy->getElementType();
1117   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1118   // The Idx argument should be a pointer and the type of the pointer and
1119   // the type of pipe element should also be the same.
1120   if (!ArgTy ||
1121       !S.Context.hasSameType(
1122           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1123     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1124         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1125         << ArgIdx->getType() << ArgIdx->getSourceRange();
1126     return true;
1127   }
1128   return false;
1129 }
1130 
1131 // Performs semantic analysis for the read/write_pipe call.
1132 // \param S Reference to the semantic analyzer.
1133 // \param Call A pointer to the builtin call.
1134 // \return True if a semantic error has been found, false otherwise.
1135 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1136   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1137   // functions have two forms.
1138   switch (Call->getNumArgs()) {
1139   case 2:
1140     if (checkOpenCLPipeArg(S, Call))
1141       return true;
1142     // The call with 2 arguments should be
1143     // read/write_pipe(pipe T, T*).
1144     // Check packet type T.
1145     if (checkOpenCLPipePacketType(S, Call, 1))
1146       return true;
1147     break;
1148 
1149   case 4: {
1150     if (checkOpenCLPipeArg(S, Call))
1151       return true;
1152     // The call with 4 arguments should be
1153     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1154     // Check reserve_id_t.
1155     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1156       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1157           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1158           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1159       return true;
1160     }
1161 
1162     // Check the index.
1163     const Expr *Arg2 = Call->getArg(2);
1164     if (!Arg2->getType()->isIntegerType() &&
1165         !Arg2->getType()->isUnsignedIntegerType()) {
1166       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1167           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1168           << Arg2->getType() << Arg2->getSourceRange();
1169       return true;
1170     }
1171 
1172     // Check packet type T.
1173     if (checkOpenCLPipePacketType(S, Call, 3))
1174       return true;
1175   } break;
1176   default:
1177     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1178         << Call->getDirectCallee() << Call->getSourceRange();
1179     return true;
1180   }
1181 
1182   return false;
1183 }
1184 
1185 // Performs a semantic analysis on the {work_group_/sub_group_
1186 //        /_}reserve_{read/write}_pipe
1187 // \param S Reference to the semantic analyzer.
1188 // \param Call The call to the builtin function to be analyzed.
1189 // \return True if a semantic error was found, false otherwise.
1190 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1191   if (checkArgCount(S, Call, 2))
1192     return true;
1193 
1194   if (checkOpenCLPipeArg(S, Call))
1195     return true;
1196 
1197   // Check the reserve size.
1198   if (!Call->getArg(1)->getType()->isIntegerType() &&
1199       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1200     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1201         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1202         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1203     return true;
1204   }
1205 
1206   // Since return type of reserve_read/write_pipe built-in function is
1207   // reserve_id_t, which is not defined in the builtin def file , we used int
1208   // as return type and need to override the return type of these functions.
1209   Call->setType(S.Context.OCLReserveIDTy);
1210 
1211   return false;
1212 }
1213 
1214 // Performs a semantic analysis on {work_group_/sub_group_
1215 //        /_}commit_{read/write}_pipe
1216 // \param S Reference to the semantic analyzer.
1217 // \param Call The call to the builtin function to be analyzed.
1218 // \return True if a semantic error was found, false otherwise.
1219 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1220   if (checkArgCount(S, Call, 2))
1221     return true;
1222 
1223   if (checkOpenCLPipeArg(S, Call))
1224     return true;
1225 
1226   // Check reserve_id_t.
1227   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1228     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1229         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1230         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1231     return true;
1232   }
1233 
1234   return false;
1235 }
1236 
1237 // Performs a semantic analysis on the call to built-in Pipe
1238 //        Query Functions.
1239 // \param S Reference to the semantic analyzer.
1240 // \param Call The call to the builtin function to be analyzed.
1241 // \return True if a semantic error was found, false otherwise.
1242 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1243   if (checkArgCount(S, Call, 1))
1244     return true;
1245 
1246   if (!Call->getArg(0)->getType()->isPipeType()) {
1247     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1248         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1249     return true;
1250   }
1251 
1252   return false;
1253 }
1254 
1255 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1256 // Performs semantic analysis for the to_global/local/private call.
1257 // \param S Reference to the semantic analyzer.
1258 // \param BuiltinID ID of the builtin function.
1259 // \param Call A pointer to the builtin call.
1260 // \return True if a semantic error has been found, false otherwise.
1261 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1262                                     CallExpr *Call) {
1263   if (Call->getNumArgs() != 1) {
1264     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1265         << Call->getDirectCallee() << Call->getSourceRange();
1266     return true;
1267   }
1268 
1269   auto RT = Call->getArg(0)->getType();
1270   if (!RT->isPointerType() || RT->getPointeeType()
1271       .getAddressSpace() == LangAS::opencl_constant) {
1272     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1273         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1274     return true;
1275   }
1276 
1277   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1278     S.Diag(Call->getArg(0)->getBeginLoc(),
1279            diag::warn_opencl_generic_address_space_arg)
1280         << Call->getDirectCallee()->getNameInfo().getAsString()
1281         << Call->getArg(0)->getSourceRange();
1282   }
1283 
1284   RT = RT->getPointeeType();
1285   auto Qual = RT.getQualifiers();
1286   switch (BuiltinID) {
1287   case Builtin::BIto_global:
1288     Qual.setAddressSpace(LangAS::opencl_global);
1289     break;
1290   case Builtin::BIto_local:
1291     Qual.setAddressSpace(LangAS::opencl_local);
1292     break;
1293   case Builtin::BIto_private:
1294     Qual.setAddressSpace(LangAS::opencl_private);
1295     break;
1296   default:
1297     llvm_unreachable("Invalid builtin function");
1298   }
1299   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1300       RT.getUnqualifiedType(), Qual)));
1301 
1302   return false;
1303 }
1304 
1305 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1306   if (checkArgCount(S, TheCall, 1))
1307     return ExprError();
1308 
1309   // Compute __builtin_launder's parameter type from the argument.
1310   // The parameter type is:
1311   //  * The type of the argument if it's not an array or function type,
1312   //  Otherwise,
1313   //  * The decayed argument type.
1314   QualType ParamTy = [&]() {
1315     QualType ArgTy = TheCall->getArg(0)->getType();
1316     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1317       return S.Context.getPointerType(Ty->getElementType());
1318     if (ArgTy->isFunctionType()) {
1319       return S.Context.getPointerType(ArgTy);
1320     }
1321     return ArgTy;
1322   }();
1323 
1324   TheCall->setType(ParamTy);
1325 
1326   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1327     if (!ParamTy->isPointerType())
1328       return 0;
1329     if (ParamTy->isFunctionPointerType())
1330       return 1;
1331     if (ParamTy->isVoidPointerType())
1332       return 2;
1333     return llvm::Optional<unsigned>{};
1334   }();
1335   if (DiagSelect.hasValue()) {
1336     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1337         << DiagSelect.getValue() << TheCall->getSourceRange();
1338     return ExprError();
1339   }
1340 
1341   // We either have an incomplete class type, or we have a class template
1342   // whose instantiation has not been forced. Example:
1343   //
1344   //   template <class T> struct Foo { T value; };
1345   //   Foo<int> *p = nullptr;
1346   //   auto *d = __builtin_launder(p);
1347   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1348                             diag::err_incomplete_type))
1349     return ExprError();
1350 
1351   assert(ParamTy->getPointeeType()->isObjectType() &&
1352          "Unhandled non-object pointer case");
1353 
1354   InitializedEntity Entity =
1355       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1356   ExprResult Arg =
1357       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1358   if (Arg.isInvalid())
1359     return ExprError();
1360   TheCall->setArg(0, Arg.get());
1361 
1362   return TheCall;
1363 }
1364 
1365 // Emit an error and return true if the current architecture is not in the list
1366 // of supported architectures.
1367 static bool
1368 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1369                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1370   llvm::Triple::ArchType CurArch =
1371       S.getASTContext().getTargetInfo().getTriple().getArch();
1372   if (llvm::is_contained(SupportedArchs, CurArch))
1373     return false;
1374   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1375       << TheCall->getSourceRange();
1376   return true;
1377 }
1378 
1379 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1380                                  SourceLocation CallSiteLoc);
1381 
1382 ExprResult
1383 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1384                                CallExpr *TheCall) {
1385   ExprResult TheCallResult(TheCall);
1386 
1387   // Find out if any arguments are required to be integer constant expressions.
1388   unsigned ICEArguments = 0;
1389   ASTContext::GetBuiltinTypeError Error;
1390   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1391   if (Error != ASTContext::GE_None)
1392     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1393 
1394   // If any arguments are required to be ICE's, check and diagnose.
1395   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1396     // Skip arguments not required to be ICE's.
1397     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1398 
1399     llvm::APSInt Result;
1400     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1401       return true;
1402     ICEArguments &= ~(1 << ArgNo);
1403   }
1404 
1405   switch (BuiltinID) {
1406   case Builtin::BI__builtin___CFStringMakeConstantString:
1407     assert(TheCall->getNumArgs() == 1 &&
1408            "Wrong # arguments to builtin CFStringMakeConstantString");
1409     if (CheckObjCString(TheCall->getArg(0)))
1410       return ExprError();
1411     break;
1412   case Builtin::BI__builtin_ms_va_start:
1413   case Builtin::BI__builtin_stdarg_start:
1414   case Builtin::BI__builtin_va_start:
1415     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1416       return ExprError();
1417     break;
1418   case Builtin::BI__va_start: {
1419     switch (Context.getTargetInfo().getTriple().getArch()) {
1420     case llvm::Triple::aarch64:
1421     case llvm::Triple::arm:
1422     case llvm::Triple::thumb:
1423       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1424         return ExprError();
1425       break;
1426     default:
1427       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1428         return ExprError();
1429       break;
1430     }
1431     break;
1432   }
1433 
1434   // The acquire, release, and no fence variants are ARM and AArch64 only.
1435   case Builtin::BI_interlockedbittestandset_acq:
1436   case Builtin::BI_interlockedbittestandset_rel:
1437   case Builtin::BI_interlockedbittestandset_nf:
1438   case Builtin::BI_interlockedbittestandreset_acq:
1439   case Builtin::BI_interlockedbittestandreset_rel:
1440   case Builtin::BI_interlockedbittestandreset_nf:
1441     if (CheckBuiltinTargetSupport(
1442             *this, BuiltinID, TheCall,
1443             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1444       return ExprError();
1445     break;
1446 
1447   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1448   case Builtin::BI_bittest64:
1449   case Builtin::BI_bittestandcomplement64:
1450   case Builtin::BI_bittestandreset64:
1451   case Builtin::BI_bittestandset64:
1452   case Builtin::BI_interlockedbittestandreset64:
1453   case Builtin::BI_interlockedbittestandset64:
1454     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1455                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1456                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1457       return ExprError();
1458     break;
1459 
1460   case Builtin::BI__builtin_isgreater:
1461   case Builtin::BI__builtin_isgreaterequal:
1462   case Builtin::BI__builtin_isless:
1463   case Builtin::BI__builtin_islessequal:
1464   case Builtin::BI__builtin_islessgreater:
1465   case Builtin::BI__builtin_isunordered:
1466     if (SemaBuiltinUnorderedCompare(TheCall))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_fpclassify:
1470     if (SemaBuiltinFPClassification(TheCall, 6))
1471       return ExprError();
1472     break;
1473   case Builtin::BI__builtin_isfinite:
1474   case Builtin::BI__builtin_isinf:
1475   case Builtin::BI__builtin_isinf_sign:
1476   case Builtin::BI__builtin_isnan:
1477   case Builtin::BI__builtin_isnormal:
1478   case Builtin::BI__builtin_signbit:
1479   case Builtin::BI__builtin_signbitf:
1480   case Builtin::BI__builtin_signbitl:
1481     if (SemaBuiltinFPClassification(TheCall, 1))
1482       return ExprError();
1483     break;
1484   case Builtin::BI__builtin_shufflevector:
1485     return SemaBuiltinShuffleVector(TheCall);
1486     // TheCall will be freed by the smart pointer here, but that's fine, since
1487     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1488   case Builtin::BI__builtin_prefetch:
1489     if (SemaBuiltinPrefetch(TheCall))
1490       return ExprError();
1491     break;
1492   case Builtin::BI__builtin_alloca_with_align:
1493     if (SemaBuiltinAllocaWithAlign(TheCall))
1494       return ExprError();
1495     LLVM_FALLTHROUGH;
1496   case Builtin::BI__builtin_alloca:
1497     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1498         << TheCall->getDirectCallee();
1499     break;
1500   case Builtin::BI__assume:
1501   case Builtin::BI__builtin_assume:
1502     if (SemaBuiltinAssume(TheCall))
1503       return ExprError();
1504     break;
1505   case Builtin::BI__builtin_assume_aligned:
1506     if (SemaBuiltinAssumeAligned(TheCall))
1507       return ExprError();
1508     break;
1509   case Builtin::BI__builtin_dynamic_object_size:
1510   case Builtin::BI__builtin_object_size:
1511     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1512       return ExprError();
1513     break;
1514   case Builtin::BI__builtin_longjmp:
1515     if (SemaBuiltinLongjmp(TheCall))
1516       return ExprError();
1517     break;
1518   case Builtin::BI__builtin_setjmp:
1519     if (SemaBuiltinSetjmp(TheCall))
1520       return ExprError();
1521     break;
1522   case Builtin::BI_setjmp:
1523   case Builtin::BI_setjmpex:
1524     if (checkArgCount(*this, TheCall, 1))
1525       return true;
1526     break;
1527   case Builtin::BI__builtin_classify_type:
1528     if (checkArgCount(*this, TheCall, 1)) return true;
1529     TheCall->setType(Context.IntTy);
1530     break;
1531   case Builtin::BI__builtin_constant_p: {
1532     if (checkArgCount(*this, TheCall, 1)) return true;
1533     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1534     if (Arg.isInvalid()) return true;
1535     TheCall->setArg(0, Arg.get());
1536     TheCall->setType(Context.IntTy);
1537     break;
1538   }
1539   case Builtin::BI__builtin_launder:
1540     return SemaBuiltinLaunder(*this, TheCall);
1541   case Builtin::BI__sync_fetch_and_add:
1542   case Builtin::BI__sync_fetch_and_add_1:
1543   case Builtin::BI__sync_fetch_and_add_2:
1544   case Builtin::BI__sync_fetch_and_add_4:
1545   case Builtin::BI__sync_fetch_and_add_8:
1546   case Builtin::BI__sync_fetch_and_add_16:
1547   case Builtin::BI__sync_fetch_and_sub:
1548   case Builtin::BI__sync_fetch_and_sub_1:
1549   case Builtin::BI__sync_fetch_and_sub_2:
1550   case Builtin::BI__sync_fetch_and_sub_4:
1551   case Builtin::BI__sync_fetch_and_sub_8:
1552   case Builtin::BI__sync_fetch_and_sub_16:
1553   case Builtin::BI__sync_fetch_and_or:
1554   case Builtin::BI__sync_fetch_and_or_1:
1555   case Builtin::BI__sync_fetch_and_or_2:
1556   case Builtin::BI__sync_fetch_and_or_4:
1557   case Builtin::BI__sync_fetch_and_or_8:
1558   case Builtin::BI__sync_fetch_and_or_16:
1559   case Builtin::BI__sync_fetch_and_and:
1560   case Builtin::BI__sync_fetch_and_and_1:
1561   case Builtin::BI__sync_fetch_and_and_2:
1562   case Builtin::BI__sync_fetch_and_and_4:
1563   case Builtin::BI__sync_fetch_and_and_8:
1564   case Builtin::BI__sync_fetch_and_and_16:
1565   case Builtin::BI__sync_fetch_and_xor:
1566   case Builtin::BI__sync_fetch_and_xor_1:
1567   case Builtin::BI__sync_fetch_and_xor_2:
1568   case Builtin::BI__sync_fetch_and_xor_4:
1569   case Builtin::BI__sync_fetch_and_xor_8:
1570   case Builtin::BI__sync_fetch_and_xor_16:
1571   case Builtin::BI__sync_fetch_and_nand:
1572   case Builtin::BI__sync_fetch_and_nand_1:
1573   case Builtin::BI__sync_fetch_and_nand_2:
1574   case Builtin::BI__sync_fetch_and_nand_4:
1575   case Builtin::BI__sync_fetch_and_nand_8:
1576   case Builtin::BI__sync_fetch_and_nand_16:
1577   case Builtin::BI__sync_add_and_fetch:
1578   case Builtin::BI__sync_add_and_fetch_1:
1579   case Builtin::BI__sync_add_and_fetch_2:
1580   case Builtin::BI__sync_add_and_fetch_4:
1581   case Builtin::BI__sync_add_and_fetch_8:
1582   case Builtin::BI__sync_add_and_fetch_16:
1583   case Builtin::BI__sync_sub_and_fetch:
1584   case Builtin::BI__sync_sub_and_fetch_1:
1585   case Builtin::BI__sync_sub_and_fetch_2:
1586   case Builtin::BI__sync_sub_and_fetch_4:
1587   case Builtin::BI__sync_sub_and_fetch_8:
1588   case Builtin::BI__sync_sub_and_fetch_16:
1589   case Builtin::BI__sync_and_and_fetch:
1590   case Builtin::BI__sync_and_and_fetch_1:
1591   case Builtin::BI__sync_and_and_fetch_2:
1592   case Builtin::BI__sync_and_and_fetch_4:
1593   case Builtin::BI__sync_and_and_fetch_8:
1594   case Builtin::BI__sync_and_and_fetch_16:
1595   case Builtin::BI__sync_or_and_fetch:
1596   case Builtin::BI__sync_or_and_fetch_1:
1597   case Builtin::BI__sync_or_and_fetch_2:
1598   case Builtin::BI__sync_or_and_fetch_4:
1599   case Builtin::BI__sync_or_and_fetch_8:
1600   case Builtin::BI__sync_or_and_fetch_16:
1601   case Builtin::BI__sync_xor_and_fetch:
1602   case Builtin::BI__sync_xor_and_fetch_1:
1603   case Builtin::BI__sync_xor_and_fetch_2:
1604   case Builtin::BI__sync_xor_and_fetch_4:
1605   case Builtin::BI__sync_xor_and_fetch_8:
1606   case Builtin::BI__sync_xor_and_fetch_16:
1607   case Builtin::BI__sync_nand_and_fetch:
1608   case Builtin::BI__sync_nand_and_fetch_1:
1609   case Builtin::BI__sync_nand_and_fetch_2:
1610   case Builtin::BI__sync_nand_and_fetch_4:
1611   case Builtin::BI__sync_nand_and_fetch_8:
1612   case Builtin::BI__sync_nand_and_fetch_16:
1613   case Builtin::BI__sync_val_compare_and_swap:
1614   case Builtin::BI__sync_val_compare_and_swap_1:
1615   case Builtin::BI__sync_val_compare_and_swap_2:
1616   case Builtin::BI__sync_val_compare_and_swap_4:
1617   case Builtin::BI__sync_val_compare_and_swap_8:
1618   case Builtin::BI__sync_val_compare_and_swap_16:
1619   case Builtin::BI__sync_bool_compare_and_swap:
1620   case Builtin::BI__sync_bool_compare_and_swap_1:
1621   case Builtin::BI__sync_bool_compare_and_swap_2:
1622   case Builtin::BI__sync_bool_compare_and_swap_4:
1623   case Builtin::BI__sync_bool_compare_and_swap_8:
1624   case Builtin::BI__sync_bool_compare_and_swap_16:
1625   case Builtin::BI__sync_lock_test_and_set:
1626   case Builtin::BI__sync_lock_test_and_set_1:
1627   case Builtin::BI__sync_lock_test_and_set_2:
1628   case Builtin::BI__sync_lock_test_and_set_4:
1629   case Builtin::BI__sync_lock_test_and_set_8:
1630   case Builtin::BI__sync_lock_test_and_set_16:
1631   case Builtin::BI__sync_lock_release:
1632   case Builtin::BI__sync_lock_release_1:
1633   case Builtin::BI__sync_lock_release_2:
1634   case Builtin::BI__sync_lock_release_4:
1635   case Builtin::BI__sync_lock_release_8:
1636   case Builtin::BI__sync_lock_release_16:
1637   case Builtin::BI__sync_swap:
1638   case Builtin::BI__sync_swap_1:
1639   case Builtin::BI__sync_swap_2:
1640   case Builtin::BI__sync_swap_4:
1641   case Builtin::BI__sync_swap_8:
1642   case Builtin::BI__sync_swap_16:
1643     return SemaBuiltinAtomicOverloaded(TheCallResult);
1644   case Builtin::BI__sync_synchronize:
1645     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1646         << TheCall->getCallee()->getSourceRange();
1647     break;
1648   case Builtin::BI__builtin_nontemporal_load:
1649   case Builtin::BI__builtin_nontemporal_store:
1650     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1651   case Builtin::BI__builtin_memcpy_inline: {
1652     clang::Expr *SizeOp = TheCall->getArg(2);
1653     // We warn about copying to or from `nullptr` pointers when `size` is
1654     // greater than 0. When `size` is value dependent we cannot evaluate its
1655     // value so we bail out.
1656     if (SizeOp->isValueDependent())
1657       break;
1658     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1659       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1660       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1661     }
1662     break;
1663   }
1664 #define BUILTIN(ID, TYPE, ATTRS)
1665 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1666   case Builtin::BI##ID: \
1667     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1668 #include "clang/Basic/Builtins.def"
1669   case Builtin::BI__annotation:
1670     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1671       return ExprError();
1672     break;
1673   case Builtin::BI__builtin_annotation:
1674     if (SemaBuiltinAnnotation(*this, TheCall))
1675       return ExprError();
1676     break;
1677   case Builtin::BI__builtin_addressof:
1678     if (SemaBuiltinAddressof(*this, TheCall))
1679       return ExprError();
1680     break;
1681   case Builtin::BI__builtin_is_aligned:
1682   case Builtin::BI__builtin_align_up:
1683   case Builtin::BI__builtin_align_down:
1684     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1685       return ExprError();
1686     break;
1687   case Builtin::BI__builtin_add_overflow:
1688   case Builtin::BI__builtin_sub_overflow:
1689   case Builtin::BI__builtin_mul_overflow:
1690     if (SemaBuiltinOverflow(*this, TheCall))
1691       return ExprError();
1692     break;
1693   case Builtin::BI__builtin_operator_new:
1694   case Builtin::BI__builtin_operator_delete: {
1695     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1696     ExprResult Res =
1697         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1698     if (Res.isInvalid())
1699       CorrectDelayedTyposInExpr(TheCallResult.get());
1700     return Res;
1701   }
1702   case Builtin::BI__builtin_dump_struct: {
1703     // We first want to ensure we are called with 2 arguments
1704     if (checkArgCount(*this, TheCall, 2))
1705       return ExprError();
1706     // Ensure that the first argument is of type 'struct XX *'
1707     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1708     const QualType PtrArgType = PtrArg->getType();
1709     if (!PtrArgType->isPointerType() ||
1710         !PtrArgType->getPointeeType()->isRecordType()) {
1711       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1712           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1713           << "structure pointer";
1714       return ExprError();
1715     }
1716 
1717     // Ensure that the second argument is of type 'FunctionType'
1718     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1719     const QualType FnPtrArgType = FnPtrArg->getType();
1720     if (!FnPtrArgType->isPointerType()) {
1721       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1722           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1723           << FnPtrArgType << "'int (*)(const char *, ...)'";
1724       return ExprError();
1725     }
1726 
1727     const auto *FuncType =
1728         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1729 
1730     if (!FuncType) {
1731       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1732           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1733           << FnPtrArgType << "'int (*)(const char *, ...)'";
1734       return ExprError();
1735     }
1736 
1737     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1738       if (!FT->getNumParams()) {
1739         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1740             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1741             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1742         return ExprError();
1743       }
1744       QualType PT = FT->getParamType(0);
1745       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1746           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1747           !PT->getPointeeType().isConstQualified()) {
1748         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1749             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1750             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1751         return ExprError();
1752       }
1753     }
1754 
1755     TheCall->setType(Context.IntTy);
1756     break;
1757   }
1758   case Builtin::BI__builtin_preserve_access_index:
1759     if (SemaBuiltinPreserveAI(*this, TheCall))
1760       return ExprError();
1761     break;
1762   case Builtin::BI__builtin_call_with_static_chain:
1763     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1764       return ExprError();
1765     break;
1766   case Builtin::BI__exception_code:
1767   case Builtin::BI_exception_code:
1768     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1769                                  diag::err_seh___except_block))
1770       return ExprError();
1771     break;
1772   case Builtin::BI__exception_info:
1773   case Builtin::BI_exception_info:
1774     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1775                                  diag::err_seh___except_filter))
1776       return ExprError();
1777     break;
1778   case Builtin::BI__GetExceptionInfo:
1779     if (checkArgCount(*this, TheCall, 1))
1780       return ExprError();
1781 
1782     if (CheckCXXThrowOperand(
1783             TheCall->getBeginLoc(),
1784             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1785             TheCall))
1786       return ExprError();
1787 
1788     TheCall->setType(Context.VoidPtrTy);
1789     break;
1790   // OpenCL v2.0, s6.13.16 - Pipe functions
1791   case Builtin::BIread_pipe:
1792   case Builtin::BIwrite_pipe:
1793     // Since those two functions are declared with var args, we need a semantic
1794     // check for the argument.
1795     if (SemaBuiltinRWPipe(*this, TheCall))
1796       return ExprError();
1797     break;
1798   case Builtin::BIreserve_read_pipe:
1799   case Builtin::BIreserve_write_pipe:
1800   case Builtin::BIwork_group_reserve_read_pipe:
1801   case Builtin::BIwork_group_reserve_write_pipe:
1802     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1803       return ExprError();
1804     break;
1805   case Builtin::BIsub_group_reserve_read_pipe:
1806   case Builtin::BIsub_group_reserve_write_pipe:
1807     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1808         SemaBuiltinReserveRWPipe(*this, TheCall))
1809       return ExprError();
1810     break;
1811   case Builtin::BIcommit_read_pipe:
1812   case Builtin::BIcommit_write_pipe:
1813   case Builtin::BIwork_group_commit_read_pipe:
1814   case Builtin::BIwork_group_commit_write_pipe:
1815     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1816       return ExprError();
1817     break;
1818   case Builtin::BIsub_group_commit_read_pipe:
1819   case Builtin::BIsub_group_commit_write_pipe:
1820     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1821         SemaBuiltinCommitRWPipe(*this, TheCall))
1822       return ExprError();
1823     break;
1824   case Builtin::BIget_pipe_num_packets:
1825   case Builtin::BIget_pipe_max_packets:
1826     if (SemaBuiltinPipePackets(*this, TheCall))
1827       return ExprError();
1828     break;
1829   case Builtin::BIto_global:
1830   case Builtin::BIto_local:
1831   case Builtin::BIto_private:
1832     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1833       return ExprError();
1834     break;
1835   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1836   case Builtin::BIenqueue_kernel:
1837     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1838       return ExprError();
1839     break;
1840   case Builtin::BIget_kernel_work_group_size:
1841   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1842     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1843       return ExprError();
1844     break;
1845   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1846   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1847     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1848       return ExprError();
1849     break;
1850   case Builtin::BI__builtin_os_log_format:
1851     Cleanup.setExprNeedsCleanups(true);
1852     LLVM_FALLTHROUGH;
1853   case Builtin::BI__builtin_os_log_format_buffer_size:
1854     if (SemaBuiltinOSLogFormat(TheCall))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__builtin_frame_address:
1858   case Builtin::BI__builtin_return_address:
1859     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1860       return ExprError();
1861 
1862     // -Wframe-address warning if non-zero passed to builtin
1863     // return/frame address.
1864     Expr::EvalResult Result;
1865     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1866         Result.Val.getInt() != 0)
1867       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1868           << ((BuiltinID == Builtin::BI__builtin_return_address)
1869                   ? "__builtin_return_address"
1870                   : "__builtin_frame_address")
1871           << TheCall->getSourceRange();
1872     break;
1873   }
1874 
1875   // Since the target specific builtins for each arch overlap, only check those
1876   // of the arch we are compiling for.
1877   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1878     switch (Context.getTargetInfo().getTriple().getArch()) {
1879       case llvm::Triple::arm:
1880       case llvm::Triple::armeb:
1881       case llvm::Triple::thumb:
1882       case llvm::Triple::thumbeb:
1883         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1884           return ExprError();
1885         break;
1886       case llvm::Triple::aarch64:
1887       case llvm::Triple::aarch64_32:
1888       case llvm::Triple::aarch64_be:
1889         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1890           return ExprError();
1891         break;
1892       case llvm::Triple::bpfeb:
1893       case llvm::Triple::bpfel:
1894         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1895           return ExprError();
1896         break;
1897       case llvm::Triple::hexagon:
1898         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1899           return ExprError();
1900         break;
1901       case llvm::Triple::mips:
1902       case llvm::Triple::mipsel:
1903       case llvm::Triple::mips64:
1904       case llvm::Triple::mips64el:
1905         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1906           return ExprError();
1907         break;
1908       case llvm::Triple::systemz:
1909         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1910           return ExprError();
1911         break;
1912       case llvm::Triple::x86:
1913       case llvm::Triple::x86_64:
1914         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1915           return ExprError();
1916         break;
1917       case llvm::Triple::ppc:
1918       case llvm::Triple::ppc64:
1919       case llvm::Triple::ppc64le:
1920         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1921           return ExprError();
1922         break;
1923       default:
1924         break;
1925     }
1926   }
1927 
1928   return TheCallResult;
1929 }
1930 
1931 // Get the valid immediate range for the specified NEON type code.
1932 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1933   NeonTypeFlags Type(t);
1934   int IsQuad = ForceQuad ? true : Type.isQuad();
1935   switch (Type.getEltType()) {
1936   case NeonTypeFlags::Int8:
1937   case NeonTypeFlags::Poly8:
1938     return shift ? 7 : (8 << IsQuad) - 1;
1939   case NeonTypeFlags::Int16:
1940   case NeonTypeFlags::Poly16:
1941     return shift ? 15 : (4 << IsQuad) - 1;
1942   case NeonTypeFlags::Int32:
1943     return shift ? 31 : (2 << IsQuad) - 1;
1944   case NeonTypeFlags::Int64:
1945   case NeonTypeFlags::Poly64:
1946     return shift ? 63 : (1 << IsQuad) - 1;
1947   case NeonTypeFlags::Poly128:
1948     return shift ? 127 : (1 << IsQuad) - 1;
1949   case NeonTypeFlags::Float16:
1950     assert(!shift && "cannot shift float types!");
1951     return (4 << IsQuad) - 1;
1952   case NeonTypeFlags::Float32:
1953     assert(!shift && "cannot shift float types!");
1954     return (2 << IsQuad) - 1;
1955   case NeonTypeFlags::Float64:
1956     assert(!shift && "cannot shift float types!");
1957     return (1 << IsQuad) - 1;
1958   }
1959   llvm_unreachable("Invalid NeonTypeFlag!");
1960 }
1961 
1962 /// getNeonEltType - Return the QualType corresponding to the elements of
1963 /// the vector type specified by the NeonTypeFlags.  This is used to check
1964 /// the pointer arguments for Neon load/store intrinsics.
1965 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1966                                bool IsPolyUnsigned, bool IsInt64Long) {
1967   switch (Flags.getEltType()) {
1968   case NeonTypeFlags::Int8:
1969     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1970   case NeonTypeFlags::Int16:
1971     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1972   case NeonTypeFlags::Int32:
1973     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1974   case NeonTypeFlags::Int64:
1975     if (IsInt64Long)
1976       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1977     else
1978       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1979                                 : Context.LongLongTy;
1980   case NeonTypeFlags::Poly8:
1981     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1982   case NeonTypeFlags::Poly16:
1983     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1984   case NeonTypeFlags::Poly64:
1985     if (IsInt64Long)
1986       return Context.UnsignedLongTy;
1987     else
1988       return Context.UnsignedLongLongTy;
1989   case NeonTypeFlags::Poly128:
1990     break;
1991   case NeonTypeFlags::Float16:
1992     return Context.HalfTy;
1993   case NeonTypeFlags::Float32:
1994     return Context.FloatTy;
1995   case NeonTypeFlags::Float64:
1996     return Context.DoubleTy;
1997   }
1998   llvm_unreachable("Invalid NeonTypeFlag!");
1999 }
2000 
2001 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2002   // Range check SVE intrinsics that take immediate values.
2003   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2004 
2005   switch (BuiltinID) {
2006   default:
2007     return false;
2008 #define GET_SVE_IMMEDIATE_CHECK
2009 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2010 #undef GET_SVE_IMMEDIATE_CHECK
2011   }
2012 
2013   // Perform all the immediate checks for this builtin call.
2014   bool HasError = false;
2015   for (auto &I : ImmChecks) {
2016     int ArgNum, CheckTy, ElementSizeInBits;
2017     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2018 
2019     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2020     case SVETypeFlags::ImmCheck0_31:
2021       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2022         HasError = true;
2023       break;
2024     case SVETypeFlags::ImmCheck1_16:
2025       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2026         HasError = true;
2027       break;
2028     }
2029   }
2030 
2031   return HasError;
2032 }
2033 
2034 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2035   llvm::APSInt Result;
2036   uint64_t mask = 0;
2037   unsigned TV = 0;
2038   int PtrArgNum = -1;
2039   bool HasConstPtr = false;
2040   switch (BuiltinID) {
2041 #define GET_NEON_OVERLOAD_CHECK
2042 #include "clang/Basic/arm_neon.inc"
2043 #include "clang/Basic/arm_fp16.inc"
2044 #undef GET_NEON_OVERLOAD_CHECK
2045   }
2046 
2047   // For NEON intrinsics which are overloaded on vector element type, validate
2048   // the immediate which specifies which variant to emit.
2049   unsigned ImmArg = TheCall->getNumArgs()-1;
2050   if (mask) {
2051     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2052       return true;
2053 
2054     TV = Result.getLimitedValue(64);
2055     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2056       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2057              << TheCall->getArg(ImmArg)->getSourceRange();
2058   }
2059 
2060   if (PtrArgNum >= 0) {
2061     // Check that pointer arguments have the specified type.
2062     Expr *Arg = TheCall->getArg(PtrArgNum);
2063     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2064       Arg = ICE->getSubExpr();
2065     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2066     QualType RHSTy = RHS.get()->getType();
2067 
2068     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
2069     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2070                           Arch == llvm::Triple::aarch64_32 ||
2071                           Arch == llvm::Triple::aarch64_be;
2072     bool IsInt64Long =
2073         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
2074     QualType EltTy =
2075         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2076     if (HasConstPtr)
2077       EltTy = EltTy.withConst();
2078     QualType LHSTy = Context.getPointerType(EltTy);
2079     AssignConvertType ConvTy;
2080     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2081     if (RHS.isInvalid())
2082       return true;
2083     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2084                                  RHS.get(), AA_Assigning))
2085       return true;
2086   }
2087 
2088   // For NEON intrinsics which take an immediate value as part of the
2089   // instruction, range check them here.
2090   unsigned i = 0, l = 0, u = 0;
2091   switch (BuiltinID) {
2092   default:
2093     return false;
2094   #define GET_NEON_IMMEDIATE_CHECK
2095   #include "clang/Basic/arm_neon.inc"
2096   #include "clang/Basic/arm_fp16.inc"
2097   #undef GET_NEON_IMMEDIATE_CHECK
2098   }
2099 
2100   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2101 }
2102 
2103 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2104   switch (BuiltinID) {
2105   default:
2106     return false;
2107   #include "clang/Basic/arm_mve_builtin_sema.inc"
2108   }
2109 }
2110 
2111 bool Sema::CheckCDEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2112   bool Err = false;
2113   switch (BuiltinID) {
2114   default:
2115     return false;
2116 #include "clang/Basic/arm_cde_builtin_sema.inc"
2117   }
2118 
2119   if (Err)
2120     return true;
2121 
2122   return CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ true);
2123 }
2124 
2125 bool Sema::CheckARMCoprocessorImmediate(const Expr *CoprocArg, bool WantCDE) {
2126   if (isConstantEvaluated())
2127     return false;
2128 
2129   // We can't check the value of a dependent argument.
2130   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2131     return false;
2132 
2133   llvm::APSInt CoprocNoAP;
2134   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2135   (void)IsICE;
2136   assert(IsICE && "Coprocossor immediate is not a constant expression");
2137   int64_t CoprocNo = CoprocNoAP.getExtValue();
2138   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2139 
2140   uint32_t CDECoprocMask = Context.getTargetInfo().getARMCDECoprocMask();
2141   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2142 
2143   if (IsCDECoproc != WantCDE)
2144     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2145            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2146 
2147   return false;
2148 }
2149 
2150 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2151                                         unsigned MaxWidth) {
2152   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2153           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2154           BuiltinID == ARM::BI__builtin_arm_strex ||
2155           BuiltinID == ARM::BI__builtin_arm_stlex ||
2156           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2157           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2158           BuiltinID == AArch64::BI__builtin_arm_strex ||
2159           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2160          "unexpected ARM builtin");
2161   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2162                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2163                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2164                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2165 
2166   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2167 
2168   // Ensure that we have the proper number of arguments.
2169   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2170     return true;
2171 
2172   // Inspect the pointer argument of the atomic builtin.  This should always be
2173   // a pointer type, whose element is an integral scalar or pointer type.
2174   // Because it is a pointer type, we don't have to worry about any implicit
2175   // casts here.
2176   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2177   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2178   if (PointerArgRes.isInvalid())
2179     return true;
2180   PointerArg = PointerArgRes.get();
2181 
2182   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2183   if (!pointerType) {
2184     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2185         << PointerArg->getType() << PointerArg->getSourceRange();
2186     return true;
2187   }
2188 
2189   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2190   // task is to insert the appropriate casts into the AST. First work out just
2191   // what the appropriate type is.
2192   QualType ValType = pointerType->getPointeeType();
2193   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2194   if (IsLdrex)
2195     AddrType.addConst();
2196 
2197   // Issue a warning if the cast is dodgy.
2198   CastKind CastNeeded = CK_NoOp;
2199   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2200     CastNeeded = CK_BitCast;
2201     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2202         << PointerArg->getType() << Context.getPointerType(AddrType)
2203         << AA_Passing << PointerArg->getSourceRange();
2204   }
2205 
2206   // Finally, do the cast and replace the argument with the corrected version.
2207   AddrType = Context.getPointerType(AddrType);
2208   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2209   if (PointerArgRes.isInvalid())
2210     return true;
2211   PointerArg = PointerArgRes.get();
2212 
2213   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2214 
2215   // In general, we allow ints, floats and pointers to be loaded and stored.
2216   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2217       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2218     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2219         << PointerArg->getType() << PointerArg->getSourceRange();
2220     return true;
2221   }
2222 
2223   // But ARM doesn't have instructions to deal with 128-bit versions.
2224   if (Context.getTypeSize(ValType) > MaxWidth) {
2225     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2226     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2227         << PointerArg->getType() << PointerArg->getSourceRange();
2228     return true;
2229   }
2230 
2231   switch (ValType.getObjCLifetime()) {
2232   case Qualifiers::OCL_None:
2233   case Qualifiers::OCL_ExplicitNone:
2234     // okay
2235     break;
2236 
2237   case Qualifiers::OCL_Weak:
2238   case Qualifiers::OCL_Strong:
2239   case Qualifiers::OCL_Autoreleasing:
2240     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2241         << ValType << PointerArg->getSourceRange();
2242     return true;
2243   }
2244 
2245   if (IsLdrex) {
2246     TheCall->setType(ValType);
2247     return false;
2248   }
2249 
2250   // Initialize the argument to be stored.
2251   ExprResult ValArg = TheCall->getArg(0);
2252   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2253       Context, ValType, /*consume*/ false);
2254   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2255   if (ValArg.isInvalid())
2256     return true;
2257   TheCall->setArg(0, ValArg.get());
2258 
2259   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2260   // but the custom checker bypasses all default analysis.
2261   TheCall->setType(Context.IntTy);
2262   return false;
2263 }
2264 
2265 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2266   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2267       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2268       BuiltinID == ARM::BI__builtin_arm_strex ||
2269       BuiltinID == ARM::BI__builtin_arm_stlex) {
2270     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2271   }
2272 
2273   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2274     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2275       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2276   }
2277 
2278   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2279       BuiltinID == ARM::BI__builtin_arm_wsr64)
2280     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2281 
2282   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2283       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2284       BuiltinID == ARM::BI__builtin_arm_wsr ||
2285       BuiltinID == ARM::BI__builtin_arm_wsrp)
2286     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2287 
2288   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2289     return true;
2290   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2291     return true;
2292   if (CheckCDEBuiltinFunctionCall(BuiltinID, TheCall))
2293     return true;
2294 
2295   // For intrinsics which take an immediate value as part of the instruction,
2296   // range check them here.
2297   // FIXME: VFP Intrinsics should error if VFP not present.
2298   switch (BuiltinID) {
2299   default: return false;
2300   case ARM::BI__builtin_arm_ssat:
2301     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2302   case ARM::BI__builtin_arm_usat:
2303     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2304   case ARM::BI__builtin_arm_ssat16:
2305     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2306   case ARM::BI__builtin_arm_usat16:
2307     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2308   case ARM::BI__builtin_arm_vcvtr_f:
2309   case ARM::BI__builtin_arm_vcvtr_d:
2310     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2311   case ARM::BI__builtin_arm_dmb:
2312   case ARM::BI__builtin_arm_dsb:
2313   case ARM::BI__builtin_arm_isb:
2314   case ARM::BI__builtin_arm_dbg:
2315     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2316   case ARM::BI__builtin_arm_cdp:
2317   case ARM::BI__builtin_arm_cdp2:
2318   case ARM::BI__builtin_arm_mcr:
2319   case ARM::BI__builtin_arm_mcr2:
2320   case ARM::BI__builtin_arm_mrc:
2321   case ARM::BI__builtin_arm_mrc2:
2322   case ARM::BI__builtin_arm_mcrr:
2323   case ARM::BI__builtin_arm_mcrr2:
2324   case ARM::BI__builtin_arm_mrrc:
2325   case ARM::BI__builtin_arm_mrrc2:
2326   case ARM::BI__builtin_arm_ldc:
2327   case ARM::BI__builtin_arm_ldcl:
2328   case ARM::BI__builtin_arm_ldc2:
2329   case ARM::BI__builtin_arm_ldc2l:
2330   case ARM::BI__builtin_arm_stc:
2331   case ARM::BI__builtin_arm_stcl:
2332   case ARM::BI__builtin_arm_stc2:
2333   case ARM::BI__builtin_arm_stc2l:
2334     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2335            CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ false);
2336   }
2337 }
2338 
2339 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
2340                                          CallExpr *TheCall) {
2341   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2342       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2343       BuiltinID == AArch64::BI__builtin_arm_strex ||
2344       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2345     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2346   }
2347 
2348   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2349     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2350       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2351       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2352       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2353   }
2354 
2355   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2356       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2357     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2358 
2359   // Memory Tagging Extensions (MTE) Intrinsics
2360   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2361       BuiltinID == AArch64::BI__builtin_arm_addg ||
2362       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2363       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2364       BuiltinID == AArch64::BI__builtin_arm_stg ||
2365       BuiltinID == AArch64::BI__builtin_arm_subp) {
2366     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2367   }
2368 
2369   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2370       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2371       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2372       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2373     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2374 
2375   // Only check the valid encoding range. Any constant in this range would be
2376   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2377   // an exception for incorrect registers. This matches MSVC behavior.
2378   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2379       BuiltinID == AArch64::BI_WriteStatusReg)
2380     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2381 
2382   if (BuiltinID == AArch64::BI__getReg)
2383     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2384 
2385   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2386     return true;
2387 
2388   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2389     return true;
2390 
2391   // For intrinsics which take an immediate value as part of the instruction,
2392   // range check them here.
2393   unsigned i = 0, l = 0, u = 0;
2394   switch (BuiltinID) {
2395   default: return false;
2396   case AArch64::BI__builtin_arm_dmb:
2397   case AArch64::BI__builtin_arm_dsb:
2398   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2399   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2400   }
2401 
2402   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2403 }
2404 
2405 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2406                                        CallExpr *TheCall) {
2407   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
2408          "unexpected ARM builtin");
2409 
2410   if (checkArgCount(*this, TheCall, 2))
2411     return true;
2412 
2413   // The first argument needs to be a record field access.
2414   // If it is an array element access, we delay decision
2415   // to BPF backend to check whether the access is a
2416   // field access or not.
2417   Expr *Arg = TheCall->getArg(0);
2418   if (Arg->getType()->getAsPlaceholderType() ||
2419       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2420        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2421        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2422     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2423         << 1 << Arg->getSourceRange();
2424     return true;
2425   }
2426 
2427   // The second argument needs to be a constant int
2428   llvm::APSInt Value;
2429   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
2430     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2431         << 2 << Arg->getSourceRange();
2432     return true;
2433   }
2434 
2435   TheCall->setType(Context.UnsignedIntTy);
2436   return false;
2437 }
2438 
2439 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2440   struct ArgInfo {
2441     uint8_t OpNum;
2442     bool IsSigned;
2443     uint8_t BitWidth;
2444     uint8_t Align;
2445   };
2446   struct BuiltinInfo {
2447     unsigned BuiltinID;
2448     ArgInfo Infos[2];
2449   };
2450 
2451   static BuiltinInfo Infos[] = {
2452     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2453     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2454     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2455     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2456     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2457     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2458     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2459     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2460     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2461     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2462     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2463 
2464     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2465     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2466     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2467     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2468     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2469     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2470     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2471     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2472     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2473     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2474     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2475 
2476     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2477     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2478     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2479     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2480     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2481     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2482     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2483     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2484     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2485     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2486     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2487     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2488     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2489     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2490     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2491     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2492     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2493     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2494     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2495     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2496     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2497     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2498     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2499     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2500     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2501     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2502     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2503     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2504     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2505     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2506     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2507     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2508     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2509     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2510     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2511     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2512     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2513     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2514     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2515     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2516     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2517     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2518     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2519     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2520     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2521     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2522     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2523     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2524     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2525     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2526     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2527     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2528                                                       {{ 1, false, 6,  0 }} },
2529     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2530     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2531     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2532     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2533     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2534     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2535     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2536                                                       {{ 1, false, 5,  0 }} },
2537     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2538     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2539     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2540     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2541     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2542     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2543                                                        { 2, false, 5,  0 }} },
2544     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2545                                                        { 2, false, 6,  0 }} },
2546     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2547                                                        { 3, false, 5,  0 }} },
2548     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2549                                                        { 3, false, 6,  0 }} },
2550     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2551     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2552     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2553     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2554     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2555     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2556     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2557     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2558     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2559     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2560     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2561     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2562     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2563     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2564     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2565     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2566                                                       {{ 2, false, 4,  0 },
2567                                                        { 3, false, 5,  0 }} },
2568     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2569                                                       {{ 2, false, 4,  0 },
2570                                                        { 3, false, 5,  0 }} },
2571     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2572                                                       {{ 2, false, 4,  0 },
2573                                                        { 3, false, 5,  0 }} },
2574     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2575                                                       {{ 2, false, 4,  0 },
2576                                                        { 3, false, 5,  0 }} },
2577     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2578     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2579     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2580     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2581     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2582     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2583     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2584     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2585     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2586     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2587     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2588                                                        { 2, false, 5,  0 }} },
2589     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2590                                                        { 2, false, 6,  0 }} },
2591     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2592     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2593     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2594     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2595     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2596     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2597     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2598     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2599     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2600                                                       {{ 1, false, 4,  0 }} },
2601     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2602     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2603                                                       {{ 1, false, 4,  0 }} },
2604     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2605     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2606     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2607     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2608     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2610     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2611     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2612     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2613     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2615     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2616     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2617     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2624                                                       {{ 3, false, 1,  0 }} },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2629                                                       {{ 3, false, 1,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2634                                                       {{ 3, false, 1,  0 }} },
2635   };
2636 
2637   // Use a dynamically initialized static to sort the table exactly once on
2638   // first run.
2639   static const bool SortOnce =
2640       (llvm::sort(Infos,
2641                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2642                    return LHS.BuiltinID < RHS.BuiltinID;
2643                  }),
2644        true);
2645   (void)SortOnce;
2646 
2647   const BuiltinInfo *F = llvm::partition_point(
2648       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2649   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2650     return false;
2651 
2652   bool Error = false;
2653 
2654   for (const ArgInfo &A : F->Infos) {
2655     // Ignore empty ArgInfo elements.
2656     if (A.BitWidth == 0)
2657       continue;
2658 
2659     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2660     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2661     if (!A.Align) {
2662       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2663     } else {
2664       unsigned M = 1 << A.Align;
2665       Min *= M;
2666       Max *= M;
2667       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2668                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2669     }
2670   }
2671   return Error;
2672 }
2673 
2674 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2675                                            CallExpr *TheCall) {
2676   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2677 }
2678 
2679 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2680   return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
2681          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2682 }
2683 
2684 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
2685   const TargetInfo &TI = Context.getTargetInfo();
2686 
2687   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2688       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2689     if (!TI.hasFeature("dsp"))
2690       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2691   }
2692 
2693   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2694       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2695     if (!TI.hasFeature("dspr2"))
2696       return Diag(TheCall->getBeginLoc(),
2697                   diag::err_mips_builtin_requires_dspr2);
2698   }
2699 
2700   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2701       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2702     if (!TI.hasFeature("msa"))
2703       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2704   }
2705 
2706   return false;
2707 }
2708 
2709 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2710 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2711 // ordering for DSP is unspecified. MSA is ordered by the data format used
2712 // by the underlying instruction i.e., df/m, df/n and then by size.
2713 //
2714 // FIXME: The size tests here should instead be tablegen'd along with the
2715 //        definitions from include/clang/Basic/BuiltinsMips.def.
2716 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2717 //        be too.
2718 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2719   unsigned i = 0, l = 0, u = 0, m = 0;
2720   switch (BuiltinID) {
2721   default: return false;
2722   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2723   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2724   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2725   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2726   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2727   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2728   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2729   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2730   // df/m field.
2731   // These intrinsics take an unsigned 3 bit immediate.
2732   case Mips::BI__builtin_msa_bclri_b:
2733   case Mips::BI__builtin_msa_bnegi_b:
2734   case Mips::BI__builtin_msa_bseti_b:
2735   case Mips::BI__builtin_msa_sat_s_b:
2736   case Mips::BI__builtin_msa_sat_u_b:
2737   case Mips::BI__builtin_msa_slli_b:
2738   case Mips::BI__builtin_msa_srai_b:
2739   case Mips::BI__builtin_msa_srari_b:
2740   case Mips::BI__builtin_msa_srli_b:
2741   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2742   case Mips::BI__builtin_msa_binsli_b:
2743   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2744   // These intrinsics take an unsigned 4 bit immediate.
2745   case Mips::BI__builtin_msa_bclri_h:
2746   case Mips::BI__builtin_msa_bnegi_h:
2747   case Mips::BI__builtin_msa_bseti_h:
2748   case Mips::BI__builtin_msa_sat_s_h:
2749   case Mips::BI__builtin_msa_sat_u_h:
2750   case Mips::BI__builtin_msa_slli_h:
2751   case Mips::BI__builtin_msa_srai_h:
2752   case Mips::BI__builtin_msa_srari_h:
2753   case Mips::BI__builtin_msa_srli_h:
2754   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2755   case Mips::BI__builtin_msa_binsli_h:
2756   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2757   // These intrinsics take an unsigned 5 bit immediate.
2758   // The first block of intrinsics actually have an unsigned 5 bit field,
2759   // not a df/n field.
2760   case Mips::BI__builtin_msa_cfcmsa:
2761   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2762   case Mips::BI__builtin_msa_clei_u_b:
2763   case Mips::BI__builtin_msa_clei_u_h:
2764   case Mips::BI__builtin_msa_clei_u_w:
2765   case Mips::BI__builtin_msa_clei_u_d:
2766   case Mips::BI__builtin_msa_clti_u_b:
2767   case Mips::BI__builtin_msa_clti_u_h:
2768   case Mips::BI__builtin_msa_clti_u_w:
2769   case Mips::BI__builtin_msa_clti_u_d:
2770   case Mips::BI__builtin_msa_maxi_u_b:
2771   case Mips::BI__builtin_msa_maxi_u_h:
2772   case Mips::BI__builtin_msa_maxi_u_w:
2773   case Mips::BI__builtin_msa_maxi_u_d:
2774   case Mips::BI__builtin_msa_mini_u_b:
2775   case Mips::BI__builtin_msa_mini_u_h:
2776   case Mips::BI__builtin_msa_mini_u_w:
2777   case Mips::BI__builtin_msa_mini_u_d:
2778   case Mips::BI__builtin_msa_addvi_b:
2779   case Mips::BI__builtin_msa_addvi_h:
2780   case Mips::BI__builtin_msa_addvi_w:
2781   case Mips::BI__builtin_msa_addvi_d:
2782   case Mips::BI__builtin_msa_bclri_w:
2783   case Mips::BI__builtin_msa_bnegi_w:
2784   case Mips::BI__builtin_msa_bseti_w:
2785   case Mips::BI__builtin_msa_sat_s_w:
2786   case Mips::BI__builtin_msa_sat_u_w:
2787   case Mips::BI__builtin_msa_slli_w:
2788   case Mips::BI__builtin_msa_srai_w:
2789   case Mips::BI__builtin_msa_srari_w:
2790   case Mips::BI__builtin_msa_srli_w:
2791   case Mips::BI__builtin_msa_srlri_w:
2792   case Mips::BI__builtin_msa_subvi_b:
2793   case Mips::BI__builtin_msa_subvi_h:
2794   case Mips::BI__builtin_msa_subvi_w:
2795   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2796   case Mips::BI__builtin_msa_binsli_w:
2797   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2798   // These intrinsics take an unsigned 6 bit immediate.
2799   case Mips::BI__builtin_msa_bclri_d:
2800   case Mips::BI__builtin_msa_bnegi_d:
2801   case Mips::BI__builtin_msa_bseti_d:
2802   case Mips::BI__builtin_msa_sat_s_d:
2803   case Mips::BI__builtin_msa_sat_u_d:
2804   case Mips::BI__builtin_msa_slli_d:
2805   case Mips::BI__builtin_msa_srai_d:
2806   case Mips::BI__builtin_msa_srari_d:
2807   case Mips::BI__builtin_msa_srli_d:
2808   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2809   case Mips::BI__builtin_msa_binsli_d:
2810   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2811   // These intrinsics take a signed 5 bit immediate.
2812   case Mips::BI__builtin_msa_ceqi_b:
2813   case Mips::BI__builtin_msa_ceqi_h:
2814   case Mips::BI__builtin_msa_ceqi_w:
2815   case Mips::BI__builtin_msa_ceqi_d:
2816   case Mips::BI__builtin_msa_clti_s_b:
2817   case Mips::BI__builtin_msa_clti_s_h:
2818   case Mips::BI__builtin_msa_clti_s_w:
2819   case Mips::BI__builtin_msa_clti_s_d:
2820   case Mips::BI__builtin_msa_clei_s_b:
2821   case Mips::BI__builtin_msa_clei_s_h:
2822   case Mips::BI__builtin_msa_clei_s_w:
2823   case Mips::BI__builtin_msa_clei_s_d:
2824   case Mips::BI__builtin_msa_maxi_s_b:
2825   case Mips::BI__builtin_msa_maxi_s_h:
2826   case Mips::BI__builtin_msa_maxi_s_w:
2827   case Mips::BI__builtin_msa_maxi_s_d:
2828   case Mips::BI__builtin_msa_mini_s_b:
2829   case Mips::BI__builtin_msa_mini_s_h:
2830   case Mips::BI__builtin_msa_mini_s_w:
2831   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2832   // These intrinsics take an unsigned 8 bit immediate.
2833   case Mips::BI__builtin_msa_andi_b:
2834   case Mips::BI__builtin_msa_nori_b:
2835   case Mips::BI__builtin_msa_ori_b:
2836   case Mips::BI__builtin_msa_shf_b:
2837   case Mips::BI__builtin_msa_shf_h:
2838   case Mips::BI__builtin_msa_shf_w:
2839   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2840   case Mips::BI__builtin_msa_bseli_b:
2841   case Mips::BI__builtin_msa_bmnzi_b:
2842   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2843   // df/n format
2844   // These intrinsics take an unsigned 4 bit immediate.
2845   case Mips::BI__builtin_msa_copy_s_b:
2846   case Mips::BI__builtin_msa_copy_u_b:
2847   case Mips::BI__builtin_msa_insve_b:
2848   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2849   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2850   // These intrinsics take an unsigned 3 bit immediate.
2851   case Mips::BI__builtin_msa_copy_s_h:
2852   case Mips::BI__builtin_msa_copy_u_h:
2853   case Mips::BI__builtin_msa_insve_h:
2854   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2855   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2856   // These intrinsics take an unsigned 2 bit immediate.
2857   case Mips::BI__builtin_msa_copy_s_w:
2858   case Mips::BI__builtin_msa_copy_u_w:
2859   case Mips::BI__builtin_msa_insve_w:
2860   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2861   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2862   // These intrinsics take an unsigned 1 bit immediate.
2863   case Mips::BI__builtin_msa_copy_s_d:
2864   case Mips::BI__builtin_msa_copy_u_d:
2865   case Mips::BI__builtin_msa_insve_d:
2866   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2867   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2868   // Memory offsets and immediate loads.
2869   // These intrinsics take a signed 10 bit immediate.
2870   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2871   case Mips::BI__builtin_msa_ldi_h:
2872   case Mips::BI__builtin_msa_ldi_w:
2873   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2874   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
2875   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
2876   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
2877   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
2878   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
2879   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
2880   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
2881   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
2882   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
2883   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
2884   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
2885   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
2886   }
2887 
2888   if (!m)
2889     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2890 
2891   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2892          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2893 }
2894 
2895 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2896   unsigned i = 0, l = 0, u = 0;
2897   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2898                       BuiltinID == PPC::BI__builtin_divdeu ||
2899                       BuiltinID == PPC::BI__builtin_bpermd;
2900   bool IsTarget64Bit = Context.getTargetInfo()
2901                               .getTypeWidth(Context
2902                                             .getTargetInfo()
2903                                             .getIntPtrType()) == 64;
2904   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2905                        BuiltinID == PPC::BI__builtin_divweu ||
2906                        BuiltinID == PPC::BI__builtin_divde ||
2907                        BuiltinID == PPC::BI__builtin_divdeu;
2908 
2909   if (Is64BitBltin && !IsTarget64Bit)
2910     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
2911            << TheCall->getSourceRange();
2912 
2913   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2914       (BuiltinID == PPC::BI__builtin_bpermd &&
2915        !Context.getTargetInfo().hasFeature("bpermd")))
2916     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2917            << TheCall->getSourceRange();
2918 
2919   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
2920     if (!Context.getTargetInfo().hasFeature("vsx"))
2921       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2922              << TheCall->getSourceRange();
2923     return false;
2924   };
2925 
2926   switch (BuiltinID) {
2927   default: return false;
2928   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2929   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2930     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2931            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2932   case PPC::BI__builtin_altivec_dss:
2933     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
2934   case PPC::BI__builtin_tbegin:
2935   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2936   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2937   case PPC::BI__builtin_tabortwc:
2938   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2939   case PPC::BI__builtin_tabortwci:
2940   case PPC::BI__builtin_tabortdci:
2941     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2942            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
2943   case PPC::BI__builtin_altivec_dst:
2944   case PPC::BI__builtin_altivec_dstt:
2945   case PPC::BI__builtin_altivec_dstst:
2946   case PPC::BI__builtin_altivec_dststt:
2947     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
2948   case PPC::BI__builtin_vsx_xxpermdi:
2949   case PPC::BI__builtin_vsx_xxsldwi:
2950     return SemaBuiltinVSX(TheCall);
2951   case PPC::BI__builtin_unpack_vector_int128:
2952     return SemaVSXCheck(TheCall) ||
2953            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2954   case PPC::BI__builtin_pack_vector_int128:
2955     return SemaVSXCheck(TheCall);
2956   }
2957   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2958 }
2959 
2960 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2961                                            CallExpr *TheCall) {
2962   if (BuiltinID == SystemZ::BI__builtin_tabort) {
2963     Expr *Arg = TheCall->getArg(0);
2964     llvm::APSInt AbortCode(32);
2965     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2966         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2967       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
2968              << Arg->getSourceRange();
2969   }
2970 
2971   // For intrinsics which take an immediate value as part of the instruction,
2972   // range check them here.
2973   unsigned i = 0, l = 0, u = 0;
2974   switch (BuiltinID) {
2975   default: return false;
2976   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2977   case SystemZ::BI__builtin_s390_verimb:
2978   case SystemZ::BI__builtin_s390_verimh:
2979   case SystemZ::BI__builtin_s390_verimf:
2980   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2981   case SystemZ::BI__builtin_s390_vfaeb:
2982   case SystemZ::BI__builtin_s390_vfaeh:
2983   case SystemZ::BI__builtin_s390_vfaef:
2984   case SystemZ::BI__builtin_s390_vfaebs:
2985   case SystemZ::BI__builtin_s390_vfaehs:
2986   case SystemZ::BI__builtin_s390_vfaefs:
2987   case SystemZ::BI__builtin_s390_vfaezb:
2988   case SystemZ::BI__builtin_s390_vfaezh:
2989   case SystemZ::BI__builtin_s390_vfaezf:
2990   case SystemZ::BI__builtin_s390_vfaezbs:
2991   case SystemZ::BI__builtin_s390_vfaezhs:
2992   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
2993   case SystemZ::BI__builtin_s390_vfisb:
2994   case SystemZ::BI__builtin_s390_vfidb:
2995     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2996            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2997   case SystemZ::BI__builtin_s390_vftcisb:
2998   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2999   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3000   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3001   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3002   case SystemZ::BI__builtin_s390_vstrcb:
3003   case SystemZ::BI__builtin_s390_vstrch:
3004   case SystemZ::BI__builtin_s390_vstrcf:
3005   case SystemZ::BI__builtin_s390_vstrczb:
3006   case SystemZ::BI__builtin_s390_vstrczh:
3007   case SystemZ::BI__builtin_s390_vstrczf:
3008   case SystemZ::BI__builtin_s390_vstrcbs:
3009   case SystemZ::BI__builtin_s390_vstrchs:
3010   case SystemZ::BI__builtin_s390_vstrcfs:
3011   case SystemZ::BI__builtin_s390_vstrczbs:
3012   case SystemZ::BI__builtin_s390_vstrczhs:
3013   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3014   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3015   case SystemZ::BI__builtin_s390_vfminsb:
3016   case SystemZ::BI__builtin_s390_vfmaxsb:
3017   case SystemZ::BI__builtin_s390_vfmindb:
3018   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3019   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3020   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3021   }
3022   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3023 }
3024 
3025 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3026 /// This checks that the target supports __builtin_cpu_supports and
3027 /// that the string argument is constant and valid.
3028 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3029   Expr *Arg = TheCall->getArg(0);
3030 
3031   // Check if the argument is a string literal.
3032   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3033     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3034            << Arg->getSourceRange();
3035 
3036   // Check the contents of the string.
3037   StringRef Feature =
3038       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3039   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3040     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3041            << Arg->getSourceRange();
3042   return false;
3043 }
3044 
3045 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3046 /// This checks that the target supports __builtin_cpu_is and
3047 /// that the string argument is constant and valid.
3048 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3049   Expr *Arg = TheCall->getArg(0);
3050 
3051   // Check if the argument is a string literal.
3052   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3053     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3054            << Arg->getSourceRange();
3055 
3056   // Check the contents of the string.
3057   StringRef Feature =
3058       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3059   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3060     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3061            << Arg->getSourceRange();
3062   return false;
3063 }
3064 
3065 // Check if the rounding mode is legal.
3066 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3067   // Indicates if this instruction has rounding control or just SAE.
3068   bool HasRC = false;
3069 
3070   unsigned ArgNum = 0;
3071   switch (BuiltinID) {
3072   default:
3073     return false;
3074   case X86::BI__builtin_ia32_vcvttsd2si32:
3075   case X86::BI__builtin_ia32_vcvttsd2si64:
3076   case X86::BI__builtin_ia32_vcvttsd2usi32:
3077   case X86::BI__builtin_ia32_vcvttsd2usi64:
3078   case X86::BI__builtin_ia32_vcvttss2si32:
3079   case X86::BI__builtin_ia32_vcvttss2si64:
3080   case X86::BI__builtin_ia32_vcvttss2usi32:
3081   case X86::BI__builtin_ia32_vcvttss2usi64:
3082     ArgNum = 1;
3083     break;
3084   case X86::BI__builtin_ia32_maxpd512:
3085   case X86::BI__builtin_ia32_maxps512:
3086   case X86::BI__builtin_ia32_minpd512:
3087   case X86::BI__builtin_ia32_minps512:
3088     ArgNum = 2;
3089     break;
3090   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3091   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3092   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3093   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3094   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3095   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3096   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3097   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3098   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3099   case X86::BI__builtin_ia32_exp2pd_mask:
3100   case X86::BI__builtin_ia32_exp2ps_mask:
3101   case X86::BI__builtin_ia32_getexppd512_mask:
3102   case X86::BI__builtin_ia32_getexpps512_mask:
3103   case X86::BI__builtin_ia32_rcp28pd_mask:
3104   case X86::BI__builtin_ia32_rcp28ps_mask:
3105   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3106   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3107   case X86::BI__builtin_ia32_vcomisd:
3108   case X86::BI__builtin_ia32_vcomiss:
3109   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3110     ArgNum = 3;
3111     break;
3112   case X86::BI__builtin_ia32_cmppd512_mask:
3113   case X86::BI__builtin_ia32_cmpps512_mask:
3114   case X86::BI__builtin_ia32_cmpsd_mask:
3115   case X86::BI__builtin_ia32_cmpss_mask:
3116   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3117   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3118   case X86::BI__builtin_ia32_getexpss128_round_mask:
3119   case X86::BI__builtin_ia32_getmantpd512_mask:
3120   case X86::BI__builtin_ia32_getmantps512_mask:
3121   case X86::BI__builtin_ia32_maxsd_round_mask:
3122   case X86::BI__builtin_ia32_maxss_round_mask:
3123   case X86::BI__builtin_ia32_minsd_round_mask:
3124   case X86::BI__builtin_ia32_minss_round_mask:
3125   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3126   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3127   case X86::BI__builtin_ia32_reducepd512_mask:
3128   case X86::BI__builtin_ia32_reduceps512_mask:
3129   case X86::BI__builtin_ia32_rndscalepd_mask:
3130   case X86::BI__builtin_ia32_rndscaleps_mask:
3131   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3132   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3133     ArgNum = 4;
3134     break;
3135   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3136   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3137   case X86::BI__builtin_ia32_fixupimmps512_mask:
3138   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3139   case X86::BI__builtin_ia32_fixupimmsd_mask:
3140   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3141   case X86::BI__builtin_ia32_fixupimmss_mask:
3142   case X86::BI__builtin_ia32_fixupimmss_maskz:
3143   case X86::BI__builtin_ia32_getmantsd_round_mask:
3144   case X86::BI__builtin_ia32_getmantss_round_mask:
3145   case X86::BI__builtin_ia32_rangepd512_mask:
3146   case X86::BI__builtin_ia32_rangeps512_mask:
3147   case X86::BI__builtin_ia32_rangesd128_round_mask:
3148   case X86::BI__builtin_ia32_rangess128_round_mask:
3149   case X86::BI__builtin_ia32_reducesd_mask:
3150   case X86::BI__builtin_ia32_reducess_mask:
3151   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3152   case X86::BI__builtin_ia32_rndscaless_round_mask:
3153     ArgNum = 5;
3154     break;
3155   case X86::BI__builtin_ia32_vcvtsd2si64:
3156   case X86::BI__builtin_ia32_vcvtsd2si32:
3157   case X86::BI__builtin_ia32_vcvtsd2usi32:
3158   case X86::BI__builtin_ia32_vcvtsd2usi64:
3159   case X86::BI__builtin_ia32_vcvtss2si32:
3160   case X86::BI__builtin_ia32_vcvtss2si64:
3161   case X86::BI__builtin_ia32_vcvtss2usi32:
3162   case X86::BI__builtin_ia32_vcvtss2usi64:
3163   case X86::BI__builtin_ia32_sqrtpd512:
3164   case X86::BI__builtin_ia32_sqrtps512:
3165     ArgNum = 1;
3166     HasRC = true;
3167     break;
3168   case X86::BI__builtin_ia32_addpd512:
3169   case X86::BI__builtin_ia32_addps512:
3170   case X86::BI__builtin_ia32_divpd512:
3171   case X86::BI__builtin_ia32_divps512:
3172   case X86::BI__builtin_ia32_mulpd512:
3173   case X86::BI__builtin_ia32_mulps512:
3174   case X86::BI__builtin_ia32_subpd512:
3175   case X86::BI__builtin_ia32_subps512:
3176   case X86::BI__builtin_ia32_cvtsi2sd64:
3177   case X86::BI__builtin_ia32_cvtsi2ss32:
3178   case X86::BI__builtin_ia32_cvtsi2ss64:
3179   case X86::BI__builtin_ia32_cvtusi2sd64:
3180   case X86::BI__builtin_ia32_cvtusi2ss32:
3181   case X86::BI__builtin_ia32_cvtusi2ss64:
3182     ArgNum = 2;
3183     HasRC = true;
3184     break;
3185   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3186   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3187   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3188   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3189   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3190   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3191   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3192   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3193   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3194   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3195   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3196   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3197   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3198   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3199   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3200     ArgNum = 3;
3201     HasRC = true;
3202     break;
3203   case X86::BI__builtin_ia32_addss_round_mask:
3204   case X86::BI__builtin_ia32_addsd_round_mask:
3205   case X86::BI__builtin_ia32_divss_round_mask:
3206   case X86::BI__builtin_ia32_divsd_round_mask:
3207   case X86::BI__builtin_ia32_mulss_round_mask:
3208   case X86::BI__builtin_ia32_mulsd_round_mask:
3209   case X86::BI__builtin_ia32_subss_round_mask:
3210   case X86::BI__builtin_ia32_subsd_round_mask:
3211   case X86::BI__builtin_ia32_scalefpd512_mask:
3212   case X86::BI__builtin_ia32_scalefps512_mask:
3213   case X86::BI__builtin_ia32_scalefsd_round_mask:
3214   case X86::BI__builtin_ia32_scalefss_round_mask:
3215   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3216   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3217   case X86::BI__builtin_ia32_sqrtss_round_mask:
3218   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3219   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3220   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3221   case X86::BI__builtin_ia32_vfmaddss3_mask:
3222   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3223   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3224   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3225   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3226   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3227   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3228   case X86::BI__builtin_ia32_vfmaddps512_mask:
3229   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3230   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3231   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3232   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3233   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3234   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3235   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3236   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3237   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3238   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3239   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3240     ArgNum = 4;
3241     HasRC = true;
3242     break;
3243   }
3244 
3245   llvm::APSInt Result;
3246 
3247   // We can't check the value of a dependent argument.
3248   Expr *Arg = TheCall->getArg(ArgNum);
3249   if (Arg->isTypeDependent() || Arg->isValueDependent())
3250     return false;
3251 
3252   // Check constant-ness first.
3253   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3254     return true;
3255 
3256   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3257   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3258   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3259   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3260   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3261       Result == 8/*ROUND_NO_EXC*/ ||
3262       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3263       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3264     return false;
3265 
3266   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3267          << Arg->getSourceRange();
3268 }
3269 
3270 // Check if the gather/scatter scale is legal.
3271 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3272                                              CallExpr *TheCall) {
3273   unsigned ArgNum = 0;
3274   switch (BuiltinID) {
3275   default:
3276     return false;
3277   case X86::BI__builtin_ia32_gatherpfdpd:
3278   case X86::BI__builtin_ia32_gatherpfdps:
3279   case X86::BI__builtin_ia32_gatherpfqpd:
3280   case X86::BI__builtin_ia32_gatherpfqps:
3281   case X86::BI__builtin_ia32_scatterpfdpd:
3282   case X86::BI__builtin_ia32_scatterpfdps:
3283   case X86::BI__builtin_ia32_scatterpfqpd:
3284   case X86::BI__builtin_ia32_scatterpfqps:
3285     ArgNum = 3;
3286     break;
3287   case X86::BI__builtin_ia32_gatherd_pd:
3288   case X86::BI__builtin_ia32_gatherd_pd256:
3289   case X86::BI__builtin_ia32_gatherq_pd:
3290   case X86::BI__builtin_ia32_gatherq_pd256:
3291   case X86::BI__builtin_ia32_gatherd_ps:
3292   case X86::BI__builtin_ia32_gatherd_ps256:
3293   case X86::BI__builtin_ia32_gatherq_ps:
3294   case X86::BI__builtin_ia32_gatherq_ps256:
3295   case X86::BI__builtin_ia32_gatherd_q:
3296   case X86::BI__builtin_ia32_gatherd_q256:
3297   case X86::BI__builtin_ia32_gatherq_q:
3298   case X86::BI__builtin_ia32_gatherq_q256:
3299   case X86::BI__builtin_ia32_gatherd_d:
3300   case X86::BI__builtin_ia32_gatherd_d256:
3301   case X86::BI__builtin_ia32_gatherq_d:
3302   case X86::BI__builtin_ia32_gatherq_d256:
3303   case X86::BI__builtin_ia32_gather3div2df:
3304   case X86::BI__builtin_ia32_gather3div2di:
3305   case X86::BI__builtin_ia32_gather3div4df:
3306   case X86::BI__builtin_ia32_gather3div4di:
3307   case X86::BI__builtin_ia32_gather3div4sf:
3308   case X86::BI__builtin_ia32_gather3div4si:
3309   case X86::BI__builtin_ia32_gather3div8sf:
3310   case X86::BI__builtin_ia32_gather3div8si:
3311   case X86::BI__builtin_ia32_gather3siv2df:
3312   case X86::BI__builtin_ia32_gather3siv2di:
3313   case X86::BI__builtin_ia32_gather3siv4df:
3314   case X86::BI__builtin_ia32_gather3siv4di:
3315   case X86::BI__builtin_ia32_gather3siv4sf:
3316   case X86::BI__builtin_ia32_gather3siv4si:
3317   case X86::BI__builtin_ia32_gather3siv8sf:
3318   case X86::BI__builtin_ia32_gather3siv8si:
3319   case X86::BI__builtin_ia32_gathersiv8df:
3320   case X86::BI__builtin_ia32_gathersiv16sf:
3321   case X86::BI__builtin_ia32_gatherdiv8df:
3322   case X86::BI__builtin_ia32_gatherdiv16sf:
3323   case X86::BI__builtin_ia32_gathersiv8di:
3324   case X86::BI__builtin_ia32_gathersiv16si:
3325   case X86::BI__builtin_ia32_gatherdiv8di:
3326   case X86::BI__builtin_ia32_gatherdiv16si:
3327   case X86::BI__builtin_ia32_scatterdiv2df:
3328   case X86::BI__builtin_ia32_scatterdiv2di:
3329   case X86::BI__builtin_ia32_scatterdiv4df:
3330   case X86::BI__builtin_ia32_scatterdiv4di:
3331   case X86::BI__builtin_ia32_scatterdiv4sf:
3332   case X86::BI__builtin_ia32_scatterdiv4si:
3333   case X86::BI__builtin_ia32_scatterdiv8sf:
3334   case X86::BI__builtin_ia32_scatterdiv8si:
3335   case X86::BI__builtin_ia32_scattersiv2df:
3336   case X86::BI__builtin_ia32_scattersiv2di:
3337   case X86::BI__builtin_ia32_scattersiv4df:
3338   case X86::BI__builtin_ia32_scattersiv4di:
3339   case X86::BI__builtin_ia32_scattersiv4sf:
3340   case X86::BI__builtin_ia32_scattersiv4si:
3341   case X86::BI__builtin_ia32_scattersiv8sf:
3342   case X86::BI__builtin_ia32_scattersiv8si:
3343   case X86::BI__builtin_ia32_scattersiv8df:
3344   case X86::BI__builtin_ia32_scattersiv16sf:
3345   case X86::BI__builtin_ia32_scatterdiv8df:
3346   case X86::BI__builtin_ia32_scatterdiv16sf:
3347   case X86::BI__builtin_ia32_scattersiv8di:
3348   case X86::BI__builtin_ia32_scattersiv16si:
3349   case X86::BI__builtin_ia32_scatterdiv8di:
3350   case X86::BI__builtin_ia32_scatterdiv16si:
3351     ArgNum = 4;
3352     break;
3353   }
3354 
3355   llvm::APSInt Result;
3356 
3357   // We can't check the value of a dependent argument.
3358   Expr *Arg = TheCall->getArg(ArgNum);
3359   if (Arg->isTypeDependent() || Arg->isValueDependent())
3360     return false;
3361 
3362   // Check constant-ness first.
3363   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3364     return true;
3365 
3366   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3367     return false;
3368 
3369   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3370          << Arg->getSourceRange();
3371 }
3372 
3373 static bool isX86_32Builtin(unsigned BuiltinID) {
3374   // These builtins only work on x86-32 targets.
3375   switch (BuiltinID) {
3376   case X86::BI__builtin_ia32_readeflags_u32:
3377   case X86::BI__builtin_ia32_writeeflags_u32:
3378     return true;
3379   }
3380 
3381   return false;
3382 }
3383 
3384 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3385   if (BuiltinID == X86::BI__builtin_cpu_supports)
3386     return SemaBuiltinCpuSupports(*this, TheCall);
3387 
3388   if (BuiltinID == X86::BI__builtin_cpu_is)
3389     return SemaBuiltinCpuIs(*this, TheCall);
3390 
3391   // Check for 32-bit only builtins on a 64-bit target.
3392   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3393   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3394     return Diag(TheCall->getCallee()->getBeginLoc(),
3395                 diag::err_32_bit_builtin_64_bit_tgt);
3396 
3397   // If the intrinsic has rounding or SAE make sure its valid.
3398   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3399     return true;
3400 
3401   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3402   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3403     return true;
3404 
3405   // For intrinsics which take an immediate value as part of the instruction,
3406   // range check them here.
3407   int i = 0, l = 0, u = 0;
3408   switch (BuiltinID) {
3409   default:
3410     return false;
3411   case X86::BI__builtin_ia32_vec_ext_v2si:
3412   case X86::BI__builtin_ia32_vec_ext_v2di:
3413   case X86::BI__builtin_ia32_vextractf128_pd256:
3414   case X86::BI__builtin_ia32_vextractf128_ps256:
3415   case X86::BI__builtin_ia32_vextractf128_si256:
3416   case X86::BI__builtin_ia32_extract128i256:
3417   case X86::BI__builtin_ia32_extractf64x4_mask:
3418   case X86::BI__builtin_ia32_extracti64x4_mask:
3419   case X86::BI__builtin_ia32_extractf32x8_mask:
3420   case X86::BI__builtin_ia32_extracti32x8_mask:
3421   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3422   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3423   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3424   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3425     i = 1; l = 0; u = 1;
3426     break;
3427   case X86::BI__builtin_ia32_vec_set_v2di:
3428   case X86::BI__builtin_ia32_vinsertf128_pd256:
3429   case X86::BI__builtin_ia32_vinsertf128_ps256:
3430   case X86::BI__builtin_ia32_vinsertf128_si256:
3431   case X86::BI__builtin_ia32_insert128i256:
3432   case X86::BI__builtin_ia32_insertf32x8:
3433   case X86::BI__builtin_ia32_inserti32x8:
3434   case X86::BI__builtin_ia32_insertf64x4:
3435   case X86::BI__builtin_ia32_inserti64x4:
3436   case X86::BI__builtin_ia32_insertf64x2_256:
3437   case X86::BI__builtin_ia32_inserti64x2_256:
3438   case X86::BI__builtin_ia32_insertf32x4_256:
3439   case X86::BI__builtin_ia32_inserti32x4_256:
3440     i = 2; l = 0; u = 1;
3441     break;
3442   case X86::BI__builtin_ia32_vpermilpd:
3443   case X86::BI__builtin_ia32_vec_ext_v4hi:
3444   case X86::BI__builtin_ia32_vec_ext_v4si:
3445   case X86::BI__builtin_ia32_vec_ext_v4sf:
3446   case X86::BI__builtin_ia32_vec_ext_v4di:
3447   case X86::BI__builtin_ia32_extractf32x4_mask:
3448   case X86::BI__builtin_ia32_extracti32x4_mask:
3449   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3450   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3451     i = 1; l = 0; u = 3;
3452     break;
3453   case X86::BI_mm_prefetch:
3454   case X86::BI__builtin_ia32_vec_ext_v8hi:
3455   case X86::BI__builtin_ia32_vec_ext_v8si:
3456     i = 1; l = 0; u = 7;
3457     break;
3458   case X86::BI__builtin_ia32_sha1rnds4:
3459   case X86::BI__builtin_ia32_blendpd:
3460   case X86::BI__builtin_ia32_shufpd:
3461   case X86::BI__builtin_ia32_vec_set_v4hi:
3462   case X86::BI__builtin_ia32_vec_set_v4si:
3463   case X86::BI__builtin_ia32_vec_set_v4di:
3464   case X86::BI__builtin_ia32_shuf_f32x4_256:
3465   case X86::BI__builtin_ia32_shuf_f64x2_256:
3466   case X86::BI__builtin_ia32_shuf_i32x4_256:
3467   case X86::BI__builtin_ia32_shuf_i64x2_256:
3468   case X86::BI__builtin_ia32_insertf64x2_512:
3469   case X86::BI__builtin_ia32_inserti64x2_512:
3470   case X86::BI__builtin_ia32_insertf32x4:
3471   case X86::BI__builtin_ia32_inserti32x4:
3472     i = 2; l = 0; u = 3;
3473     break;
3474   case X86::BI__builtin_ia32_vpermil2pd:
3475   case X86::BI__builtin_ia32_vpermil2pd256:
3476   case X86::BI__builtin_ia32_vpermil2ps:
3477   case X86::BI__builtin_ia32_vpermil2ps256:
3478     i = 3; l = 0; u = 3;
3479     break;
3480   case X86::BI__builtin_ia32_cmpb128_mask:
3481   case X86::BI__builtin_ia32_cmpw128_mask:
3482   case X86::BI__builtin_ia32_cmpd128_mask:
3483   case X86::BI__builtin_ia32_cmpq128_mask:
3484   case X86::BI__builtin_ia32_cmpb256_mask:
3485   case X86::BI__builtin_ia32_cmpw256_mask:
3486   case X86::BI__builtin_ia32_cmpd256_mask:
3487   case X86::BI__builtin_ia32_cmpq256_mask:
3488   case X86::BI__builtin_ia32_cmpb512_mask:
3489   case X86::BI__builtin_ia32_cmpw512_mask:
3490   case X86::BI__builtin_ia32_cmpd512_mask:
3491   case X86::BI__builtin_ia32_cmpq512_mask:
3492   case X86::BI__builtin_ia32_ucmpb128_mask:
3493   case X86::BI__builtin_ia32_ucmpw128_mask:
3494   case X86::BI__builtin_ia32_ucmpd128_mask:
3495   case X86::BI__builtin_ia32_ucmpq128_mask:
3496   case X86::BI__builtin_ia32_ucmpb256_mask:
3497   case X86::BI__builtin_ia32_ucmpw256_mask:
3498   case X86::BI__builtin_ia32_ucmpd256_mask:
3499   case X86::BI__builtin_ia32_ucmpq256_mask:
3500   case X86::BI__builtin_ia32_ucmpb512_mask:
3501   case X86::BI__builtin_ia32_ucmpw512_mask:
3502   case X86::BI__builtin_ia32_ucmpd512_mask:
3503   case X86::BI__builtin_ia32_ucmpq512_mask:
3504   case X86::BI__builtin_ia32_vpcomub:
3505   case X86::BI__builtin_ia32_vpcomuw:
3506   case X86::BI__builtin_ia32_vpcomud:
3507   case X86::BI__builtin_ia32_vpcomuq:
3508   case X86::BI__builtin_ia32_vpcomb:
3509   case X86::BI__builtin_ia32_vpcomw:
3510   case X86::BI__builtin_ia32_vpcomd:
3511   case X86::BI__builtin_ia32_vpcomq:
3512   case X86::BI__builtin_ia32_vec_set_v8hi:
3513   case X86::BI__builtin_ia32_vec_set_v8si:
3514     i = 2; l = 0; u = 7;
3515     break;
3516   case X86::BI__builtin_ia32_vpermilpd256:
3517   case X86::BI__builtin_ia32_roundps:
3518   case X86::BI__builtin_ia32_roundpd:
3519   case X86::BI__builtin_ia32_roundps256:
3520   case X86::BI__builtin_ia32_roundpd256:
3521   case X86::BI__builtin_ia32_getmantpd128_mask:
3522   case X86::BI__builtin_ia32_getmantpd256_mask:
3523   case X86::BI__builtin_ia32_getmantps128_mask:
3524   case X86::BI__builtin_ia32_getmantps256_mask:
3525   case X86::BI__builtin_ia32_getmantpd512_mask:
3526   case X86::BI__builtin_ia32_getmantps512_mask:
3527   case X86::BI__builtin_ia32_vec_ext_v16qi:
3528   case X86::BI__builtin_ia32_vec_ext_v16hi:
3529     i = 1; l = 0; u = 15;
3530     break;
3531   case X86::BI__builtin_ia32_pblendd128:
3532   case X86::BI__builtin_ia32_blendps:
3533   case X86::BI__builtin_ia32_blendpd256:
3534   case X86::BI__builtin_ia32_shufpd256:
3535   case X86::BI__builtin_ia32_roundss:
3536   case X86::BI__builtin_ia32_roundsd:
3537   case X86::BI__builtin_ia32_rangepd128_mask:
3538   case X86::BI__builtin_ia32_rangepd256_mask:
3539   case X86::BI__builtin_ia32_rangepd512_mask:
3540   case X86::BI__builtin_ia32_rangeps128_mask:
3541   case X86::BI__builtin_ia32_rangeps256_mask:
3542   case X86::BI__builtin_ia32_rangeps512_mask:
3543   case X86::BI__builtin_ia32_getmantsd_round_mask:
3544   case X86::BI__builtin_ia32_getmantss_round_mask:
3545   case X86::BI__builtin_ia32_vec_set_v16qi:
3546   case X86::BI__builtin_ia32_vec_set_v16hi:
3547     i = 2; l = 0; u = 15;
3548     break;
3549   case X86::BI__builtin_ia32_vec_ext_v32qi:
3550     i = 1; l = 0; u = 31;
3551     break;
3552   case X86::BI__builtin_ia32_cmpps:
3553   case X86::BI__builtin_ia32_cmpss:
3554   case X86::BI__builtin_ia32_cmppd:
3555   case X86::BI__builtin_ia32_cmpsd:
3556   case X86::BI__builtin_ia32_cmpps256:
3557   case X86::BI__builtin_ia32_cmppd256:
3558   case X86::BI__builtin_ia32_cmpps128_mask:
3559   case X86::BI__builtin_ia32_cmppd128_mask:
3560   case X86::BI__builtin_ia32_cmpps256_mask:
3561   case X86::BI__builtin_ia32_cmppd256_mask:
3562   case X86::BI__builtin_ia32_cmpps512_mask:
3563   case X86::BI__builtin_ia32_cmppd512_mask:
3564   case X86::BI__builtin_ia32_cmpsd_mask:
3565   case X86::BI__builtin_ia32_cmpss_mask:
3566   case X86::BI__builtin_ia32_vec_set_v32qi:
3567     i = 2; l = 0; u = 31;
3568     break;
3569   case X86::BI__builtin_ia32_permdf256:
3570   case X86::BI__builtin_ia32_permdi256:
3571   case X86::BI__builtin_ia32_permdf512:
3572   case X86::BI__builtin_ia32_permdi512:
3573   case X86::BI__builtin_ia32_vpermilps:
3574   case X86::BI__builtin_ia32_vpermilps256:
3575   case X86::BI__builtin_ia32_vpermilpd512:
3576   case X86::BI__builtin_ia32_vpermilps512:
3577   case X86::BI__builtin_ia32_pshufd:
3578   case X86::BI__builtin_ia32_pshufd256:
3579   case X86::BI__builtin_ia32_pshufd512:
3580   case X86::BI__builtin_ia32_pshufhw:
3581   case X86::BI__builtin_ia32_pshufhw256:
3582   case X86::BI__builtin_ia32_pshufhw512:
3583   case X86::BI__builtin_ia32_pshuflw:
3584   case X86::BI__builtin_ia32_pshuflw256:
3585   case X86::BI__builtin_ia32_pshuflw512:
3586   case X86::BI__builtin_ia32_vcvtps2ph:
3587   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3588   case X86::BI__builtin_ia32_vcvtps2ph256:
3589   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3590   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3591   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3592   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3593   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3594   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3595   case X86::BI__builtin_ia32_rndscaleps_mask:
3596   case X86::BI__builtin_ia32_rndscalepd_mask:
3597   case X86::BI__builtin_ia32_reducepd128_mask:
3598   case X86::BI__builtin_ia32_reducepd256_mask:
3599   case X86::BI__builtin_ia32_reducepd512_mask:
3600   case X86::BI__builtin_ia32_reduceps128_mask:
3601   case X86::BI__builtin_ia32_reduceps256_mask:
3602   case X86::BI__builtin_ia32_reduceps512_mask:
3603   case X86::BI__builtin_ia32_prold512:
3604   case X86::BI__builtin_ia32_prolq512:
3605   case X86::BI__builtin_ia32_prold128:
3606   case X86::BI__builtin_ia32_prold256:
3607   case X86::BI__builtin_ia32_prolq128:
3608   case X86::BI__builtin_ia32_prolq256:
3609   case X86::BI__builtin_ia32_prord512:
3610   case X86::BI__builtin_ia32_prorq512:
3611   case X86::BI__builtin_ia32_prord128:
3612   case X86::BI__builtin_ia32_prord256:
3613   case X86::BI__builtin_ia32_prorq128:
3614   case X86::BI__builtin_ia32_prorq256:
3615   case X86::BI__builtin_ia32_fpclasspd128_mask:
3616   case X86::BI__builtin_ia32_fpclasspd256_mask:
3617   case X86::BI__builtin_ia32_fpclassps128_mask:
3618   case X86::BI__builtin_ia32_fpclassps256_mask:
3619   case X86::BI__builtin_ia32_fpclassps512_mask:
3620   case X86::BI__builtin_ia32_fpclasspd512_mask:
3621   case X86::BI__builtin_ia32_fpclasssd_mask:
3622   case X86::BI__builtin_ia32_fpclassss_mask:
3623   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3624   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3625   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3626   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3627   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3628   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3629   case X86::BI__builtin_ia32_kshiftliqi:
3630   case X86::BI__builtin_ia32_kshiftlihi:
3631   case X86::BI__builtin_ia32_kshiftlisi:
3632   case X86::BI__builtin_ia32_kshiftlidi:
3633   case X86::BI__builtin_ia32_kshiftriqi:
3634   case X86::BI__builtin_ia32_kshiftrihi:
3635   case X86::BI__builtin_ia32_kshiftrisi:
3636   case X86::BI__builtin_ia32_kshiftridi:
3637     i = 1; l = 0; u = 255;
3638     break;
3639   case X86::BI__builtin_ia32_vperm2f128_pd256:
3640   case X86::BI__builtin_ia32_vperm2f128_ps256:
3641   case X86::BI__builtin_ia32_vperm2f128_si256:
3642   case X86::BI__builtin_ia32_permti256:
3643   case X86::BI__builtin_ia32_pblendw128:
3644   case X86::BI__builtin_ia32_pblendw256:
3645   case X86::BI__builtin_ia32_blendps256:
3646   case X86::BI__builtin_ia32_pblendd256:
3647   case X86::BI__builtin_ia32_palignr128:
3648   case X86::BI__builtin_ia32_palignr256:
3649   case X86::BI__builtin_ia32_palignr512:
3650   case X86::BI__builtin_ia32_alignq512:
3651   case X86::BI__builtin_ia32_alignd512:
3652   case X86::BI__builtin_ia32_alignd128:
3653   case X86::BI__builtin_ia32_alignd256:
3654   case X86::BI__builtin_ia32_alignq128:
3655   case X86::BI__builtin_ia32_alignq256:
3656   case X86::BI__builtin_ia32_vcomisd:
3657   case X86::BI__builtin_ia32_vcomiss:
3658   case X86::BI__builtin_ia32_shuf_f32x4:
3659   case X86::BI__builtin_ia32_shuf_f64x2:
3660   case X86::BI__builtin_ia32_shuf_i32x4:
3661   case X86::BI__builtin_ia32_shuf_i64x2:
3662   case X86::BI__builtin_ia32_shufpd512:
3663   case X86::BI__builtin_ia32_shufps:
3664   case X86::BI__builtin_ia32_shufps256:
3665   case X86::BI__builtin_ia32_shufps512:
3666   case X86::BI__builtin_ia32_dbpsadbw128:
3667   case X86::BI__builtin_ia32_dbpsadbw256:
3668   case X86::BI__builtin_ia32_dbpsadbw512:
3669   case X86::BI__builtin_ia32_vpshldd128:
3670   case X86::BI__builtin_ia32_vpshldd256:
3671   case X86::BI__builtin_ia32_vpshldd512:
3672   case X86::BI__builtin_ia32_vpshldq128:
3673   case X86::BI__builtin_ia32_vpshldq256:
3674   case X86::BI__builtin_ia32_vpshldq512:
3675   case X86::BI__builtin_ia32_vpshldw128:
3676   case X86::BI__builtin_ia32_vpshldw256:
3677   case X86::BI__builtin_ia32_vpshldw512:
3678   case X86::BI__builtin_ia32_vpshrdd128:
3679   case X86::BI__builtin_ia32_vpshrdd256:
3680   case X86::BI__builtin_ia32_vpshrdd512:
3681   case X86::BI__builtin_ia32_vpshrdq128:
3682   case X86::BI__builtin_ia32_vpshrdq256:
3683   case X86::BI__builtin_ia32_vpshrdq512:
3684   case X86::BI__builtin_ia32_vpshrdw128:
3685   case X86::BI__builtin_ia32_vpshrdw256:
3686   case X86::BI__builtin_ia32_vpshrdw512:
3687     i = 2; l = 0; u = 255;
3688     break;
3689   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3690   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3691   case X86::BI__builtin_ia32_fixupimmps512_mask:
3692   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3693   case X86::BI__builtin_ia32_fixupimmsd_mask:
3694   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3695   case X86::BI__builtin_ia32_fixupimmss_mask:
3696   case X86::BI__builtin_ia32_fixupimmss_maskz:
3697   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3698   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3699   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3700   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3701   case X86::BI__builtin_ia32_fixupimmps128_mask:
3702   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3703   case X86::BI__builtin_ia32_fixupimmps256_mask:
3704   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3705   case X86::BI__builtin_ia32_pternlogd512_mask:
3706   case X86::BI__builtin_ia32_pternlogd512_maskz:
3707   case X86::BI__builtin_ia32_pternlogq512_mask:
3708   case X86::BI__builtin_ia32_pternlogq512_maskz:
3709   case X86::BI__builtin_ia32_pternlogd128_mask:
3710   case X86::BI__builtin_ia32_pternlogd128_maskz:
3711   case X86::BI__builtin_ia32_pternlogd256_mask:
3712   case X86::BI__builtin_ia32_pternlogd256_maskz:
3713   case X86::BI__builtin_ia32_pternlogq128_mask:
3714   case X86::BI__builtin_ia32_pternlogq128_maskz:
3715   case X86::BI__builtin_ia32_pternlogq256_mask:
3716   case X86::BI__builtin_ia32_pternlogq256_maskz:
3717     i = 3; l = 0; u = 255;
3718     break;
3719   case X86::BI__builtin_ia32_gatherpfdpd:
3720   case X86::BI__builtin_ia32_gatherpfdps:
3721   case X86::BI__builtin_ia32_gatherpfqpd:
3722   case X86::BI__builtin_ia32_gatherpfqps:
3723   case X86::BI__builtin_ia32_scatterpfdpd:
3724   case X86::BI__builtin_ia32_scatterpfdps:
3725   case X86::BI__builtin_ia32_scatterpfqpd:
3726   case X86::BI__builtin_ia32_scatterpfqps:
3727     i = 4; l = 2; u = 3;
3728     break;
3729   case X86::BI__builtin_ia32_reducesd_mask:
3730   case X86::BI__builtin_ia32_reducess_mask:
3731   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3732   case X86::BI__builtin_ia32_rndscaless_round_mask:
3733     i = 4; l = 0; u = 255;
3734     break;
3735   }
3736 
3737   // Note that we don't force a hard error on the range check here, allowing
3738   // template-generated or macro-generated dead code to potentially have out-of-
3739   // range values. These need to code generate, but don't need to necessarily
3740   // make any sense. We use a warning that defaults to an error.
3741   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3742 }
3743 
3744 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3745 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3746 /// Returns true when the format fits the function and the FormatStringInfo has
3747 /// been populated.
3748 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3749                                FormatStringInfo *FSI) {
3750   FSI->HasVAListArg = Format->getFirstArg() == 0;
3751   FSI->FormatIdx = Format->getFormatIdx() - 1;
3752   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3753 
3754   // The way the format attribute works in GCC, the implicit this argument
3755   // of member functions is counted. However, it doesn't appear in our own
3756   // lists, so decrement format_idx in that case.
3757   if (IsCXXMember) {
3758     if(FSI->FormatIdx == 0)
3759       return false;
3760     --FSI->FormatIdx;
3761     if (FSI->FirstDataArg != 0)
3762       --FSI->FirstDataArg;
3763   }
3764   return true;
3765 }
3766 
3767 /// Checks if a the given expression evaluates to null.
3768 ///
3769 /// Returns true if the value evaluates to null.
3770 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3771   // If the expression has non-null type, it doesn't evaluate to null.
3772   if (auto nullability
3773         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3774     if (*nullability == NullabilityKind::NonNull)
3775       return false;
3776   }
3777 
3778   // As a special case, transparent unions initialized with zero are
3779   // considered null for the purposes of the nonnull attribute.
3780   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3781     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3782       if (const CompoundLiteralExpr *CLE =
3783           dyn_cast<CompoundLiteralExpr>(Expr))
3784         if (const InitListExpr *ILE =
3785             dyn_cast<InitListExpr>(CLE->getInitializer()))
3786           Expr = ILE->getInit(0);
3787   }
3788 
3789   bool Result;
3790   return (!Expr->isValueDependent() &&
3791           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3792           !Result);
3793 }
3794 
3795 static void CheckNonNullArgument(Sema &S,
3796                                  const Expr *ArgExpr,
3797                                  SourceLocation CallSiteLoc) {
3798   if (CheckNonNullExpr(S, ArgExpr))
3799     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3800                           S.PDiag(diag::warn_null_arg)
3801                               << ArgExpr->getSourceRange());
3802 }
3803 
3804 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3805   FormatStringInfo FSI;
3806   if ((GetFormatStringType(Format) == FST_NSString) &&
3807       getFormatStringInfo(Format, false, &FSI)) {
3808     Idx = FSI.FormatIdx;
3809     return true;
3810   }
3811   return false;
3812 }
3813 
3814 /// Diagnose use of %s directive in an NSString which is being passed
3815 /// as formatting string to formatting method.
3816 static void
3817 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3818                                         const NamedDecl *FDecl,
3819                                         Expr **Args,
3820                                         unsigned NumArgs) {
3821   unsigned Idx = 0;
3822   bool Format = false;
3823   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3824   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3825     Idx = 2;
3826     Format = true;
3827   }
3828   else
3829     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3830       if (S.GetFormatNSStringIdx(I, Idx)) {
3831         Format = true;
3832         break;
3833       }
3834     }
3835   if (!Format || NumArgs <= Idx)
3836     return;
3837   const Expr *FormatExpr = Args[Idx];
3838   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3839     FormatExpr = CSCE->getSubExpr();
3840   const StringLiteral *FormatString;
3841   if (const ObjCStringLiteral *OSL =
3842       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3843     FormatString = OSL->getString();
3844   else
3845     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3846   if (!FormatString)
3847     return;
3848   if (S.FormatStringHasSArg(FormatString)) {
3849     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3850       << "%s" << 1 << 1;
3851     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3852       << FDecl->getDeclName();
3853   }
3854 }
3855 
3856 /// Determine whether the given type has a non-null nullability annotation.
3857 static bool isNonNullType(ASTContext &ctx, QualType type) {
3858   if (auto nullability = type->getNullability(ctx))
3859     return *nullability == NullabilityKind::NonNull;
3860 
3861   return false;
3862 }
3863 
3864 static void CheckNonNullArguments(Sema &S,
3865                                   const NamedDecl *FDecl,
3866                                   const FunctionProtoType *Proto,
3867                                   ArrayRef<const Expr *> Args,
3868                                   SourceLocation CallSiteLoc) {
3869   assert((FDecl || Proto) && "Need a function declaration or prototype");
3870 
3871   // Already checked by by constant evaluator.
3872   if (S.isConstantEvaluated())
3873     return;
3874   // Check the attributes attached to the method/function itself.
3875   llvm::SmallBitVector NonNullArgs;
3876   if (FDecl) {
3877     // Handle the nonnull attribute on the function/method declaration itself.
3878     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3879       if (!NonNull->args_size()) {
3880         // Easy case: all pointer arguments are nonnull.
3881         for (const auto *Arg : Args)
3882           if (S.isValidPointerAttrType(Arg->getType()))
3883             CheckNonNullArgument(S, Arg, CallSiteLoc);
3884         return;
3885       }
3886 
3887       for (const ParamIdx &Idx : NonNull->args()) {
3888         unsigned IdxAST = Idx.getASTIndex();
3889         if (IdxAST >= Args.size())
3890           continue;
3891         if (NonNullArgs.empty())
3892           NonNullArgs.resize(Args.size());
3893         NonNullArgs.set(IdxAST);
3894       }
3895     }
3896   }
3897 
3898   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3899     // Handle the nonnull attribute on the parameters of the
3900     // function/method.
3901     ArrayRef<ParmVarDecl*> parms;
3902     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3903       parms = FD->parameters();
3904     else
3905       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3906 
3907     unsigned ParamIndex = 0;
3908     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3909          I != E; ++I, ++ParamIndex) {
3910       const ParmVarDecl *PVD = *I;
3911       if (PVD->hasAttr<NonNullAttr>() ||
3912           isNonNullType(S.Context, PVD->getType())) {
3913         if (NonNullArgs.empty())
3914           NonNullArgs.resize(Args.size());
3915 
3916         NonNullArgs.set(ParamIndex);
3917       }
3918     }
3919   } else {
3920     // If we have a non-function, non-method declaration but no
3921     // function prototype, try to dig out the function prototype.
3922     if (!Proto) {
3923       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3924         QualType type = VD->getType().getNonReferenceType();
3925         if (auto pointerType = type->getAs<PointerType>())
3926           type = pointerType->getPointeeType();
3927         else if (auto blockType = type->getAs<BlockPointerType>())
3928           type = blockType->getPointeeType();
3929         // FIXME: data member pointers?
3930 
3931         // Dig out the function prototype, if there is one.
3932         Proto = type->getAs<FunctionProtoType>();
3933       }
3934     }
3935 
3936     // Fill in non-null argument information from the nullability
3937     // information on the parameter types (if we have them).
3938     if (Proto) {
3939       unsigned Index = 0;
3940       for (auto paramType : Proto->getParamTypes()) {
3941         if (isNonNullType(S.Context, paramType)) {
3942           if (NonNullArgs.empty())
3943             NonNullArgs.resize(Args.size());
3944 
3945           NonNullArgs.set(Index);
3946         }
3947 
3948         ++Index;
3949       }
3950     }
3951   }
3952 
3953   // Check for non-null arguments.
3954   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3955        ArgIndex != ArgIndexEnd; ++ArgIndex) {
3956     if (NonNullArgs[ArgIndex])
3957       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
3958   }
3959 }
3960 
3961 /// Handles the checks for format strings, non-POD arguments to vararg
3962 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3963 /// attributes.
3964 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
3965                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
3966                      bool IsMemberFunction, SourceLocation Loc,
3967                      SourceRange Range, VariadicCallType CallType) {
3968   // FIXME: We should check as much as we can in the template definition.
3969   if (CurContext->isDependentContext())
3970     return;
3971 
3972   // Printf and scanf checking.
3973   llvm::SmallBitVector CheckedVarArgs;
3974   if (FDecl) {
3975     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3976       // Only create vector if there are format attributes.
3977       CheckedVarArgs.resize(Args.size());
3978 
3979       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3980                            CheckedVarArgs);
3981     }
3982   }
3983 
3984   // Refuse POD arguments that weren't caught by the format string
3985   // checks above.
3986   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3987   if (CallType != VariadicDoesNotApply &&
3988       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3989     unsigned NumParams = Proto ? Proto->getNumParams()
3990                        : FDecl && isa<FunctionDecl>(FDecl)
3991                            ? cast<FunctionDecl>(FDecl)->getNumParams()
3992                        : FDecl && isa<ObjCMethodDecl>(FDecl)
3993                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
3994                        : 0;
3995 
3996     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3997       // Args[ArgIdx] can be null in malformed code.
3998       if (const Expr *Arg = Args[ArgIdx]) {
3999         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4000           checkVariadicArgument(Arg, CallType);
4001       }
4002     }
4003   }
4004 
4005   if (FDecl || Proto) {
4006     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4007 
4008     // Type safety checking.
4009     if (FDecl) {
4010       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4011         CheckArgumentWithTypeTag(I, Args, Loc);
4012     }
4013   }
4014 
4015   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4016     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4017     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4018     if (!Arg->isValueDependent()) {
4019       Expr::EvalResult Align;
4020       if (Arg->EvaluateAsInt(Align, Context)) {
4021         const llvm::APSInt &I = Align.Val.getInt();
4022         if (!I.isPowerOf2())
4023           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4024               << Arg->getSourceRange();
4025 
4026         if (I > Sema::MaximumAlignment)
4027           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4028               << Arg->getSourceRange() << Sema::MaximumAlignment;
4029       }
4030     }
4031   }
4032 
4033   if (FD)
4034     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4035 }
4036 
4037 /// CheckConstructorCall - Check a constructor call for correctness and safety
4038 /// properties not enforced by the C type system.
4039 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4040                                 ArrayRef<const Expr *> Args,
4041                                 const FunctionProtoType *Proto,
4042                                 SourceLocation Loc) {
4043   VariadicCallType CallType =
4044     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4045   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4046             Loc, SourceRange(), CallType);
4047 }
4048 
4049 /// CheckFunctionCall - Check a direct function call for various correctness
4050 /// and safety properties not strictly enforced by the C type system.
4051 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4052                              const FunctionProtoType *Proto) {
4053   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4054                               isa<CXXMethodDecl>(FDecl);
4055   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4056                           IsMemberOperatorCall;
4057   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4058                                                   TheCall->getCallee());
4059   Expr** Args = TheCall->getArgs();
4060   unsigned NumArgs = TheCall->getNumArgs();
4061 
4062   Expr *ImplicitThis = nullptr;
4063   if (IsMemberOperatorCall) {
4064     // If this is a call to a member operator, hide the first argument
4065     // from checkCall.
4066     // FIXME: Our choice of AST representation here is less than ideal.
4067     ImplicitThis = Args[0];
4068     ++Args;
4069     --NumArgs;
4070   } else if (IsMemberFunction)
4071     ImplicitThis =
4072         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4073 
4074   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4075             IsMemberFunction, TheCall->getRParenLoc(),
4076             TheCall->getCallee()->getSourceRange(), CallType);
4077 
4078   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4079   // None of the checks below are needed for functions that don't have
4080   // simple names (e.g., C++ conversion functions).
4081   if (!FnInfo)
4082     return false;
4083 
4084   CheckAbsoluteValueFunction(TheCall, FDecl);
4085   CheckMaxUnsignedZero(TheCall, FDecl);
4086 
4087   if (getLangOpts().ObjC)
4088     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4089 
4090   unsigned CMId = FDecl->getMemoryFunctionKind();
4091   if (CMId == 0)
4092     return false;
4093 
4094   // Handle memory setting and copying functions.
4095   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4096     CheckStrlcpycatArguments(TheCall, FnInfo);
4097   else if (CMId == Builtin::BIstrncat)
4098     CheckStrncatArguments(TheCall, FnInfo);
4099   else
4100     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4101 
4102   return false;
4103 }
4104 
4105 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4106                                ArrayRef<const Expr *> Args) {
4107   VariadicCallType CallType =
4108       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4109 
4110   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4111             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4112             CallType);
4113 
4114   return false;
4115 }
4116 
4117 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4118                             const FunctionProtoType *Proto) {
4119   QualType Ty;
4120   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4121     Ty = V->getType().getNonReferenceType();
4122   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4123     Ty = F->getType().getNonReferenceType();
4124   else
4125     return false;
4126 
4127   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4128       !Ty->isFunctionProtoType())
4129     return false;
4130 
4131   VariadicCallType CallType;
4132   if (!Proto || !Proto->isVariadic()) {
4133     CallType = VariadicDoesNotApply;
4134   } else if (Ty->isBlockPointerType()) {
4135     CallType = VariadicBlock;
4136   } else { // Ty->isFunctionPointerType()
4137     CallType = VariadicFunction;
4138   }
4139 
4140   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4141             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4142             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4143             TheCall->getCallee()->getSourceRange(), CallType);
4144 
4145   return false;
4146 }
4147 
4148 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4149 /// such as function pointers returned from functions.
4150 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4151   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4152                                                   TheCall->getCallee());
4153   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4154             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4155             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4156             TheCall->getCallee()->getSourceRange(), CallType);
4157 
4158   return false;
4159 }
4160 
4161 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4162   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4163     return false;
4164 
4165   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4166   switch (Op) {
4167   case AtomicExpr::AO__c11_atomic_init:
4168   case AtomicExpr::AO__opencl_atomic_init:
4169     llvm_unreachable("There is no ordering argument for an init");
4170 
4171   case AtomicExpr::AO__c11_atomic_load:
4172   case AtomicExpr::AO__opencl_atomic_load:
4173   case AtomicExpr::AO__atomic_load_n:
4174   case AtomicExpr::AO__atomic_load:
4175     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4176            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4177 
4178   case AtomicExpr::AO__c11_atomic_store:
4179   case AtomicExpr::AO__opencl_atomic_store:
4180   case AtomicExpr::AO__atomic_store:
4181   case AtomicExpr::AO__atomic_store_n:
4182     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4183            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4184            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4185 
4186   default:
4187     return true;
4188   }
4189 }
4190 
4191 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4192                                          AtomicExpr::AtomicOp Op) {
4193   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4194   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4195   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4196   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4197                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4198                          Op);
4199 }
4200 
4201 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4202                                  SourceLocation RParenLoc, MultiExprArg Args,
4203                                  AtomicExpr::AtomicOp Op,
4204                                  AtomicArgumentOrder ArgOrder) {
4205   // All the non-OpenCL operations take one of the following forms.
4206   // The OpenCL operations take the __c11 forms with one extra argument for
4207   // synchronization scope.
4208   enum {
4209     // C    __c11_atomic_init(A *, C)
4210     Init,
4211 
4212     // C    __c11_atomic_load(A *, int)
4213     Load,
4214 
4215     // void __atomic_load(A *, CP, int)
4216     LoadCopy,
4217 
4218     // void __atomic_store(A *, CP, int)
4219     Copy,
4220 
4221     // C    __c11_atomic_add(A *, M, int)
4222     Arithmetic,
4223 
4224     // C    __atomic_exchange_n(A *, CP, int)
4225     Xchg,
4226 
4227     // void __atomic_exchange(A *, C *, CP, int)
4228     GNUXchg,
4229 
4230     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4231     C11CmpXchg,
4232 
4233     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4234     GNUCmpXchg
4235   } Form = Init;
4236 
4237   const unsigned NumForm = GNUCmpXchg + 1;
4238   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4239   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4240   // where:
4241   //   C is an appropriate type,
4242   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4243   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4244   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4245   //   the int parameters are for orderings.
4246 
4247   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4248       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4249       "need to update code for modified forms");
4250   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4251                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4252                         AtomicExpr::AO__atomic_load,
4253                 "need to update code for modified C11 atomics");
4254   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4255                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4256   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4257                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4258                IsOpenCL;
4259   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4260              Op == AtomicExpr::AO__atomic_store_n ||
4261              Op == AtomicExpr::AO__atomic_exchange_n ||
4262              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4263   bool IsAddSub = false;
4264 
4265   switch (Op) {
4266   case AtomicExpr::AO__c11_atomic_init:
4267   case AtomicExpr::AO__opencl_atomic_init:
4268     Form = Init;
4269     break;
4270 
4271   case AtomicExpr::AO__c11_atomic_load:
4272   case AtomicExpr::AO__opencl_atomic_load:
4273   case AtomicExpr::AO__atomic_load_n:
4274     Form = Load;
4275     break;
4276 
4277   case AtomicExpr::AO__atomic_load:
4278     Form = LoadCopy;
4279     break;
4280 
4281   case AtomicExpr::AO__c11_atomic_store:
4282   case AtomicExpr::AO__opencl_atomic_store:
4283   case AtomicExpr::AO__atomic_store:
4284   case AtomicExpr::AO__atomic_store_n:
4285     Form = Copy;
4286     break;
4287 
4288   case AtomicExpr::AO__c11_atomic_fetch_add:
4289   case AtomicExpr::AO__c11_atomic_fetch_sub:
4290   case AtomicExpr::AO__opencl_atomic_fetch_add:
4291   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4292   case AtomicExpr::AO__atomic_fetch_add:
4293   case AtomicExpr::AO__atomic_fetch_sub:
4294   case AtomicExpr::AO__atomic_add_fetch:
4295   case AtomicExpr::AO__atomic_sub_fetch:
4296     IsAddSub = true;
4297     LLVM_FALLTHROUGH;
4298   case AtomicExpr::AO__c11_atomic_fetch_and:
4299   case AtomicExpr::AO__c11_atomic_fetch_or:
4300   case AtomicExpr::AO__c11_atomic_fetch_xor:
4301   case AtomicExpr::AO__opencl_atomic_fetch_and:
4302   case AtomicExpr::AO__opencl_atomic_fetch_or:
4303   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4304   case AtomicExpr::AO__atomic_fetch_and:
4305   case AtomicExpr::AO__atomic_fetch_or:
4306   case AtomicExpr::AO__atomic_fetch_xor:
4307   case AtomicExpr::AO__atomic_fetch_nand:
4308   case AtomicExpr::AO__atomic_and_fetch:
4309   case AtomicExpr::AO__atomic_or_fetch:
4310   case AtomicExpr::AO__atomic_xor_fetch:
4311   case AtomicExpr::AO__atomic_nand_fetch:
4312   case AtomicExpr::AO__c11_atomic_fetch_min:
4313   case AtomicExpr::AO__c11_atomic_fetch_max:
4314   case AtomicExpr::AO__opencl_atomic_fetch_min:
4315   case AtomicExpr::AO__opencl_atomic_fetch_max:
4316   case AtomicExpr::AO__atomic_min_fetch:
4317   case AtomicExpr::AO__atomic_max_fetch:
4318   case AtomicExpr::AO__atomic_fetch_min:
4319   case AtomicExpr::AO__atomic_fetch_max:
4320     Form = Arithmetic;
4321     break;
4322 
4323   case AtomicExpr::AO__c11_atomic_exchange:
4324   case AtomicExpr::AO__opencl_atomic_exchange:
4325   case AtomicExpr::AO__atomic_exchange_n:
4326     Form = Xchg;
4327     break;
4328 
4329   case AtomicExpr::AO__atomic_exchange:
4330     Form = GNUXchg;
4331     break;
4332 
4333   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4334   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4335   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4336   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4337     Form = C11CmpXchg;
4338     break;
4339 
4340   case AtomicExpr::AO__atomic_compare_exchange:
4341   case AtomicExpr::AO__atomic_compare_exchange_n:
4342     Form = GNUCmpXchg;
4343     break;
4344   }
4345 
4346   unsigned AdjustedNumArgs = NumArgs[Form];
4347   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4348     ++AdjustedNumArgs;
4349   // Check we have the right number of arguments.
4350   if (Args.size() < AdjustedNumArgs) {
4351     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4352         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4353         << ExprRange;
4354     return ExprError();
4355   } else if (Args.size() > AdjustedNumArgs) {
4356     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4357          diag::err_typecheck_call_too_many_args)
4358         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4359         << ExprRange;
4360     return ExprError();
4361   }
4362 
4363   // Inspect the first argument of the atomic operation.
4364   Expr *Ptr = Args[0];
4365   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4366   if (ConvertedPtr.isInvalid())
4367     return ExprError();
4368 
4369   Ptr = ConvertedPtr.get();
4370   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4371   if (!pointerType) {
4372     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4373         << Ptr->getType() << Ptr->getSourceRange();
4374     return ExprError();
4375   }
4376 
4377   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4378   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4379   QualType ValType = AtomTy; // 'C'
4380   if (IsC11) {
4381     if (!AtomTy->isAtomicType()) {
4382       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4383           << Ptr->getType() << Ptr->getSourceRange();
4384       return ExprError();
4385     }
4386     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4387         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4388       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4389           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4390           << Ptr->getSourceRange();
4391       return ExprError();
4392     }
4393     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4394   } else if (Form != Load && Form != LoadCopy) {
4395     if (ValType.isConstQualified()) {
4396       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4397           << Ptr->getType() << Ptr->getSourceRange();
4398       return ExprError();
4399     }
4400   }
4401 
4402   // For an arithmetic operation, the implied arithmetic must be well-formed.
4403   if (Form == Arithmetic) {
4404     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4405     if (IsAddSub && !ValType->isIntegerType()
4406         && !ValType->isPointerType()) {
4407       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4408           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4409       return ExprError();
4410     }
4411     if (!IsAddSub && !ValType->isIntegerType()) {
4412       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4413           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4414       return ExprError();
4415     }
4416     if (IsC11 && ValType->isPointerType() &&
4417         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4418                             diag::err_incomplete_type)) {
4419       return ExprError();
4420     }
4421   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4422     // For __atomic_*_n operations, the value type must be a scalar integral or
4423     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4424     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4425         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4426     return ExprError();
4427   }
4428 
4429   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4430       !AtomTy->isScalarType()) {
4431     // For GNU atomics, require a trivially-copyable type. This is not part of
4432     // the GNU atomics specification, but we enforce it for sanity.
4433     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4434         << Ptr->getType() << Ptr->getSourceRange();
4435     return ExprError();
4436   }
4437 
4438   switch (ValType.getObjCLifetime()) {
4439   case Qualifiers::OCL_None:
4440   case Qualifiers::OCL_ExplicitNone:
4441     // okay
4442     break;
4443 
4444   case Qualifiers::OCL_Weak:
4445   case Qualifiers::OCL_Strong:
4446   case Qualifiers::OCL_Autoreleasing:
4447     // FIXME: Can this happen? By this point, ValType should be known
4448     // to be trivially copyable.
4449     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4450         << ValType << Ptr->getSourceRange();
4451     return ExprError();
4452   }
4453 
4454   // All atomic operations have an overload which takes a pointer to a volatile
4455   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4456   // into the result or the other operands. Similarly atomic_load takes a
4457   // pointer to a const 'A'.
4458   ValType.removeLocalVolatile();
4459   ValType.removeLocalConst();
4460   QualType ResultType = ValType;
4461   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4462       Form == Init)
4463     ResultType = Context.VoidTy;
4464   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4465     ResultType = Context.BoolTy;
4466 
4467   // The type of a parameter passed 'by value'. In the GNU atomics, such
4468   // arguments are actually passed as pointers.
4469   QualType ByValType = ValType; // 'CP'
4470   bool IsPassedByAddress = false;
4471   if (!IsC11 && !IsN) {
4472     ByValType = Ptr->getType();
4473     IsPassedByAddress = true;
4474   }
4475 
4476   SmallVector<Expr *, 5> APIOrderedArgs;
4477   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4478     APIOrderedArgs.push_back(Args[0]);
4479     switch (Form) {
4480     case Init:
4481     case Load:
4482       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4483       break;
4484     case LoadCopy:
4485     case Copy:
4486     case Arithmetic:
4487     case Xchg:
4488       APIOrderedArgs.push_back(Args[2]); // Val1
4489       APIOrderedArgs.push_back(Args[1]); // Order
4490       break;
4491     case GNUXchg:
4492       APIOrderedArgs.push_back(Args[2]); // Val1
4493       APIOrderedArgs.push_back(Args[3]); // Val2
4494       APIOrderedArgs.push_back(Args[1]); // Order
4495       break;
4496     case C11CmpXchg:
4497       APIOrderedArgs.push_back(Args[2]); // Val1
4498       APIOrderedArgs.push_back(Args[4]); // Val2
4499       APIOrderedArgs.push_back(Args[1]); // Order
4500       APIOrderedArgs.push_back(Args[3]); // OrderFail
4501       break;
4502     case GNUCmpXchg:
4503       APIOrderedArgs.push_back(Args[2]); // Val1
4504       APIOrderedArgs.push_back(Args[4]); // Val2
4505       APIOrderedArgs.push_back(Args[5]); // Weak
4506       APIOrderedArgs.push_back(Args[1]); // Order
4507       APIOrderedArgs.push_back(Args[3]); // OrderFail
4508       break;
4509     }
4510   } else
4511     APIOrderedArgs.append(Args.begin(), Args.end());
4512 
4513   // The first argument's non-CV pointer type is used to deduce the type of
4514   // subsequent arguments, except for:
4515   //  - weak flag (always converted to bool)
4516   //  - memory order (always converted to int)
4517   //  - scope  (always converted to int)
4518   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4519     QualType Ty;
4520     if (i < NumVals[Form] + 1) {
4521       switch (i) {
4522       case 0:
4523         // The first argument is always a pointer. It has a fixed type.
4524         // It is always dereferenced, a nullptr is undefined.
4525         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4526         // Nothing else to do: we already know all we want about this pointer.
4527         continue;
4528       case 1:
4529         // The second argument is the non-atomic operand. For arithmetic, this
4530         // is always passed by value, and for a compare_exchange it is always
4531         // passed by address. For the rest, GNU uses by-address and C11 uses
4532         // by-value.
4533         assert(Form != Load);
4534         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4535           Ty = ValType;
4536         else if (Form == Copy || Form == Xchg) {
4537           if (IsPassedByAddress) {
4538             // The value pointer is always dereferenced, a nullptr is undefined.
4539             CheckNonNullArgument(*this, APIOrderedArgs[i],
4540                                  ExprRange.getBegin());
4541           }
4542           Ty = ByValType;
4543         } else if (Form == Arithmetic)
4544           Ty = Context.getPointerDiffType();
4545         else {
4546           Expr *ValArg = APIOrderedArgs[i];
4547           // The value pointer is always dereferenced, a nullptr is undefined.
4548           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4549           LangAS AS = LangAS::Default;
4550           // Keep address space of non-atomic pointer type.
4551           if (const PointerType *PtrTy =
4552                   ValArg->getType()->getAs<PointerType>()) {
4553             AS = PtrTy->getPointeeType().getAddressSpace();
4554           }
4555           Ty = Context.getPointerType(
4556               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4557         }
4558         break;
4559       case 2:
4560         // The third argument to compare_exchange / GNU exchange is the desired
4561         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4562         if (IsPassedByAddress)
4563           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4564         Ty = ByValType;
4565         break;
4566       case 3:
4567         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4568         Ty = Context.BoolTy;
4569         break;
4570       }
4571     } else {
4572       // The order(s) and scope are always converted to int.
4573       Ty = Context.IntTy;
4574     }
4575 
4576     InitializedEntity Entity =
4577         InitializedEntity::InitializeParameter(Context, Ty, false);
4578     ExprResult Arg = APIOrderedArgs[i];
4579     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4580     if (Arg.isInvalid())
4581       return true;
4582     APIOrderedArgs[i] = Arg.get();
4583   }
4584 
4585   // Permute the arguments into a 'consistent' order.
4586   SmallVector<Expr*, 5> SubExprs;
4587   SubExprs.push_back(Ptr);
4588   switch (Form) {
4589   case Init:
4590     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4591     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4592     break;
4593   case Load:
4594     SubExprs.push_back(APIOrderedArgs[1]); // Order
4595     break;
4596   case LoadCopy:
4597   case Copy:
4598   case Arithmetic:
4599   case Xchg:
4600     SubExprs.push_back(APIOrderedArgs[2]); // Order
4601     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4602     break;
4603   case GNUXchg:
4604     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4605     SubExprs.push_back(APIOrderedArgs[3]); // Order
4606     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4607     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4608     break;
4609   case C11CmpXchg:
4610     SubExprs.push_back(APIOrderedArgs[3]); // Order
4611     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4612     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4613     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4614     break;
4615   case GNUCmpXchg:
4616     SubExprs.push_back(APIOrderedArgs[4]); // Order
4617     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4618     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4619     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4620     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4621     break;
4622   }
4623 
4624   if (SubExprs.size() >= 2 && Form != Init) {
4625     llvm::APSInt Result(32);
4626     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4627         !isValidOrderingForOp(Result.getSExtValue(), Op))
4628       Diag(SubExprs[1]->getBeginLoc(),
4629            diag::warn_atomic_op_has_invalid_memory_order)
4630           << SubExprs[1]->getSourceRange();
4631   }
4632 
4633   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4634     auto *Scope = Args[Args.size() - 1];
4635     llvm::APSInt Result(32);
4636     if (Scope->isIntegerConstantExpr(Result, Context) &&
4637         !ScopeModel->isValid(Result.getZExtValue())) {
4638       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4639           << Scope->getSourceRange();
4640     }
4641     SubExprs.push_back(Scope);
4642   }
4643 
4644   AtomicExpr *AE = new (Context)
4645       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4646 
4647   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4648        Op == AtomicExpr::AO__c11_atomic_store ||
4649        Op == AtomicExpr::AO__opencl_atomic_load ||
4650        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4651       Context.AtomicUsesUnsupportedLibcall(AE))
4652     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4653         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4654              Op == AtomicExpr::AO__opencl_atomic_load)
4655                 ? 0
4656                 : 1);
4657 
4658   return AE;
4659 }
4660 
4661 /// checkBuiltinArgument - Given a call to a builtin function, perform
4662 /// normal type-checking on the given argument, updating the call in
4663 /// place.  This is useful when a builtin function requires custom
4664 /// type-checking for some of its arguments but not necessarily all of
4665 /// them.
4666 ///
4667 /// Returns true on error.
4668 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4669   FunctionDecl *Fn = E->getDirectCallee();
4670   assert(Fn && "builtin call without direct callee!");
4671 
4672   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4673   InitializedEntity Entity =
4674     InitializedEntity::InitializeParameter(S.Context, Param);
4675 
4676   ExprResult Arg = E->getArg(0);
4677   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4678   if (Arg.isInvalid())
4679     return true;
4680 
4681   E->setArg(ArgIndex, Arg.get());
4682   return false;
4683 }
4684 
4685 /// We have a call to a function like __sync_fetch_and_add, which is an
4686 /// overloaded function based on the pointer type of its first argument.
4687 /// The main BuildCallExpr routines have already promoted the types of
4688 /// arguments because all of these calls are prototyped as void(...).
4689 ///
4690 /// This function goes through and does final semantic checking for these
4691 /// builtins, as well as generating any warnings.
4692 ExprResult
4693 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4694   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4695   Expr *Callee = TheCall->getCallee();
4696   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4697   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4698 
4699   // Ensure that we have at least one argument to do type inference from.
4700   if (TheCall->getNumArgs() < 1) {
4701     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4702         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4703     return ExprError();
4704   }
4705 
4706   // Inspect the first argument of the atomic builtin.  This should always be
4707   // a pointer type, whose element is an integral scalar or pointer type.
4708   // Because it is a pointer type, we don't have to worry about any implicit
4709   // casts here.
4710   // FIXME: We don't allow floating point scalars as input.
4711   Expr *FirstArg = TheCall->getArg(0);
4712   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4713   if (FirstArgResult.isInvalid())
4714     return ExprError();
4715   FirstArg = FirstArgResult.get();
4716   TheCall->setArg(0, FirstArg);
4717 
4718   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4719   if (!pointerType) {
4720     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4721         << FirstArg->getType() << FirstArg->getSourceRange();
4722     return ExprError();
4723   }
4724 
4725   QualType ValType = pointerType->getPointeeType();
4726   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4727       !ValType->isBlockPointerType()) {
4728     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4729         << FirstArg->getType() << FirstArg->getSourceRange();
4730     return ExprError();
4731   }
4732 
4733   if (ValType.isConstQualified()) {
4734     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4735         << FirstArg->getType() << FirstArg->getSourceRange();
4736     return ExprError();
4737   }
4738 
4739   switch (ValType.getObjCLifetime()) {
4740   case Qualifiers::OCL_None:
4741   case Qualifiers::OCL_ExplicitNone:
4742     // okay
4743     break;
4744 
4745   case Qualifiers::OCL_Weak:
4746   case Qualifiers::OCL_Strong:
4747   case Qualifiers::OCL_Autoreleasing:
4748     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4749         << ValType << FirstArg->getSourceRange();
4750     return ExprError();
4751   }
4752 
4753   // Strip any qualifiers off ValType.
4754   ValType = ValType.getUnqualifiedType();
4755 
4756   // The majority of builtins return a value, but a few have special return
4757   // types, so allow them to override appropriately below.
4758   QualType ResultType = ValType;
4759 
4760   // We need to figure out which concrete builtin this maps onto.  For example,
4761   // __sync_fetch_and_add with a 2 byte object turns into
4762   // __sync_fetch_and_add_2.
4763 #define BUILTIN_ROW(x) \
4764   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4765     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4766 
4767   static const unsigned BuiltinIndices[][5] = {
4768     BUILTIN_ROW(__sync_fetch_and_add),
4769     BUILTIN_ROW(__sync_fetch_and_sub),
4770     BUILTIN_ROW(__sync_fetch_and_or),
4771     BUILTIN_ROW(__sync_fetch_and_and),
4772     BUILTIN_ROW(__sync_fetch_and_xor),
4773     BUILTIN_ROW(__sync_fetch_and_nand),
4774 
4775     BUILTIN_ROW(__sync_add_and_fetch),
4776     BUILTIN_ROW(__sync_sub_and_fetch),
4777     BUILTIN_ROW(__sync_and_and_fetch),
4778     BUILTIN_ROW(__sync_or_and_fetch),
4779     BUILTIN_ROW(__sync_xor_and_fetch),
4780     BUILTIN_ROW(__sync_nand_and_fetch),
4781 
4782     BUILTIN_ROW(__sync_val_compare_and_swap),
4783     BUILTIN_ROW(__sync_bool_compare_and_swap),
4784     BUILTIN_ROW(__sync_lock_test_and_set),
4785     BUILTIN_ROW(__sync_lock_release),
4786     BUILTIN_ROW(__sync_swap)
4787   };
4788 #undef BUILTIN_ROW
4789 
4790   // Determine the index of the size.
4791   unsigned SizeIndex;
4792   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4793   case 1: SizeIndex = 0; break;
4794   case 2: SizeIndex = 1; break;
4795   case 4: SizeIndex = 2; break;
4796   case 8: SizeIndex = 3; break;
4797   case 16: SizeIndex = 4; break;
4798   default:
4799     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4800         << FirstArg->getType() << FirstArg->getSourceRange();
4801     return ExprError();
4802   }
4803 
4804   // Each of these builtins has one pointer argument, followed by some number of
4805   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4806   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4807   // as the number of fixed args.
4808   unsigned BuiltinID = FDecl->getBuiltinID();
4809   unsigned BuiltinIndex, NumFixed = 1;
4810   bool WarnAboutSemanticsChange = false;
4811   switch (BuiltinID) {
4812   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4813   case Builtin::BI__sync_fetch_and_add:
4814   case Builtin::BI__sync_fetch_and_add_1:
4815   case Builtin::BI__sync_fetch_and_add_2:
4816   case Builtin::BI__sync_fetch_and_add_4:
4817   case Builtin::BI__sync_fetch_and_add_8:
4818   case Builtin::BI__sync_fetch_and_add_16:
4819     BuiltinIndex = 0;
4820     break;
4821 
4822   case Builtin::BI__sync_fetch_and_sub:
4823   case Builtin::BI__sync_fetch_and_sub_1:
4824   case Builtin::BI__sync_fetch_and_sub_2:
4825   case Builtin::BI__sync_fetch_and_sub_4:
4826   case Builtin::BI__sync_fetch_and_sub_8:
4827   case Builtin::BI__sync_fetch_and_sub_16:
4828     BuiltinIndex = 1;
4829     break;
4830 
4831   case Builtin::BI__sync_fetch_and_or:
4832   case Builtin::BI__sync_fetch_and_or_1:
4833   case Builtin::BI__sync_fetch_and_or_2:
4834   case Builtin::BI__sync_fetch_and_or_4:
4835   case Builtin::BI__sync_fetch_and_or_8:
4836   case Builtin::BI__sync_fetch_and_or_16:
4837     BuiltinIndex = 2;
4838     break;
4839 
4840   case Builtin::BI__sync_fetch_and_and:
4841   case Builtin::BI__sync_fetch_and_and_1:
4842   case Builtin::BI__sync_fetch_and_and_2:
4843   case Builtin::BI__sync_fetch_and_and_4:
4844   case Builtin::BI__sync_fetch_and_and_8:
4845   case Builtin::BI__sync_fetch_and_and_16:
4846     BuiltinIndex = 3;
4847     break;
4848 
4849   case Builtin::BI__sync_fetch_and_xor:
4850   case Builtin::BI__sync_fetch_and_xor_1:
4851   case Builtin::BI__sync_fetch_and_xor_2:
4852   case Builtin::BI__sync_fetch_and_xor_4:
4853   case Builtin::BI__sync_fetch_and_xor_8:
4854   case Builtin::BI__sync_fetch_and_xor_16:
4855     BuiltinIndex = 4;
4856     break;
4857 
4858   case Builtin::BI__sync_fetch_and_nand:
4859   case Builtin::BI__sync_fetch_and_nand_1:
4860   case Builtin::BI__sync_fetch_and_nand_2:
4861   case Builtin::BI__sync_fetch_and_nand_4:
4862   case Builtin::BI__sync_fetch_and_nand_8:
4863   case Builtin::BI__sync_fetch_and_nand_16:
4864     BuiltinIndex = 5;
4865     WarnAboutSemanticsChange = true;
4866     break;
4867 
4868   case Builtin::BI__sync_add_and_fetch:
4869   case Builtin::BI__sync_add_and_fetch_1:
4870   case Builtin::BI__sync_add_and_fetch_2:
4871   case Builtin::BI__sync_add_and_fetch_4:
4872   case Builtin::BI__sync_add_and_fetch_8:
4873   case Builtin::BI__sync_add_and_fetch_16:
4874     BuiltinIndex = 6;
4875     break;
4876 
4877   case Builtin::BI__sync_sub_and_fetch:
4878   case Builtin::BI__sync_sub_and_fetch_1:
4879   case Builtin::BI__sync_sub_and_fetch_2:
4880   case Builtin::BI__sync_sub_and_fetch_4:
4881   case Builtin::BI__sync_sub_and_fetch_8:
4882   case Builtin::BI__sync_sub_and_fetch_16:
4883     BuiltinIndex = 7;
4884     break;
4885 
4886   case Builtin::BI__sync_and_and_fetch:
4887   case Builtin::BI__sync_and_and_fetch_1:
4888   case Builtin::BI__sync_and_and_fetch_2:
4889   case Builtin::BI__sync_and_and_fetch_4:
4890   case Builtin::BI__sync_and_and_fetch_8:
4891   case Builtin::BI__sync_and_and_fetch_16:
4892     BuiltinIndex = 8;
4893     break;
4894 
4895   case Builtin::BI__sync_or_and_fetch:
4896   case Builtin::BI__sync_or_and_fetch_1:
4897   case Builtin::BI__sync_or_and_fetch_2:
4898   case Builtin::BI__sync_or_and_fetch_4:
4899   case Builtin::BI__sync_or_and_fetch_8:
4900   case Builtin::BI__sync_or_and_fetch_16:
4901     BuiltinIndex = 9;
4902     break;
4903 
4904   case Builtin::BI__sync_xor_and_fetch:
4905   case Builtin::BI__sync_xor_and_fetch_1:
4906   case Builtin::BI__sync_xor_and_fetch_2:
4907   case Builtin::BI__sync_xor_and_fetch_4:
4908   case Builtin::BI__sync_xor_and_fetch_8:
4909   case Builtin::BI__sync_xor_and_fetch_16:
4910     BuiltinIndex = 10;
4911     break;
4912 
4913   case Builtin::BI__sync_nand_and_fetch:
4914   case Builtin::BI__sync_nand_and_fetch_1:
4915   case Builtin::BI__sync_nand_and_fetch_2:
4916   case Builtin::BI__sync_nand_and_fetch_4:
4917   case Builtin::BI__sync_nand_and_fetch_8:
4918   case Builtin::BI__sync_nand_and_fetch_16:
4919     BuiltinIndex = 11;
4920     WarnAboutSemanticsChange = true;
4921     break;
4922 
4923   case Builtin::BI__sync_val_compare_and_swap:
4924   case Builtin::BI__sync_val_compare_and_swap_1:
4925   case Builtin::BI__sync_val_compare_and_swap_2:
4926   case Builtin::BI__sync_val_compare_and_swap_4:
4927   case Builtin::BI__sync_val_compare_and_swap_8:
4928   case Builtin::BI__sync_val_compare_and_swap_16:
4929     BuiltinIndex = 12;
4930     NumFixed = 2;
4931     break;
4932 
4933   case Builtin::BI__sync_bool_compare_and_swap:
4934   case Builtin::BI__sync_bool_compare_and_swap_1:
4935   case Builtin::BI__sync_bool_compare_and_swap_2:
4936   case Builtin::BI__sync_bool_compare_and_swap_4:
4937   case Builtin::BI__sync_bool_compare_and_swap_8:
4938   case Builtin::BI__sync_bool_compare_and_swap_16:
4939     BuiltinIndex = 13;
4940     NumFixed = 2;
4941     ResultType = Context.BoolTy;
4942     break;
4943 
4944   case Builtin::BI__sync_lock_test_and_set:
4945   case Builtin::BI__sync_lock_test_and_set_1:
4946   case Builtin::BI__sync_lock_test_and_set_2:
4947   case Builtin::BI__sync_lock_test_and_set_4:
4948   case Builtin::BI__sync_lock_test_and_set_8:
4949   case Builtin::BI__sync_lock_test_and_set_16:
4950     BuiltinIndex = 14;
4951     break;
4952 
4953   case Builtin::BI__sync_lock_release:
4954   case Builtin::BI__sync_lock_release_1:
4955   case Builtin::BI__sync_lock_release_2:
4956   case Builtin::BI__sync_lock_release_4:
4957   case Builtin::BI__sync_lock_release_8:
4958   case Builtin::BI__sync_lock_release_16:
4959     BuiltinIndex = 15;
4960     NumFixed = 0;
4961     ResultType = Context.VoidTy;
4962     break;
4963 
4964   case Builtin::BI__sync_swap:
4965   case Builtin::BI__sync_swap_1:
4966   case Builtin::BI__sync_swap_2:
4967   case Builtin::BI__sync_swap_4:
4968   case Builtin::BI__sync_swap_8:
4969   case Builtin::BI__sync_swap_16:
4970     BuiltinIndex = 16;
4971     break;
4972   }
4973 
4974   // Now that we know how many fixed arguments we expect, first check that we
4975   // have at least that many.
4976   if (TheCall->getNumArgs() < 1+NumFixed) {
4977     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4978         << 0 << 1 + NumFixed << TheCall->getNumArgs()
4979         << Callee->getSourceRange();
4980     return ExprError();
4981   }
4982 
4983   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4984       << Callee->getSourceRange();
4985 
4986   if (WarnAboutSemanticsChange) {
4987     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4988         << Callee->getSourceRange();
4989   }
4990 
4991   // Get the decl for the concrete builtin from this, we can tell what the
4992   // concrete integer type we should convert to is.
4993   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4994   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4995   FunctionDecl *NewBuiltinDecl;
4996   if (NewBuiltinID == BuiltinID)
4997     NewBuiltinDecl = FDecl;
4998   else {
4999     // Perform builtin lookup to avoid redeclaring it.
5000     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5001     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5002     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5003     assert(Res.getFoundDecl());
5004     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5005     if (!NewBuiltinDecl)
5006       return ExprError();
5007   }
5008 
5009   // The first argument --- the pointer --- has a fixed type; we
5010   // deduce the types of the rest of the arguments accordingly.  Walk
5011   // the remaining arguments, converting them to the deduced value type.
5012   for (unsigned i = 0; i != NumFixed; ++i) {
5013     ExprResult Arg = TheCall->getArg(i+1);
5014 
5015     // GCC does an implicit conversion to the pointer or integer ValType.  This
5016     // can fail in some cases (1i -> int**), check for this error case now.
5017     // Initialize the argument.
5018     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5019                                                    ValType, /*consume*/ false);
5020     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5021     if (Arg.isInvalid())
5022       return ExprError();
5023 
5024     // Okay, we have something that *can* be converted to the right type.  Check
5025     // to see if there is a potentially weird extension going on here.  This can
5026     // happen when you do an atomic operation on something like an char* and
5027     // pass in 42.  The 42 gets converted to char.  This is even more strange
5028     // for things like 45.123 -> char, etc.
5029     // FIXME: Do this check.
5030     TheCall->setArg(i+1, Arg.get());
5031   }
5032 
5033   // Create a new DeclRefExpr to refer to the new decl.
5034   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5035       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5036       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5037       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5038 
5039   // Set the callee in the CallExpr.
5040   // FIXME: This loses syntactic information.
5041   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5042   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5043                                               CK_BuiltinFnToFnPtr);
5044   TheCall->setCallee(PromotedCall.get());
5045 
5046   // Change the result type of the call to match the original value type. This
5047   // is arbitrary, but the codegen for these builtins ins design to handle it
5048   // gracefully.
5049   TheCall->setType(ResultType);
5050 
5051   return TheCallResult;
5052 }
5053 
5054 /// SemaBuiltinNontemporalOverloaded - We have a call to
5055 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5056 /// overloaded function based on the pointer type of its last argument.
5057 ///
5058 /// This function goes through and does final semantic checking for these
5059 /// builtins.
5060 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5061   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5062   DeclRefExpr *DRE =
5063       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5064   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5065   unsigned BuiltinID = FDecl->getBuiltinID();
5066   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5067           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5068          "Unexpected nontemporal load/store builtin!");
5069   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5070   unsigned numArgs = isStore ? 2 : 1;
5071 
5072   // Ensure that we have the proper number of arguments.
5073   if (checkArgCount(*this, TheCall, numArgs))
5074     return ExprError();
5075 
5076   // Inspect the last argument of the nontemporal builtin.  This should always
5077   // be a pointer type, from which we imply the type of the memory access.
5078   // Because it is a pointer type, we don't have to worry about any implicit
5079   // casts here.
5080   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5081   ExprResult PointerArgResult =
5082       DefaultFunctionArrayLvalueConversion(PointerArg);
5083 
5084   if (PointerArgResult.isInvalid())
5085     return ExprError();
5086   PointerArg = PointerArgResult.get();
5087   TheCall->setArg(numArgs - 1, PointerArg);
5088 
5089   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5090   if (!pointerType) {
5091     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5092         << PointerArg->getType() << PointerArg->getSourceRange();
5093     return ExprError();
5094   }
5095 
5096   QualType ValType = pointerType->getPointeeType();
5097 
5098   // Strip any qualifiers off ValType.
5099   ValType = ValType.getUnqualifiedType();
5100   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5101       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5102       !ValType->isVectorType()) {
5103     Diag(DRE->getBeginLoc(),
5104          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5105         << PointerArg->getType() << PointerArg->getSourceRange();
5106     return ExprError();
5107   }
5108 
5109   if (!isStore) {
5110     TheCall->setType(ValType);
5111     return TheCallResult;
5112   }
5113 
5114   ExprResult ValArg = TheCall->getArg(0);
5115   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5116       Context, ValType, /*consume*/ false);
5117   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5118   if (ValArg.isInvalid())
5119     return ExprError();
5120 
5121   TheCall->setArg(0, ValArg.get());
5122   TheCall->setType(Context.VoidTy);
5123   return TheCallResult;
5124 }
5125 
5126 /// CheckObjCString - Checks that the argument to the builtin
5127 /// CFString constructor is correct
5128 /// Note: It might also make sense to do the UTF-16 conversion here (would
5129 /// simplify the backend).
5130 bool Sema::CheckObjCString(Expr *Arg) {
5131   Arg = Arg->IgnoreParenCasts();
5132   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5133 
5134   if (!Literal || !Literal->isAscii()) {
5135     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5136         << Arg->getSourceRange();
5137     return true;
5138   }
5139 
5140   if (Literal->containsNonAsciiOrNull()) {
5141     StringRef String = Literal->getString();
5142     unsigned NumBytes = String.size();
5143     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5144     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5145     llvm::UTF16 *ToPtr = &ToBuf[0];
5146 
5147     llvm::ConversionResult Result =
5148         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5149                                  ToPtr + NumBytes, llvm::strictConversion);
5150     // Check for conversion failure.
5151     if (Result != llvm::conversionOK)
5152       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5153           << Arg->getSourceRange();
5154   }
5155   return false;
5156 }
5157 
5158 /// CheckObjCString - Checks that the format string argument to the os_log()
5159 /// and os_trace() functions is correct, and converts it to const char *.
5160 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5161   Arg = Arg->IgnoreParenCasts();
5162   auto *Literal = dyn_cast<StringLiteral>(Arg);
5163   if (!Literal) {
5164     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5165       Literal = ObjcLiteral->getString();
5166     }
5167   }
5168 
5169   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5170     return ExprError(
5171         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5172         << Arg->getSourceRange());
5173   }
5174 
5175   ExprResult Result(Literal);
5176   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5177   InitializedEntity Entity =
5178       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5179   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5180   return Result;
5181 }
5182 
5183 /// Check that the user is calling the appropriate va_start builtin for the
5184 /// target and calling convention.
5185 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5186   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5187   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5188   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5189                     TT.getArch() == llvm::Triple::aarch64_32);
5190   bool IsWindows = TT.isOSWindows();
5191   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5192   if (IsX64 || IsAArch64) {
5193     CallingConv CC = CC_C;
5194     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5195       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5196     if (IsMSVAStart) {
5197       // Don't allow this in System V ABI functions.
5198       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5199         return S.Diag(Fn->getBeginLoc(),
5200                       diag::err_ms_va_start_used_in_sysv_function);
5201     } else {
5202       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5203       // On x64 Windows, don't allow this in System V ABI functions.
5204       // (Yes, that means there's no corresponding way to support variadic
5205       // System V ABI functions on Windows.)
5206       if ((IsWindows && CC == CC_X86_64SysV) ||
5207           (!IsWindows && CC == CC_Win64))
5208         return S.Diag(Fn->getBeginLoc(),
5209                       diag::err_va_start_used_in_wrong_abi_function)
5210                << !IsWindows;
5211     }
5212     return false;
5213   }
5214 
5215   if (IsMSVAStart)
5216     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5217   return false;
5218 }
5219 
5220 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5221                                              ParmVarDecl **LastParam = nullptr) {
5222   // Determine whether the current function, block, or obj-c method is variadic
5223   // and get its parameter list.
5224   bool IsVariadic = false;
5225   ArrayRef<ParmVarDecl *> Params;
5226   DeclContext *Caller = S.CurContext;
5227   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5228     IsVariadic = Block->isVariadic();
5229     Params = Block->parameters();
5230   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5231     IsVariadic = FD->isVariadic();
5232     Params = FD->parameters();
5233   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5234     IsVariadic = MD->isVariadic();
5235     // FIXME: This isn't correct for methods (results in bogus warning).
5236     Params = MD->parameters();
5237   } else if (isa<CapturedDecl>(Caller)) {
5238     // We don't support va_start in a CapturedDecl.
5239     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5240     return true;
5241   } else {
5242     // This must be some other declcontext that parses exprs.
5243     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5244     return true;
5245   }
5246 
5247   if (!IsVariadic) {
5248     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5249     return true;
5250   }
5251 
5252   if (LastParam)
5253     *LastParam = Params.empty() ? nullptr : Params.back();
5254 
5255   return false;
5256 }
5257 
5258 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5259 /// for validity.  Emit an error and return true on failure; return false
5260 /// on success.
5261 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5262   Expr *Fn = TheCall->getCallee();
5263 
5264   if (checkVAStartABI(*this, BuiltinID, Fn))
5265     return true;
5266 
5267   if (TheCall->getNumArgs() > 2) {
5268     Diag(TheCall->getArg(2)->getBeginLoc(),
5269          diag::err_typecheck_call_too_many_args)
5270         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5271         << Fn->getSourceRange()
5272         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5273                        (*(TheCall->arg_end() - 1))->getEndLoc());
5274     return true;
5275   }
5276 
5277   if (TheCall->getNumArgs() < 2) {
5278     return Diag(TheCall->getEndLoc(),
5279                 diag::err_typecheck_call_too_few_args_at_least)
5280            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5281   }
5282 
5283   // Type-check the first argument normally.
5284   if (checkBuiltinArgument(*this, TheCall, 0))
5285     return true;
5286 
5287   // Check that the current function is variadic, and get its last parameter.
5288   ParmVarDecl *LastParam;
5289   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5290     return true;
5291 
5292   // Verify that the second argument to the builtin is the last argument of the
5293   // current function or method.
5294   bool SecondArgIsLastNamedArgument = false;
5295   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5296 
5297   // These are valid if SecondArgIsLastNamedArgument is false after the next
5298   // block.
5299   QualType Type;
5300   SourceLocation ParamLoc;
5301   bool IsCRegister = false;
5302 
5303   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5304     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5305       SecondArgIsLastNamedArgument = PV == LastParam;
5306 
5307       Type = PV->getType();
5308       ParamLoc = PV->getLocation();
5309       IsCRegister =
5310           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5311     }
5312   }
5313 
5314   if (!SecondArgIsLastNamedArgument)
5315     Diag(TheCall->getArg(1)->getBeginLoc(),
5316          diag::warn_second_arg_of_va_start_not_last_named_param);
5317   else if (IsCRegister || Type->isReferenceType() ||
5318            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5319              // Promotable integers are UB, but enumerations need a bit of
5320              // extra checking to see what their promotable type actually is.
5321              if (!Type->isPromotableIntegerType())
5322                return false;
5323              if (!Type->isEnumeralType())
5324                return true;
5325              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5326              return !(ED &&
5327                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5328            }()) {
5329     unsigned Reason = 0;
5330     if (Type->isReferenceType())  Reason = 1;
5331     else if (IsCRegister)         Reason = 2;
5332     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5333     Diag(ParamLoc, diag::note_parameter_type) << Type;
5334   }
5335 
5336   TheCall->setType(Context.VoidTy);
5337   return false;
5338 }
5339 
5340 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5341   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5342   //                 const char *named_addr);
5343 
5344   Expr *Func = Call->getCallee();
5345 
5346   if (Call->getNumArgs() < 3)
5347     return Diag(Call->getEndLoc(),
5348                 diag::err_typecheck_call_too_few_args_at_least)
5349            << 0 /*function call*/ << 3 << Call->getNumArgs();
5350 
5351   // Type-check the first argument normally.
5352   if (checkBuiltinArgument(*this, Call, 0))
5353     return true;
5354 
5355   // Check that the current function is variadic.
5356   if (checkVAStartIsInVariadicFunction(*this, Func))
5357     return true;
5358 
5359   // __va_start on Windows does not validate the parameter qualifiers
5360 
5361   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5362   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5363 
5364   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5365   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5366 
5367   const QualType &ConstCharPtrTy =
5368       Context.getPointerType(Context.CharTy.withConst());
5369   if (!Arg1Ty->isPointerType() ||
5370       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5371     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5372         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5373         << 0                                      /* qualifier difference */
5374         << 3                                      /* parameter mismatch */
5375         << 2 << Arg1->getType() << ConstCharPtrTy;
5376 
5377   const QualType SizeTy = Context.getSizeType();
5378   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5379     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5380         << Arg2->getType() << SizeTy << 1 /* different class */
5381         << 0                              /* qualifier difference */
5382         << 3                              /* parameter mismatch */
5383         << 3 << Arg2->getType() << SizeTy;
5384 
5385   return false;
5386 }
5387 
5388 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5389 /// friends.  This is declared to take (...), so we have to check everything.
5390 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5391   if (TheCall->getNumArgs() < 2)
5392     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5393            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5394   if (TheCall->getNumArgs() > 2)
5395     return Diag(TheCall->getArg(2)->getBeginLoc(),
5396                 diag::err_typecheck_call_too_many_args)
5397            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5398            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5399                           (*(TheCall->arg_end() - 1))->getEndLoc());
5400 
5401   ExprResult OrigArg0 = TheCall->getArg(0);
5402   ExprResult OrigArg1 = TheCall->getArg(1);
5403 
5404   // Do standard promotions between the two arguments, returning their common
5405   // type.
5406   QualType Res = UsualArithmeticConversions(
5407       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5408   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5409     return true;
5410 
5411   // Make sure any conversions are pushed back into the call; this is
5412   // type safe since unordered compare builtins are declared as "_Bool
5413   // foo(...)".
5414   TheCall->setArg(0, OrigArg0.get());
5415   TheCall->setArg(1, OrigArg1.get());
5416 
5417   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5418     return false;
5419 
5420   // If the common type isn't a real floating type, then the arguments were
5421   // invalid for this operation.
5422   if (Res.isNull() || !Res->isRealFloatingType())
5423     return Diag(OrigArg0.get()->getBeginLoc(),
5424                 diag::err_typecheck_call_invalid_ordered_compare)
5425            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5426            << SourceRange(OrigArg0.get()->getBeginLoc(),
5427                           OrigArg1.get()->getEndLoc());
5428 
5429   return false;
5430 }
5431 
5432 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5433 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5434 /// to check everything. We expect the last argument to be a floating point
5435 /// value.
5436 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5437   if (TheCall->getNumArgs() < NumArgs)
5438     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5439            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5440   if (TheCall->getNumArgs() > NumArgs)
5441     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5442                 diag::err_typecheck_call_too_many_args)
5443            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5444            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5445                           (*(TheCall->arg_end() - 1))->getEndLoc());
5446 
5447   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5448   // on all preceding parameters just being int.  Try all of those.
5449   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5450     Expr *Arg = TheCall->getArg(i);
5451 
5452     if (Arg->isTypeDependent())
5453       return false;
5454 
5455     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5456 
5457     if (Res.isInvalid())
5458       return true;
5459     TheCall->setArg(i, Res.get());
5460   }
5461 
5462   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5463 
5464   if (OrigArg->isTypeDependent())
5465     return false;
5466 
5467   // Usual Unary Conversions will convert half to float, which we want for
5468   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5469   // type how it is, but do normal L->Rvalue conversions.
5470   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5471     OrigArg = UsualUnaryConversions(OrigArg).get();
5472   else
5473     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5474   TheCall->setArg(NumArgs - 1, OrigArg);
5475 
5476   // This operation requires a non-_Complex floating-point number.
5477   if (!OrigArg->getType()->isRealFloatingType())
5478     return Diag(OrigArg->getBeginLoc(),
5479                 diag::err_typecheck_call_invalid_unary_fp)
5480            << OrigArg->getType() << OrigArg->getSourceRange();
5481 
5482   return false;
5483 }
5484 
5485 // Customized Sema Checking for VSX builtins that have the following signature:
5486 // vector [...] builtinName(vector [...], vector [...], const int);
5487 // Which takes the same type of vectors (any legal vector type) for the first
5488 // two arguments and takes compile time constant for the third argument.
5489 // Example builtins are :
5490 // vector double vec_xxpermdi(vector double, vector double, int);
5491 // vector short vec_xxsldwi(vector short, vector short, int);
5492 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5493   unsigned ExpectedNumArgs = 3;
5494   if (TheCall->getNumArgs() < ExpectedNumArgs)
5495     return Diag(TheCall->getEndLoc(),
5496                 diag::err_typecheck_call_too_few_args_at_least)
5497            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5498            << TheCall->getSourceRange();
5499 
5500   if (TheCall->getNumArgs() > ExpectedNumArgs)
5501     return Diag(TheCall->getEndLoc(),
5502                 diag::err_typecheck_call_too_many_args_at_most)
5503            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5504            << TheCall->getSourceRange();
5505 
5506   // Check the third argument is a compile time constant
5507   llvm::APSInt Value;
5508   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5509     return Diag(TheCall->getBeginLoc(),
5510                 diag::err_vsx_builtin_nonconstant_argument)
5511            << 3 /* argument index */ << TheCall->getDirectCallee()
5512            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5513                           TheCall->getArg(2)->getEndLoc());
5514 
5515   QualType Arg1Ty = TheCall->getArg(0)->getType();
5516   QualType Arg2Ty = TheCall->getArg(1)->getType();
5517 
5518   // Check the type of argument 1 and argument 2 are vectors.
5519   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5520   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5521       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5522     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5523            << TheCall->getDirectCallee()
5524            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5525                           TheCall->getArg(1)->getEndLoc());
5526   }
5527 
5528   // Check the first two arguments are the same type.
5529   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5530     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5531            << TheCall->getDirectCallee()
5532            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5533                           TheCall->getArg(1)->getEndLoc());
5534   }
5535 
5536   // When default clang type checking is turned off and the customized type
5537   // checking is used, the returning type of the function must be explicitly
5538   // set. Otherwise it is _Bool by default.
5539   TheCall->setType(Arg1Ty);
5540 
5541   return false;
5542 }
5543 
5544 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5545 // This is declared to take (...), so we have to check everything.
5546 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5547   if (TheCall->getNumArgs() < 2)
5548     return ExprError(Diag(TheCall->getEndLoc(),
5549                           diag::err_typecheck_call_too_few_args_at_least)
5550                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5551                      << TheCall->getSourceRange());
5552 
5553   // Determine which of the following types of shufflevector we're checking:
5554   // 1) unary, vector mask: (lhs, mask)
5555   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5556   QualType resType = TheCall->getArg(0)->getType();
5557   unsigned numElements = 0;
5558 
5559   if (!TheCall->getArg(0)->isTypeDependent() &&
5560       !TheCall->getArg(1)->isTypeDependent()) {
5561     QualType LHSType = TheCall->getArg(0)->getType();
5562     QualType RHSType = TheCall->getArg(1)->getType();
5563 
5564     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5565       return ExprError(
5566           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5567           << TheCall->getDirectCallee()
5568           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5569                          TheCall->getArg(1)->getEndLoc()));
5570 
5571     numElements = LHSType->castAs<VectorType>()->getNumElements();
5572     unsigned numResElements = TheCall->getNumArgs() - 2;
5573 
5574     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5575     // with mask.  If so, verify that RHS is an integer vector type with the
5576     // same number of elts as lhs.
5577     if (TheCall->getNumArgs() == 2) {
5578       if (!RHSType->hasIntegerRepresentation() ||
5579           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5580         return ExprError(Diag(TheCall->getBeginLoc(),
5581                               diag::err_vec_builtin_incompatible_vector)
5582                          << TheCall->getDirectCallee()
5583                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5584                                         TheCall->getArg(1)->getEndLoc()));
5585     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5586       return ExprError(Diag(TheCall->getBeginLoc(),
5587                             diag::err_vec_builtin_incompatible_vector)
5588                        << TheCall->getDirectCallee()
5589                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5590                                       TheCall->getArg(1)->getEndLoc()));
5591     } else if (numElements != numResElements) {
5592       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5593       resType = Context.getVectorType(eltType, numResElements,
5594                                       VectorType::GenericVector);
5595     }
5596   }
5597 
5598   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5599     if (TheCall->getArg(i)->isTypeDependent() ||
5600         TheCall->getArg(i)->isValueDependent())
5601       continue;
5602 
5603     llvm::APSInt Result(32);
5604     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5605       return ExprError(Diag(TheCall->getBeginLoc(),
5606                             diag::err_shufflevector_nonconstant_argument)
5607                        << TheCall->getArg(i)->getSourceRange());
5608 
5609     // Allow -1 which will be translated to undef in the IR.
5610     if (Result.isSigned() && Result.isAllOnesValue())
5611       continue;
5612 
5613     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5614       return ExprError(Diag(TheCall->getBeginLoc(),
5615                             diag::err_shufflevector_argument_too_large)
5616                        << TheCall->getArg(i)->getSourceRange());
5617   }
5618 
5619   SmallVector<Expr*, 32> exprs;
5620 
5621   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5622     exprs.push_back(TheCall->getArg(i));
5623     TheCall->setArg(i, nullptr);
5624   }
5625 
5626   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5627                                          TheCall->getCallee()->getBeginLoc(),
5628                                          TheCall->getRParenLoc());
5629 }
5630 
5631 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5632 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5633                                        SourceLocation BuiltinLoc,
5634                                        SourceLocation RParenLoc) {
5635   ExprValueKind VK = VK_RValue;
5636   ExprObjectKind OK = OK_Ordinary;
5637   QualType DstTy = TInfo->getType();
5638   QualType SrcTy = E->getType();
5639 
5640   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5641     return ExprError(Diag(BuiltinLoc,
5642                           diag::err_convertvector_non_vector)
5643                      << E->getSourceRange());
5644   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5645     return ExprError(Diag(BuiltinLoc,
5646                           diag::err_convertvector_non_vector_type));
5647 
5648   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5649     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5650     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5651     if (SrcElts != DstElts)
5652       return ExprError(Diag(BuiltinLoc,
5653                             diag::err_convertvector_incompatible_vector)
5654                        << E->getSourceRange());
5655   }
5656 
5657   return new (Context)
5658       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5659 }
5660 
5661 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5662 // This is declared to take (const void*, ...) and can take two
5663 // optional constant int args.
5664 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5665   unsigned NumArgs = TheCall->getNumArgs();
5666 
5667   if (NumArgs > 3)
5668     return Diag(TheCall->getEndLoc(),
5669                 diag::err_typecheck_call_too_many_args_at_most)
5670            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5671 
5672   // Argument 0 is checked for us and the remaining arguments must be
5673   // constant integers.
5674   for (unsigned i = 1; i != NumArgs; ++i)
5675     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5676       return true;
5677 
5678   return false;
5679 }
5680 
5681 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5682 // __assume does not evaluate its arguments, and should warn if its argument
5683 // has side effects.
5684 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5685   Expr *Arg = TheCall->getArg(0);
5686   if (Arg->isInstantiationDependent()) return false;
5687 
5688   if (Arg->HasSideEffects(Context))
5689     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5690         << Arg->getSourceRange()
5691         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5692 
5693   return false;
5694 }
5695 
5696 /// Handle __builtin_alloca_with_align. This is declared
5697 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5698 /// than 8.
5699 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5700   // The alignment must be a constant integer.
5701   Expr *Arg = TheCall->getArg(1);
5702 
5703   // We can't check the value of a dependent argument.
5704   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5705     if (const auto *UE =
5706             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5707       if (UE->getKind() == UETT_AlignOf ||
5708           UE->getKind() == UETT_PreferredAlignOf)
5709         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5710             << Arg->getSourceRange();
5711 
5712     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5713 
5714     if (!Result.isPowerOf2())
5715       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5716              << Arg->getSourceRange();
5717 
5718     if (Result < Context.getCharWidth())
5719       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5720              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5721 
5722     if (Result > std::numeric_limits<int32_t>::max())
5723       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5724              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5725   }
5726 
5727   return false;
5728 }
5729 
5730 /// Handle __builtin_assume_aligned. This is declared
5731 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5732 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5733   unsigned NumArgs = TheCall->getNumArgs();
5734 
5735   if (NumArgs > 3)
5736     return Diag(TheCall->getEndLoc(),
5737                 diag::err_typecheck_call_too_many_args_at_most)
5738            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5739 
5740   // The alignment must be a constant integer.
5741   Expr *Arg = TheCall->getArg(1);
5742 
5743   // We can't check the value of a dependent argument.
5744   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5745     llvm::APSInt Result;
5746     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5747       return true;
5748 
5749     if (!Result.isPowerOf2())
5750       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5751              << Arg->getSourceRange();
5752 
5753     if (Result > Sema::MaximumAlignment)
5754       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5755           << Arg->getSourceRange() << Sema::MaximumAlignment;
5756   }
5757 
5758   if (NumArgs > 2) {
5759     ExprResult Arg(TheCall->getArg(2));
5760     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5761       Context.getSizeType(), false);
5762     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5763     if (Arg.isInvalid()) return true;
5764     TheCall->setArg(2, Arg.get());
5765   }
5766 
5767   return false;
5768 }
5769 
5770 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5771   unsigned BuiltinID =
5772       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5773   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5774 
5775   unsigned NumArgs = TheCall->getNumArgs();
5776   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5777   if (NumArgs < NumRequiredArgs) {
5778     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5779            << 0 /* function call */ << NumRequiredArgs << NumArgs
5780            << TheCall->getSourceRange();
5781   }
5782   if (NumArgs >= NumRequiredArgs + 0x100) {
5783     return Diag(TheCall->getEndLoc(),
5784                 diag::err_typecheck_call_too_many_args_at_most)
5785            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5786            << TheCall->getSourceRange();
5787   }
5788   unsigned i = 0;
5789 
5790   // For formatting call, check buffer arg.
5791   if (!IsSizeCall) {
5792     ExprResult Arg(TheCall->getArg(i));
5793     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5794         Context, Context.VoidPtrTy, false);
5795     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5796     if (Arg.isInvalid())
5797       return true;
5798     TheCall->setArg(i, Arg.get());
5799     i++;
5800   }
5801 
5802   // Check string literal arg.
5803   unsigned FormatIdx = i;
5804   {
5805     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5806     if (Arg.isInvalid())
5807       return true;
5808     TheCall->setArg(i, Arg.get());
5809     i++;
5810   }
5811 
5812   // Make sure variadic args are scalar.
5813   unsigned FirstDataArg = i;
5814   while (i < NumArgs) {
5815     ExprResult Arg = DefaultVariadicArgumentPromotion(
5816         TheCall->getArg(i), VariadicFunction, nullptr);
5817     if (Arg.isInvalid())
5818       return true;
5819     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5820     if (ArgSize.getQuantity() >= 0x100) {
5821       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5822              << i << (int)ArgSize.getQuantity() << 0xff
5823              << TheCall->getSourceRange();
5824     }
5825     TheCall->setArg(i, Arg.get());
5826     i++;
5827   }
5828 
5829   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5830   // call to avoid duplicate diagnostics.
5831   if (!IsSizeCall) {
5832     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5833     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5834     bool Success = CheckFormatArguments(
5835         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5836         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5837         CheckedVarArgs);
5838     if (!Success)
5839       return true;
5840   }
5841 
5842   if (IsSizeCall) {
5843     TheCall->setType(Context.getSizeType());
5844   } else {
5845     TheCall->setType(Context.VoidPtrTy);
5846   }
5847   return false;
5848 }
5849 
5850 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5851 /// TheCall is a constant expression.
5852 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5853                                   llvm::APSInt &Result) {
5854   Expr *Arg = TheCall->getArg(ArgNum);
5855   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5856   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5857 
5858   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5859 
5860   if (!Arg->isIntegerConstantExpr(Result, Context))
5861     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5862            << FDecl->getDeclName() << Arg->getSourceRange();
5863 
5864   return false;
5865 }
5866 
5867 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5868 /// TheCall is a constant expression in the range [Low, High].
5869 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5870                                        int Low, int High, bool RangeIsError) {
5871   if (isConstantEvaluated())
5872     return false;
5873   llvm::APSInt Result;
5874 
5875   // We can't check the value of a dependent argument.
5876   Expr *Arg = TheCall->getArg(ArgNum);
5877   if (Arg->isTypeDependent() || Arg->isValueDependent())
5878     return false;
5879 
5880   // Check constant-ness first.
5881   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5882     return true;
5883 
5884   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5885     if (RangeIsError)
5886       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5887              << Result.toString(10) << Low << High << Arg->getSourceRange();
5888     else
5889       // Defer the warning until we know if the code will be emitted so that
5890       // dead code can ignore this.
5891       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5892                           PDiag(diag::warn_argument_invalid_range)
5893                               << Result.toString(10) << Low << High
5894                               << Arg->getSourceRange());
5895   }
5896 
5897   return false;
5898 }
5899 
5900 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5901 /// TheCall is a constant expression is a multiple of Num..
5902 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5903                                           unsigned Num) {
5904   llvm::APSInt Result;
5905 
5906   // We can't check the value of a dependent argument.
5907   Expr *Arg = TheCall->getArg(ArgNum);
5908   if (Arg->isTypeDependent() || Arg->isValueDependent())
5909     return false;
5910 
5911   // Check constant-ness first.
5912   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5913     return true;
5914 
5915   if (Result.getSExtValue() % Num != 0)
5916     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5917            << Num << Arg->getSourceRange();
5918 
5919   return false;
5920 }
5921 
5922 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
5923 /// constant expression representing a power of 2.
5924 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5925   llvm::APSInt Result;
5926 
5927   // We can't check the value of a dependent argument.
5928   Expr *Arg = TheCall->getArg(ArgNum);
5929   if (Arg->isTypeDependent() || Arg->isValueDependent())
5930     return false;
5931 
5932   // Check constant-ness first.
5933   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5934     return true;
5935 
5936   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5937   // and only if x is a power of 2.
5938   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5939     return false;
5940 
5941   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5942          << Arg->getSourceRange();
5943 }
5944 
5945 static bool IsShiftedByte(llvm::APSInt Value) {
5946   if (Value.isNegative())
5947     return false;
5948 
5949   // Check if it's a shifted byte, by shifting it down
5950   while (true) {
5951     // If the value fits in the bottom byte, the check passes.
5952     if (Value < 0x100)
5953       return true;
5954 
5955     // Otherwise, if the value has _any_ bits in the bottom byte, the check
5956     // fails.
5957     if ((Value & 0xFF) != 0)
5958       return false;
5959 
5960     // If the bottom 8 bits are all 0, but something above that is nonzero,
5961     // then shifting the value right by 8 bits won't affect whether it's a
5962     // shifted byte or not. So do that, and go round again.
5963     Value >>= 8;
5964   }
5965 }
5966 
5967 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
5968 /// a constant expression representing an arbitrary byte value shifted left by
5969 /// a multiple of 8 bits.
5970 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
5971                                              unsigned ArgBits) {
5972   llvm::APSInt Result;
5973 
5974   // We can't check the value of a dependent argument.
5975   Expr *Arg = TheCall->getArg(ArgNum);
5976   if (Arg->isTypeDependent() || Arg->isValueDependent())
5977     return false;
5978 
5979   // Check constant-ness first.
5980   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5981     return true;
5982 
5983   // Truncate to the given size.
5984   Result = Result.getLoBits(ArgBits);
5985   Result.setIsUnsigned(true);
5986 
5987   if (IsShiftedByte(Result))
5988     return false;
5989 
5990   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
5991          << Arg->getSourceRange();
5992 }
5993 
5994 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
5995 /// TheCall is a constant expression representing either a shifted byte value,
5996 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
5997 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
5998 /// Arm MVE intrinsics.
5999 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6000                                                    int ArgNum,
6001                                                    unsigned ArgBits) {
6002   llvm::APSInt Result;
6003 
6004   // We can't check the value of a dependent argument.
6005   Expr *Arg = TheCall->getArg(ArgNum);
6006   if (Arg->isTypeDependent() || Arg->isValueDependent())
6007     return false;
6008 
6009   // Check constant-ness first.
6010   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6011     return true;
6012 
6013   // Truncate to the given size.
6014   Result = Result.getLoBits(ArgBits);
6015   Result.setIsUnsigned(true);
6016 
6017   // Check to see if it's in either of the required forms.
6018   if (IsShiftedByte(Result) ||
6019       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6020     return false;
6021 
6022   return Diag(TheCall->getBeginLoc(),
6023               diag::err_argument_not_shifted_byte_or_xxff)
6024          << Arg->getSourceRange();
6025 }
6026 
6027 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6028 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6029   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6030     if (checkArgCount(*this, TheCall, 2))
6031       return true;
6032     Expr *Arg0 = TheCall->getArg(0);
6033     Expr *Arg1 = TheCall->getArg(1);
6034 
6035     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6036     if (FirstArg.isInvalid())
6037       return true;
6038     QualType FirstArgType = FirstArg.get()->getType();
6039     if (!FirstArgType->isAnyPointerType())
6040       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6041                << "first" << FirstArgType << Arg0->getSourceRange();
6042     TheCall->setArg(0, FirstArg.get());
6043 
6044     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6045     if (SecArg.isInvalid())
6046       return true;
6047     QualType SecArgType = SecArg.get()->getType();
6048     if (!SecArgType->isIntegerType())
6049       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6050                << "second" << SecArgType << Arg1->getSourceRange();
6051 
6052     // Derive the return type from the pointer argument.
6053     TheCall->setType(FirstArgType);
6054     return false;
6055   }
6056 
6057   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6058     if (checkArgCount(*this, TheCall, 2))
6059       return true;
6060 
6061     Expr *Arg0 = TheCall->getArg(0);
6062     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6063     if (FirstArg.isInvalid())
6064       return true;
6065     QualType FirstArgType = FirstArg.get()->getType();
6066     if (!FirstArgType->isAnyPointerType())
6067       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6068                << "first" << FirstArgType << Arg0->getSourceRange();
6069     TheCall->setArg(0, FirstArg.get());
6070 
6071     // Derive the return type from the pointer argument.
6072     TheCall->setType(FirstArgType);
6073 
6074     // Second arg must be an constant in range [0,15]
6075     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6076   }
6077 
6078   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6079     if (checkArgCount(*this, TheCall, 2))
6080       return true;
6081     Expr *Arg0 = TheCall->getArg(0);
6082     Expr *Arg1 = TheCall->getArg(1);
6083 
6084     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6085     if (FirstArg.isInvalid())
6086       return true;
6087     QualType FirstArgType = FirstArg.get()->getType();
6088     if (!FirstArgType->isAnyPointerType())
6089       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6090                << "first" << FirstArgType << Arg0->getSourceRange();
6091 
6092     QualType SecArgType = Arg1->getType();
6093     if (!SecArgType->isIntegerType())
6094       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6095                << "second" << SecArgType << Arg1->getSourceRange();
6096     TheCall->setType(Context.IntTy);
6097     return false;
6098   }
6099 
6100   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6101       BuiltinID == AArch64::BI__builtin_arm_stg) {
6102     if (checkArgCount(*this, TheCall, 1))
6103       return true;
6104     Expr *Arg0 = TheCall->getArg(0);
6105     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6106     if (FirstArg.isInvalid())
6107       return true;
6108 
6109     QualType FirstArgType = FirstArg.get()->getType();
6110     if (!FirstArgType->isAnyPointerType())
6111       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6112                << "first" << FirstArgType << Arg0->getSourceRange();
6113     TheCall->setArg(0, FirstArg.get());
6114 
6115     // Derive the return type from the pointer argument.
6116     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6117       TheCall->setType(FirstArgType);
6118     return false;
6119   }
6120 
6121   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6122     Expr *ArgA = TheCall->getArg(0);
6123     Expr *ArgB = TheCall->getArg(1);
6124 
6125     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6126     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6127 
6128     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6129       return true;
6130 
6131     QualType ArgTypeA = ArgExprA.get()->getType();
6132     QualType ArgTypeB = ArgExprB.get()->getType();
6133 
6134     auto isNull = [&] (Expr *E) -> bool {
6135       return E->isNullPointerConstant(
6136                         Context, Expr::NPC_ValueDependentIsNotNull); };
6137 
6138     // argument should be either a pointer or null
6139     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6140       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6141         << "first" << ArgTypeA << ArgA->getSourceRange();
6142 
6143     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6144       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6145         << "second" << ArgTypeB << ArgB->getSourceRange();
6146 
6147     // Ensure Pointee types are compatible
6148     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6149         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6150       QualType pointeeA = ArgTypeA->getPointeeType();
6151       QualType pointeeB = ArgTypeB->getPointeeType();
6152       if (!Context.typesAreCompatible(
6153              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6154              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6155         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6156           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6157           << ArgB->getSourceRange();
6158       }
6159     }
6160 
6161     // at least one argument should be pointer type
6162     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6163       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6164         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6165 
6166     if (isNull(ArgA)) // adopt type of the other pointer
6167       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6168 
6169     if (isNull(ArgB))
6170       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6171 
6172     TheCall->setArg(0, ArgExprA.get());
6173     TheCall->setArg(1, ArgExprB.get());
6174     TheCall->setType(Context.LongLongTy);
6175     return false;
6176   }
6177   assert(false && "Unhandled ARM MTE intrinsic");
6178   return true;
6179 }
6180 
6181 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6182 /// TheCall is an ARM/AArch64 special register string literal.
6183 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6184                                     int ArgNum, unsigned ExpectedFieldNum,
6185                                     bool AllowName) {
6186   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6187                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6188                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6189                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6190                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6191                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6192   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6193                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6194                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6195                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6196                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6197                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6198   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6199 
6200   // We can't check the value of a dependent argument.
6201   Expr *Arg = TheCall->getArg(ArgNum);
6202   if (Arg->isTypeDependent() || Arg->isValueDependent())
6203     return false;
6204 
6205   // Check if the argument is a string literal.
6206   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6207     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6208            << Arg->getSourceRange();
6209 
6210   // Check the type of special register given.
6211   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6212   SmallVector<StringRef, 6> Fields;
6213   Reg.split(Fields, ":");
6214 
6215   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6216     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6217            << Arg->getSourceRange();
6218 
6219   // If the string is the name of a register then we cannot check that it is
6220   // valid here but if the string is of one the forms described in ACLE then we
6221   // can check that the supplied fields are integers and within the valid
6222   // ranges.
6223   if (Fields.size() > 1) {
6224     bool FiveFields = Fields.size() == 5;
6225 
6226     bool ValidString = true;
6227     if (IsARMBuiltin) {
6228       ValidString &= Fields[0].startswith_lower("cp") ||
6229                      Fields[0].startswith_lower("p");
6230       if (ValidString)
6231         Fields[0] =
6232           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6233 
6234       ValidString &= Fields[2].startswith_lower("c");
6235       if (ValidString)
6236         Fields[2] = Fields[2].drop_front(1);
6237 
6238       if (FiveFields) {
6239         ValidString &= Fields[3].startswith_lower("c");
6240         if (ValidString)
6241           Fields[3] = Fields[3].drop_front(1);
6242       }
6243     }
6244 
6245     SmallVector<int, 5> Ranges;
6246     if (FiveFields)
6247       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6248     else
6249       Ranges.append({15, 7, 15});
6250 
6251     for (unsigned i=0; i<Fields.size(); ++i) {
6252       int IntField;
6253       ValidString &= !Fields[i].getAsInteger(10, IntField);
6254       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6255     }
6256 
6257     if (!ValidString)
6258       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6259              << Arg->getSourceRange();
6260   } else if (IsAArch64Builtin && Fields.size() == 1) {
6261     // If the register name is one of those that appear in the condition below
6262     // and the special register builtin being used is one of the write builtins,
6263     // then we require that the argument provided for writing to the register
6264     // is an integer constant expression. This is because it will be lowered to
6265     // an MSR (immediate) instruction, so we need to know the immediate at
6266     // compile time.
6267     if (TheCall->getNumArgs() != 2)
6268       return false;
6269 
6270     std::string RegLower = Reg.lower();
6271     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6272         RegLower != "pan" && RegLower != "uao")
6273       return false;
6274 
6275     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6276   }
6277 
6278   return false;
6279 }
6280 
6281 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6282 /// This checks that the target supports __builtin_longjmp and
6283 /// that val is a constant 1.
6284 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6285   if (!Context.getTargetInfo().hasSjLjLowering())
6286     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6287            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6288 
6289   Expr *Arg = TheCall->getArg(1);
6290   llvm::APSInt Result;
6291 
6292   // TODO: This is less than ideal. Overload this to take a value.
6293   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6294     return true;
6295 
6296   if (Result != 1)
6297     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6298            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6299 
6300   return false;
6301 }
6302 
6303 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6304 /// This checks that the target supports __builtin_setjmp.
6305 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6306   if (!Context.getTargetInfo().hasSjLjLowering())
6307     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6308            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6309   return false;
6310 }
6311 
6312 namespace {
6313 
6314 class UncoveredArgHandler {
6315   enum { Unknown = -1, AllCovered = -2 };
6316 
6317   signed FirstUncoveredArg = Unknown;
6318   SmallVector<const Expr *, 4> DiagnosticExprs;
6319 
6320 public:
6321   UncoveredArgHandler() = default;
6322 
6323   bool hasUncoveredArg() const {
6324     return (FirstUncoveredArg >= 0);
6325   }
6326 
6327   unsigned getUncoveredArg() const {
6328     assert(hasUncoveredArg() && "no uncovered argument");
6329     return FirstUncoveredArg;
6330   }
6331 
6332   void setAllCovered() {
6333     // A string has been found with all arguments covered, so clear out
6334     // the diagnostics.
6335     DiagnosticExprs.clear();
6336     FirstUncoveredArg = AllCovered;
6337   }
6338 
6339   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6340     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6341 
6342     // Don't update if a previous string covers all arguments.
6343     if (FirstUncoveredArg == AllCovered)
6344       return;
6345 
6346     // UncoveredArgHandler tracks the highest uncovered argument index
6347     // and with it all the strings that match this index.
6348     if (NewFirstUncoveredArg == FirstUncoveredArg)
6349       DiagnosticExprs.push_back(StrExpr);
6350     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6351       DiagnosticExprs.clear();
6352       DiagnosticExprs.push_back(StrExpr);
6353       FirstUncoveredArg = NewFirstUncoveredArg;
6354     }
6355   }
6356 
6357   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6358 };
6359 
6360 enum StringLiteralCheckType {
6361   SLCT_NotALiteral,
6362   SLCT_UncheckedLiteral,
6363   SLCT_CheckedLiteral
6364 };
6365 
6366 } // namespace
6367 
6368 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6369                                      BinaryOperatorKind BinOpKind,
6370                                      bool AddendIsRight) {
6371   unsigned BitWidth = Offset.getBitWidth();
6372   unsigned AddendBitWidth = Addend.getBitWidth();
6373   // There might be negative interim results.
6374   if (Addend.isUnsigned()) {
6375     Addend = Addend.zext(++AddendBitWidth);
6376     Addend.setIsSigned(true);
6377   }
6378   // Adjust the bit width of the APSInts.
6379   if (AddendBitWidth > BitWidth) {
6380     Offset = Offset.sext(AddendBitWidth);
6381     BitWidth = AddendBitWidth;
6382   } else if (BitWidth > AddendBitWidth) {
6383     Addend = Addend.sext(BitWidth);
6384   }
6385 
6386   bool Ov = false;
6387   llvm::APSInt ResOffset = Offset;
6388   if (BinOpKind == BO_Add)
6389     ResOffset = Offset.sadd_ov(Addend, Ov);
6390   else {
6391     assert(AddendIsRight && BinOpKind == BO_Sub &&
6392            "operator must be add or sub with addend on the right");
6393     ResOffset = Offset.ssub_ov(Addend, Ov);
6394   }
6395 
6396   // We add an offset to a pointer here so we should support an offset as big as
6397   // possible.
6398   if (Ov) {
6399     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6400            "index (intermediate) result too big");
6401     Offset = Offset.sext(2 * BitWidth);
6402     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6403     return;
6404   }
6405 
6406   Offset = ResOffset;
6407 }
6408 
6409 namespace {
6410 
6411 // This is a wrapper class around StringLiteral to support offsetted string
6412 // literals as format strings. It takes the offset into account when returning
6413 // the string and its length or the source locations to display notes correctly.
6414 class FormatStringLiteral {
6415   const StringLiteral *FExpr;
6416   int64_t Offset;
6417 
6418  public:
6419   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6420       : FExpr(fexpr), Offset(Offset) {}
6421 
6422   StringRef getString() const {
6423     return FExpr->getString().drop_front(Offset);
6424   }
6425 
6426   unsigned getByteLength() const {
6427     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6428   }
6429 
6430   unsigned getLength() const { return FExpr->getLength() - Offset; }
6431   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6432 
6433   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6434 
6435   QualType getType() const { return FExpr->getType(); }
6436 
6437   bool isAscii() const { return FExpr->isAscii(); }
6438   bool isWide() const { return FExpr->isWide(); }
6439   bool isUTF8() const { return FExpr->isUTF8(); }
6440   bool isUTF16() const { return FExpr->isUTF16(); }
6441   bool isUTF32() const { return FExpr->isUTF32(); }
6442   bool isPascal() const { return FExpr->isPascal(); }
6443 
6444   SourceLocation getLocationOfByte(
6445       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6446       const TargetInfo &Target, unsigned *StartToken = nullptr,
6447       unsigned *StartTokenByteOffset = nullptr) const {
6448     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6449                                     StartToken, StartTokenByteOffset);
6450   }
6451 
6452   SourceLocation getBeginLoc() const LLVM_READONLY {
6453     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6454   }
6455 
6456   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6457 };
6458 
6459 }  // namespace
6460 
6461 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6462                               const Expr *OrigFormatExpr,
6463                               ArrayRef<const Expr *> Args,
6464                               bool HasVAListArg, unsigned format_idx,
6465                               unsigned firstDataArg,
6466                               Sema::FormatStringType Type,
6467                               bool inFunctionCall,
6468                               Sema::VariadicCallType CallType,
6469                               llvm::SmallBitVector &CheckedVarArgs,
6470                               UncoveredArgHandler &UncoveredArg,
6471                               bool IgnoreStringsWithoutSpecifiers);
6472 
6473 // Determine if an expression is a string literal or constant string.
6474 // If this function returns false on the arguments to a function expecting a
6475 // format string, we will usually need to emit a warning.
6476 // True string literals are then checked by CheckFormatString.
6477 static StringLiteralCheckType
6478 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6479                       bool HasVAListArg, unsigned format_idx,
6480                       unsigned firstDataArg, Sema::FormatStringType Type,
6481                       Sema::VariadicCallType CallType, bool InFunctionCall,
6482                       llvm::SmallBitVector &CheckedVarArgs,
6483                       UncoveredArgHandler &UncoveredArg,
6484                       llvm::APSInt Offset,
6485                       bool IgnoreStringsWithoutSpecifiers = false) {
6486   if (S.isConstantEvaluated())
6487     return SLCT_NotALiteral;
6488  tryAgain:
6489   assert(Offset.isSigned() && "invalid offset");
6490 
6491   if (E->isTypeDependent() || E->isValueDependent())
6492     return SLCT_NotALiteral;
6493 
6494   E = E->IgnoreParenCasts();
6495 
6496   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6497     // Technically -Wformat-nonliteral does not warn about this case.
6498     // The behavior of printf and friends in this case is implementation
6499     // dependent.  Ideally if the format string cannot be null then
6500     // it should have a 'nonnull' attribute in the function prototype.
6501     return SLCT_UncheckedLiteral;
6502 
6503   switch (E->getStmtClass()) {
6504   case Stmt::BinaryConditionalOperatorClass:
6505   case Stmt::ConditionalOperatorClass: {
6506     // The expression is a literal if both sub-expressions were, and it was
6507     // completely checked only if both sub-expressions were checked.
6508     const AbstractConditionalOperator *C =
6509         cast<AbstractConditionalOperator>(E);
6510 
6511     // Determine whether it is necessary to check both sub-expressions, for
6512     // example, because the condition expression is a constant that can be
6513     // evaluated at compile time.
6514     bool CheckLeft = true, CheckRight = true;
6515 
6516     bool Cond;
6517     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6518                                                  S.isConstantEvaluated())) {
6519       if (Cond)
6520         CheckRight = false;
6521       else
6522         CheckLeft = false;
6523     }
6524 
6525     // We need to maintain the offsets for the right and the left hand side
6526     // separately to check if every possible indexed expression is a valid
6527     // string literal. They might have different offsets for different string
6528     // literals in the end.
6529     StringLiteralCheckType Left;
6530     if (!CheckLeft)
6531       Left = SLCT_UncheckedLiteral;
6532     else {
6533       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6534                                    HasVAListArg, format_idx, firstDataArg,
6535                                    Type, CallType, InFunctionCall,
6536                                    CheckedVarArgs, UncoveredArg, Offset,
6537                                    IgnoreStringsWithoutSpecifiers);
6538       if (Left == SLCT_NotALiteral || !CheckRight) {
6539         return Left;
6540       }
6541     }
6542 
6543     StringLiteralCheckType Right = checkFormatStringExpr(
6544         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6545         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6546         IgnoreStringsWithoutSpecifiers);
6547 
6548     return (CheckLeft && Left < Right) ? Left : Right;
6549   }
6550 
6551   case Stmt::ImplicitCastExprClass:
6552     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6553     goto tryAgain;
6554 
6555   case Stmt::OpaqueValueExprClass:
6556     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6557       E = src;
6558       goto tryAgain;
6559     }
6560     return SLCT_NotALiteral;
6561 
6562   case Stmt::PredefinedExprClass:
6563     // While __func__, etc., are technically not string literals, they
6564     // cannot contain format specifiers and thus are not a security
6565     // liability.
6566     return SLCT_UncheckedLiteral;
6567 
6568   case Stmt::DeclRefExprClass: {
6569     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6570 
6571     // As an exception, do not flag errors for variables binding to
6572     // const string literals.
6573     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6574       bool isConstant = false;
6575       QualType T = DR->getType();
6576 
6577       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6578         isConstant = AT->getElementType().isConstant(S.Context);
6579       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6580         isConstant = T.isConstant(S.Context) &&
6581                      PT->getPointeeType().isConstant(S.Context);
6582       } else if (T->isObjCObjectPointerType()) {
6583         // In ObjC, there is usually no "const ObjectPointer" type,
6584         // so don't check if the pointee type is constant.
6585         isConstant = T.isConstant(S.Context);
6586       }
6587 
6588       if (isConstant) {
6589         if (const Expr *Init = VD->getAnyInitializer()) {
6590           // Look through initializers like const char c[] = { "foo" }
6591           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6592             if (InitList->isStringLiteralInit())
6593               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6594           }
6595           return checkFormatStringExpr(S, Init, Args,
6596                                        HasVAListArg, format_idx,
6597                                        firstDataArg, Type, CallType,
6598                                        /*InFunctionCall*/ false, CheckedVarArgs,
6599                                        UncoveredArg, Offset);
6600         }
6601       }
6602 
6603       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6604       // special check to see if the format string is a function parameter
6605       // of the function calling the printf function.  If the function
6606       // has an attribute indicating it is a printf-like function, then we
6607       // should suppress warnings concerning non-literals being used in a call
6608       // to a vprintf function.  For example:
6609       //
6610       // void
6611       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6612       //      va_list ap;
6613       //      va_start(ap, fmt);
6614       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6615       //      ...
6616       // }
6617       if (HasVAListArg) {
6618         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6619           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6620             int PVIndex = PV->getFunctionScopeIndex() + 1;
6621             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6622               // adjust for implicit parameter
6623               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6624                 if (MD->isInstance())
6625                   ++PVIndex;
6626               // We also check if the formats are compatible.
6627               // We can't pass a 'scanf' string to a 'printf' function.
6628               if (PVIndex == PVFormat->getFormatIdx() &&
6629                   Type == S.GetFormatStringType(PVFormat))
6630                 return SLCT_UncheckedLiteral;
6631             }
6632           }
6633         }
6634       }
6635     }
6636 
6637     return SLCT_NotALiteral;
6638   }
6639 
6640   case Stmt::CallExprClass:
6641   case Stmt::CXXMemberCallExprClass: {
6642     const CallExpr *CE = cast<CallExpr>(E);
6643     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6644       bool IsFirst = true;
6645       StringLiteralCheckType CommonResult;
6646       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6647         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6648         StringLiteralCheckType Result = checkFormatStringExpr(
6649             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6650             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6651             IgnoreStringsWithoutSpecifiers);
6652         if (IsFirst) {
6653           CommonResult = Result;
6654           IsFirst = false;
6655         }
6656       }
6657       if (!IsFirst)
6658         return CommonResult;
6659 
6660       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6661         unsigned BuiltinID = FD->getBuiltinID();
6662         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6663             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6664           const Expr *Arg = CE->getArg(0);
6665           return checkFormatStringExpr(S, Arg, Args,
6666                                        HasVAListArg, format_idx,
6667                                        firstDataArg, Type, CallType,
6668                                        InFunctionCall, CheckedVarArgs,
6669                                        UncoveredArg, Offset,
6670                                        IgnoreStringsWithoutSpecifiers);
6671         }
6672       }
6673     }
6674 
6675     return SLCT_NotALiteral;
6676   }
6677   case Stmt::ObjCMessageExprClass: {
6678     const auto *ME = cast<ObjCMessageExpr>(E);
6679     if (const auto *MD = ME->getMethodDecl()) {
6680       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6681         // As a special case heuristic, if we're using the method -[NSBundle
6682         // localizedStringForKey:value:table:], ignore any key strings that lack
6683         // format specifiers. The idea is that if the key doesn't have any
6684         // format specifiers then its probably just a key to map to the
6685         // localized strings. If it does have format specifiers though, then its
6686         // likely that the text of the key is the format string in the
6687         // programmer's language, and should be checked.
6688         const ObjCInterfaceDecl *IFace;
6689         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6690             IFace->getIdentifier()->isStr("NSBundle") &&
6691             MD->getSelector().isKeywordSelector(
6692                 {"localizedStringForKey", "value", "table"})) {
6693           IgnoreStringsWithoutSpecifiers = true;
6694         }
6695 
6696         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6697         return checkFormatStringExpr(
6698             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6699             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6700             IgnoreStringsWithoutSpecifiers);
6701       }
6702     }
6703 
6704     return SLCT_NotALiteral;
6705   }
6706   case Stmt::ObjCStringLiteralClass:
6707   case Stmt::StringLiteralClass: {
6708     const StringLiteral *StrE = nullptr;
6709 
6710     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6711       StrE = ObjCFExpr->getString();
6712     else
6713       StrE = cast<StringLiteral>(E);
6714 
6715     if (StrE) {
6716       if (Offset.isNegative() || Offset > StrE->getLength()) {
6717         // TODO: It would be better to have an explicit warning for out of
6718         // bounds literals.
6719         return SLCT_NotALiteral;
6720       }
6721       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6722       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6723                         firstDataArg, Type, InFunctionCall, CallType,
6724                         CheckedVarArgs, UncoveredArg,
6725                         IgnoreStringsWithoutSpecifiers);
6726       return SLCT_CheckedLiteral;
6727     }
6728 
6729     return SLCT_NotALiteral;
6730   }
6731   case Stmt::BinaryOperatorClass: {
6732     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6733 
6734     // A string literal + an int offset is still a string literal.
6735     if (BinOp->isAdditiveOp()) {
6736       Expr::EvalResult LResult, RResult;
6737 
6738       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6739           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6740       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6741           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6742 
6743       if (LIsInt != RIsInt) {
6744         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6745 
6746         if (LIsInt) {
6747           if (BinOpKind == BO_Add) {
6748             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6749             E = BinOp->getRHS();
6750             goto tryAgain;
6751           }
6752         } else {
6753           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6754           E = BinOp->getLHS();
6755           goto tryAgain;
6756         }
6757       }
6758     }
6759 
6760     return SLCT_NotALiteral;
6761   }
6762   case Stmt::UnaryOperatorClass: {
6763     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6764     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6765     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6766       Expr::EvalResult IndexResult;
6767       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6768                                        Expr::SE_NoSideEffects,
6769                                        S.isConstantEvaluated())) {
6770         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6771                    /*RHS is int*/ true);
6772         E = ASE->getBase();
6773         goto tryAgain;
6774       }
6775     }
6776 
6777     return SLCT_NotALiteral;
6778   }
6779 
6780   default:
6781     return SLCT_NotALiteral;
6782   }
6783 }
6784 
6785 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6786   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6787       .Case("scanf", FST_Scanf)
6788       .Cases("printf", "printf0", FST_Printf)
6789       .Cases("NSString", "CFString", FST_NSString)
6790       .Case("strftime", FST_Strftime)
6791       .Case("strfmon", FST_Strfmon)
6792       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6793       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6794       .Case("os_trace", FST_OSLog)
6795       .Case("os_log", FST_OSLog)
6796       .Default(FST_Unknown);
6797 }
6798 
6799 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6800 /// functions) for correct use of format strings.
6801 /// Returns true if a format string has been fully checked.
6802 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6803                                 ArrayRef<const Expr *> Args,
6804                                 bool IsCXXMember,
6805                                 VariadicCallType CallType,
6806                                 SourceLocation Loc, SourceRange Range,
6807                                 llvm::SmallBitVector &CheckedVarArgs) {
6808   FormatStringInfo FSI;
6809   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6810     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6811                                 FSI.FirstDataArg, GetFormatStringType(Format),
6812                                 CallType, Loc, Range, CheckedVarArgs);
6813   return false;
6814 }
6815 
6816 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6817                                 bool HasVAListArg, unsigned format_idx,
6818                                 unsigned firstDataArg, FormatStringType Type,
6819                                 VariadicCallType CallType,
6820                                 SourceLocation Loc, SourceRange Range,
6821                                 llvm::SmallBitVector &CheckedVarArgs) {
6822   // CHECK: printf/scanf-like function is called with no format string.
6823   if (format_idx >= Args.size()) {
6824     Diag(Loc, diag::warn_missing_format_string) << Range;
6825     return false;
6826   }
6827 
6828   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6829 
6830   // CHECK: format string is not a string literal.
6831   //
6832   // Dynamically generated format strings are difficult to
6833   // automatically vet at compile time.  Requiring that format strings
6834   // are string literals: (1) permits the checking of format strings by
6835   // the compiler and thereby (2) can practically remove the source of
6836   // many format string exploits.
6837 
6838   // Format string can be either ObjC string (e.g. @"%d") or
6839   // C string (e.g. "%d")
6840   // ObjC string uses the same format specifiers as C string, so we can use
6841   // the same format string checking logic for both ObjC and C strings.
6842   UncoveredArgHandler UncoveredArg;
6843   StringLiteralCheckType CT =
6844       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6845                             format_idx, firstDataArg, Type, CallType,
6846                             /*IsFunctionCall*/ true, CheckedVarArgs,
6847                             UncoveredArg,
6848                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6849 
6850   // Generate a diagnostic where an uncovered argument is detected.
6851   if (UncoveredArg.hasUncoveredArg()) {
6852     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6853     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6854     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6855   }
6856 
6857   if (CT != SLCT_NotALiteral)
6858     // Literal format string found, check done!
6859     return CT == SLCT_CheckedLiteral;
6860 
6861   // Strftime is particular as it always uses a single 'time' argument,
6862   // so it is safe to pass a non-literal string.
6863   if (Type == FST_Strftime)
6864     return false;
6865 
6866   // Do not emit diag when the string param is a macro expansion and the
6867   // format is either NSString or CFString. This is a hack to prevent
6868   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6869   // which are usually used in place of NS and CF string literals.
6870   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6871   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6872     return false;
6873 
6874   // If there are no arguments specified, warn with -Wformat-security, otherwise
6875   // warn only with -Wformat-nonliteral.
6876   if (Args.size() == firstDataArg) {
6877     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6878       << OrigFormatExpr->getSourceRange();
6879     switch (Type) {
6880     default:
6881       break;
6882     case FST_Kprintf:
6883     case FST_FreeBSDKPrintf:
6884     case FST_Printf:
6885       Diag(FormatLoc, diag::note_format_security_fixit)
6886         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6887       break;
6888     case FST_NSString:
6889       Diag(FormatLoc, diag::note_format_security_fixit)
6890         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6891       break;
6892     }
6893   } else {
6894     Diag(FormatLoc, diag::warn_format_nonliteral)
6895       << OrigFormatExpr->getSourceRange();
6896   }
6897   return false;
6898 }
6899 
6900 namespace {
6901 
6902 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6903 protected:
6904   Sema &S;
6905   const FormatStringLiteral *FExpr;
6906   const Expr *OrigFormatExpr;
6907   const Sema::FormatStringType FSType;
6908   const unsigned FirstDataArg;
6909   const unsigned NumDataArgs;
6910   const char *Beg; // Start of format string.
6911   const bool HasVAListArg;
6912   ArrayRef<const Expr *> Args;
6913   unsigned FormatIdx;
6914   llvm::SmallBitVector CoveredArgs;
6915   bool usesPositionalArgs = false;
6916   bool atFirstArg = true;
6917   bool inFunctionCall;
6918   Sema::VariadicCallType CallType;
6919   llvm::SmallBitVector &CheckedVarArgs;
6920   UncoveredArgHandler &UncoveredArg;
6921 
6922 public:
6923   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6924                      const Expr *origFormatExpr,
6925                      const Sema::FormatStringType type, unsigned firstDataArg,
6926                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6927                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6928                      bool inFunctionCall, Sema::VariadicCallType callType,
6929                      llvm::SmallBitVector &CheckedVarArgs,
6930                      UncoveredArgHandler &UncoveredArg)
6931       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6932         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6933         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6934         inFunctionCall(inFunctionCall), CallType(callType),
6935         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6936     CoveredArgs.resize(numDataArgs);
6937     CoveredArgs.reset();
6938   }
6939 
6940   void DoneProcessing();
6941 
6942   void HandleIncompleteSpecifier(const char *startSpecifier,
6943                                  unsigned specifierLen) override;
6944 
6945   void HandleInvalidLengthModifier(
6946                            const analyze_format_string::FormatSpecifier &FS,
6947                            const analyze_format_string::ConversionSpecifier &CS,
6948                            const char *startSpecifier, unsigned specifierLen,
6949                            unsigned DiagID);
6950 
6951   void HandleNonStandardLengthModifier(
6952                     const analyze_format_string::FormatSpecifier &FS,
6953                     const char *startSpecifier, unsigned specifierLen);
6954 
6955   void HandleNonStandardConversionSpecifier(
6956                     const analyze_format_string::ConversionSpecifier &CS,
6957                     const char *startSpecifier, unsigned specifierLen);
6958 
6959   void HandlePosition(const char *startPos, unsigned posLen) override;
6960 
6961   void HandleInvalidPosition(const char *startSpecifier,
6962                              unsigned specifierLen,
6963                              analyze_format_string::PositionContext p) override;
6964 
6965   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6966 
6967   void HandleNullChar(const char *nullCharacter) override;
6968 
6969   template <typename Range>
6970   static void
6971   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6972                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6973                        bool IsStringLocation, Range StringRange,
6974                        ArrayRef<FixItHint> Fixit = None);
6975 
6976 protected:
6977   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6978                                         const char *startSpec,
6979                                         unsigned specifierLen,
6980                                         const char *csStart, unsigned csLen);
6981 
6982   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6983                                          const char *startSpec,
6984                                          unsigned specifierLen);
6985 
6986   SourceRange getFormatStringRange();
6987   CharSourceRange getSpecifierRange(const char *startSpecifier,
6988                                     unsigned specifierLen);
6989   SourceLocation getLocationOfByte(const char *x);
6990 
6991   const Expr *getDataArg(unsigned i) const;
6992 
6993   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6994                     const analyze_format_string::ConversionSpecifier &CS,
6995                     const char *startSpecifier, unsigned specifierLen,
6996                     unsigned argIndex);
6997 
6998   template <typename Range>
6999   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7000                             bool IsStringLocation, Range StringRange,
7001                             ArrayRef<FixItHint> Fixit = None);
7002 };
7003 
7004 } // namespace
7005 
7006 SourceRange CheckFormatHandler::getFormatStringRange() {
7007   return OrigFormatExpr->getSourceRange();
7008 }
7009 
7010 CharSourceRange CheckFormatHandler::
7011 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7012   SourceLocation Start = getLocationOfByte(startSpecifier);
7013   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7014 
7015   // Advance the end SourceLocation by one due to half-open ranges.
7016   End = End.getLocWithOffset(1);
7017 
7018   return CharSourceRange::getCharRange(Start, End);
7019 }
7020 
7021 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7022   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7023                                   S.getLangOpts(), S.Context.getTargetInfo());
7024 }
7025 
7026 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7027                                                    unsigned specifierLen){
7028   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7029                        getLocationOfByte(startSpecifier),
7030                        /*IsStringLocation*/true,
7031                        getSpecifierRange(startSpecifier, specifierLen));
7032 }
7033 
7034 void CheckFormatHandler::HandleInvalidLengthModifier(
7035     const analyze_format_string::FormatSpecifier &FS,
7036     const analyze_format_string::ConversionSpecifier &CS,
7037     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7038   using namespace analyze_format_string;
7039 
7040   const LengthModifier &LM = FS.getLengthModifier();
7041   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7042 
7043   // See if we know how to fix this length modifier.
7044   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7045   if (FixedLM) {
7046     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7047                          getLocationOfByte(LM.getStart()),
7048                          /*IsStringLocation*/true,
7049                          getSpecifierRange(startSpecifier, specifierLen));
7050 
7051     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7052       << FixedLM->toString()
7053       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7054 
7055   } else {
7056     FixItHint Hint;
7057     if (DiagID == diag::warn_format_nonsensical_length)
7058       Hint = FixItHint::CreateRemoval(LMRange);
7059 
7060     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7061                          getLocationOfByte(LM.getStart()),
7062                          /*IsStringLocation*/true,
7063                          getSpecifierRange(startSpecifier, specifierLen),
7064                          Hint);
7065   }
7066 }
7067 
7068 void CheckFormatHandler::HandleNonStandardLengthModifier(
7069     const analyze_format_string::FormatSpecifier &FS,
7070     const char *startSpecifier, unsigned specifierLen) {
7071   using namespace analyze_format_string;
7072 
7073   const LengthModifier &LM = FS.getLengthModifier();
7074   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7075 
7076   // See if we know how to fix this length modifier.
7077   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7078   if (FixedLM) {
7079     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7080                            << LM.toString() << 0,
7081                          getLocationOfByte(LM.getStart()),
7082                          /*IsStringLocation*/true,
7083                          getSpecifierRange(startSpecifier, specifierLen));
7084 
7085     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7086       << FixedLM->toString()
7087       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7088 
7089   } else {
7090     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7091                            << LM.toString() << 0,
7092                          getLocationOfByte(LM.getStart()),
7093                          /*IsStringLocation*/true,
7094                          getSpecifierRange(startSpecifier, specifierLen));
7095   }
7096 }
7097 
7098 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7099     const analyze_format_string::ConversionSpecifier &CS,
7100     const char *startSpecifier, unsigned specifierLen) {
7101   using namespace analyze_format_string;
7102 
7103   // See if we know how to fix this conversion specifier.
7104   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7105   if (FixedCS) {
7106     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7107                           << CS.toString() << /*conversion specifier*/1,
7108                          getLocationOfByte(CS.getStart()),
7109                          /*IsStringLocation*/true,
7110                          getSpecifierRange(startSpecifier, specifierLen));
7111 
7112     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7113     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7114       << FixedCS->toString()
7115       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7116   } else {
7117     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7118                           << CS.toString() << /*conversion specifier*/1,
7119                          getLocationOfByte(CS.getStart()),
7120                          /*IsStringLocation*/true,
7121                          getSpecifierRange(startSpecifier, specifierLen));
7122   }
7123 }
7124 
7125 void CheckFormatHandler::HandlePosition(const char *startPos,
7126                                         unsigned posLen) {
7127   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7128                                getLocationOfByte(startPos),
7129                                /*IsStringLocation*/true,
7130                                getSpecifierRange(startPos, posLen));
7131 }
7132 
7133 void
7134 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7135                                      analyze_format_string::PositionContext p) {
7136   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7137                          << (unsigned) p,
7138                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7139                        getSpecifierRange(startPos, posLen));
7140 }
7141 
7142 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7143                                             unsigned posLen) {
7144   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7145                                getLocationOfByte(startPos),
7146                                /*IsStringLocation*/true,
7147                                getSpecifierRange(startPos, posLen));
7148 }
7149 
7150 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7151   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7152     // The presence of a null character is likely an error.
7153     EmitFormatDiagnostic(
7154       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7155       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7156       getFormatStringRange());
7157   }
7158 }
7159 
7160 // Note that this may return NULL if there was an error parsing or building
7161 // one of the argument expressions.
7162 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7163   return Args[FirstDataArg + i];
7164 }
7165 
7166 void CheckFormatHandler::DoneProcessing() {
7167   // Does the number of data arguments exceed the number of
7168   // format conversions in the format string?
7169   if (!HasVAListArg) {
7170       // Find any arguments that weren't covered.
7171     CoveredArgs.flip();
7172     signed notCoveredArg = CoveredArgs.find_first();
7173     if (notCoveredArg >= 0) {
7174       assert((unsigned)notCoveredArg < NumDataArgs);
7175       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7176     } else {
7177       UncoveredArg.setAllCovered();
7178     }
7179   }
7180 }
7181 
7182 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7183                                    const Expr *ArgExpr) {
7184   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7185          "Invalid state");
7186 
7187   if (!ArgExpr)
7188     return;
7189 
7190   SourceLocation Loc = ArgExpr->getBeginLoc();
7191 
7192   if (S.getSourceManager().isInSystemMacro(Loc))
7193     return;
7194 
7195   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7196   for (auto E : DiagnosticExprs)
7197     PDiag << E->getSourceRange();
7198 
7199   CheckFormatHandler::EmitFormatDiagnostic(
7200                                   S, IsFunctionCall, DiagnosticExprs[0],
7201                                   PDiag, Loc, /*IsStringLocation*/false,
7202                                   DiagnosticExprs[0]->getSourceRange());
7203 }
7204 
7205 bool
7206 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7207                                                      SourceLocation Loc,
7208                                                      const char *startSpec,
7209                                                      unsigned specifierLen,
7210                                                      const char *csStart,
7211                                                      unsigned csLen) {
7212   bool keepGoing = true;
7213   if (argIndex < NumDataArgs) {
7214     // Consider the argument coverered, even though the specifier doesn't
7215     // make sense.
7216     CoveredArgs.set(argIndex);
7217   }
7218   else {
7219     // If argIndex exceeds the number of data arguments we
7220     // don't issue a warning because that is just a cascade of warnings (and
7221     // they may have intended '%%' anyway). We don't want to continue processing
7222     // the format string after this point, however, as we will like just get
7223     // gibberish when trying to match arguments.
7224     keepGoing = false;
7225   }
7226 
7227   StringRef Specifier(csStart, csLen);
7228 
7229   // If the specifier in non-printable, it could be the first byte of a UTF-8
7230   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7231   // hex value.
7232   std::string CodePointStr;
7233   if (!llvm::sys::locale::isPrint(*csStart)) {
7234     llvm::UTF32 CodePoint;
7235     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7236     const llvm::UTF8 *E =
7237         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7238     llvm::ConversionResult Result =
7239         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7240 
7241     if (Result != llvm::conversionOK) {
7242       unsigned char FirstChar = *csStart;
7243       CodePoint = (llvm::UTF32)FirstChar;
7244     }
7245 
7246     llvm::raw_string_ostream OS(CodePointStr);
7247     if (CodePoint < 256)
7248       OS << "\\x" << llvm::format("%02x", CodePoint);
7249     else if (CodePoint <= 0xFFFF)
7250       OS << "\\u" << llvm::format("%04x", CodePoint);
7251     else
7252       OS << "\\U" << llvm::format("%08x", CodePoint);
7253     OS.flush();
7254     Specifier = CodePointStr;
7255   }
7256 
7257   EmitFormatDiagnostic(
7258       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7259       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7260 
7261   return keepGoing;
7262 }
7263 
7264 void
7265 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7266                                                       const char *startSpec,
7267                                                       unsigned specifierLen) {
7268   EmitFormatDiagnostic(
7269     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7270     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7271 }
7272 
7273 bool
7274 CheckFormatHandler::CheckNumArgs(
7275   const analyze_format_string::FormatSpecifier &FS,
7276   const analyze_format_string::ConversionSpecifier &CS,
7277   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7278 
7279   if (argIndex >= NumDataArgs) {
7280     PartialDiagnostic PDiag = FS.usesPositionalArg()
7281       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7282            << (argIndex+1) << NumDataArgs)
7283       : S.PDiag(diag::warn_printf_insufficient_data_args);
7284     EmitFormatDiagnostic(
7285       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7286       getSpecifierRange(startSpecifier, specifierLen));
7287 
7288     // Since more arguments than conversion tokens are given, by extension
7289     // all arguments are covered, so mark this as so.
7290     UncoveredArg.setAllCovered();
7291     return false;
7292   }
7293   return true;
7294 }
7295 
7296 template<typename Range>
7297 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7298                                               SourceLocation Loc,
7299                                               bool IsStringLocation,
7300                                               Range StringRange,
7301                                               ArrayRef<FixItHint> FixIt) {
7302   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7303                        Loc, IsStringLocation, StringRange, FixIt);
7304 }
7305 
7306 /// If the format string is not within the function call, emit a note
7307 /// so that the function call and string are in diagnostic messages.
7308 ///
7309 /// \param InFunctionCall if true, the format string is within the function
7310 /// call and only one diagnostic message will be produced.  Otherwise, an
7311 /// extra note will be emitted pointing to location of the format string.
7312 ///
7313 /// \param ArgumentExpr the expression that is passed as the format string
7314 /// argument in the function call.  Used for getting locations when two
7315 /// diagnostics are emitted.
7316 ///
7317 /// \param PDiag the callee should already have provided any strings for the
7318 /// diagnostic message.  This function only adds locations and fixits
7319 /// to diagnostics.
7320 ///
7321 /// \param Loc primary location for diagnostic.  If two diagnostics are
7322 /// required, one will be at Loc and a new SourceLocation will be created for
7323 /// the other one.
7324 ///
7325 /// \param IsStringLocation if true, Loc points to the format string should be
7326 /// used for the note.  Otherwise, Loc points to the argument list and will
7327 /// be used with PDiag.
7328 ///
7329 /// \param StringRange some or all of the string to highlight.  This is
7330 /// templated so it can accept either a CharSourceRange or a SourceRange.
7331 ///
7332 /// \param FixIt optional fix it hint for the format string.
7333 template <typename Range>
7334 void CheckFormatHandler::EmitFormatDiagnostic(
7335     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7336     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7337     Range StringRange, ArrayRef<FixItHint> FixIt) {
7338   if (InFunctionCall) {
7339     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7340     D << StringRange;
7341     D << FixIt;
7342   } else {
7343     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7344       << ArgumentExpr->getSourceRange();
7345 
7346     const Sema::SemaDiagnosticBuilder &Note =
7347       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7348              diag::note_format_string_defined);
7349 
7350     Note << StringRange;
7351     Note << FixIt;
7352   }
7353 }
7354 
7355 //===--- CHECK: Printf format string checking ------------------------------===//
7356 
7357 namespace {
7358 
7359 class CheckPrintfHandler : public CheckFormatHandler {
7360 public:
7361   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7362                      const Expr *origFormatExpr,
7363                      const Sema::FormatStringType type, unsigned firstDataArg,
7364                      unsigned numDataArgs, bool isObjC, const char *beg,
7365                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7366                      unsigned formatIdx, bool inFunctionCall,
7367                      Sema::VariadicCallType CallType,
7368                      llvm::SmallBitVector &CheckedVarArgs,
7369                      UncoveredArgHandler &UncoveredArg)
7370       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7371                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7372                            inFunctionCall, CallType, CheckedVarArgs,
7373                            UncoveredArg) {}
7374 
7375   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7376 
7377   /// Returns true if '%@' specifiers are allowed in the format string.
7378   bool allowsObjCArg() const {
7379     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7380            FSType == Sema::FST_OSTrace;
7381   }
7382 
7383   bool HandleInvalidPrintfConversionSpecifier(
7384                                       const analyze_printf::PrintfSpecifier &FS,
7385                                       const char *startSpecifier,
7386                                       unsigned specifierLen) override;
7387 
7388   void handleInvalidMaskType(StringRef MaskType) override;
7389 
7390   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7391                              const char *startSpecifier,
7392                              unsigned specifierLen) override;
7393   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7394                        const char *StartSpecifier,
7395                        unsigned SpecifierLen,
7396                        const Expr *E);
7397 
7398   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7399                     const char *startSpecifier, unsigned specifierLen);
7400   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7401                            const analyze_printf::OptionalAmount &Amt,
7402                            unsigned type,
7403                            const char *startSpecifier, unsigned specifierLen);
7404   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7405                   const analyze_printf::OptionalFlag &flag,
7406                   const char *startSpecifier, unsigned specifierLen);
7407   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7408                          const analyze_printf::OptionalFlag &ignoredFlag,
7409                          const analyze_printf::OptionalFlag &flag,
7410                          const char *startSpecifier, unsigned specifierLen);
7411   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7412                            const Expr *E);
7413 
7414   void HandleEmptyObjCModifierFlag(const char *startFlag,
7415                                    unsigned flagLen) override;
7416 
7417   void HandleInvalidObjCModifierFlag(const char *startFlag,
7418                                             unsigned flagLen) override;
7419 
7420   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7421                                            const char *flagsEnd,
7422                                            const char *conversionPosition)
7423                                              override;
7424 };
7425 
7426 } // namespace
7427 
7428 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7429                                       const analyze_printf::PrintfSpecifier &FS,
7430                                       const char *startSpecifier,
7431                                       unsigned specifierLen) {
7432   const analyze_printf::PrintfConversionSpecifier &CS =
7433     FS.getConversionSpecifier();
7434 
7435   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7436                                           getLocationOfByte(CS.getStart()),
7437                                           startSpecifier, specifierLen,
7438                                           CS.getStart(), CS.getLength());
7439 }
7440 
7441 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7442   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7443 }
7444 
7445 bool CheckPrintfHandler::HandleAmount(
7446                                const analyze_format_string::OptionalAmount &Amt,
7447                                unsigned k, const char *startSpecifier,
7448                                unsigned specifierLen) {
7449   if (Amt.hasDataArgument()) {
7450     if (!HasVAListArg) {
7451       unsigned argIndex = Amt.getArgIndex();
7452       if (argIndex >= NumDataArgs) {
7453         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7454                                << k,
7455                              getLocationOfByte(Amt.getStart()),
7456                              /*IsStringLocation*/true,
7457                              getSpecifierRange(startSpecifier, specifierLen));
7458         // Don't do any more checking.  We will just emit
7459         // spurious errors.
7460         return false;
7461       }
7462 
7463       // Type check the data argument.  It should be an 'int'.
7464       // Although not in conformance with C99, we also allow the argument to be
7465       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7466       // doesn't emit a warning for that case.
7467       CoveredArgs.set(argIndex);
7468       const Expr *Arg = getDataArg(argIndex);
7469       if (!Arg)
7470         return false;
7471 
7472       QualType T = Arg->getType();
7473 
7474       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7475       assert(AT.isValid());
7476 
7477       if (!AT.matchesType(S.Context, T)) {
7478         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7479                                << k << AT.getRepresentativeTypeName(S.Context)
7480                                << T << Arg->getSourceRange(),
7481                              getLocationOfByte(Amt.getStart()),
7482                              /*IsStringLocation*/true,
7483                              getSpecifierRange(startSpecifier, specifierLen));
7484         // Don't do any more checking.  We will just emit
7485         // spurious errors.
7486         return false;
7487       }
7488     }
7489   }
7490   return true;
7491 }
7492 
7493 void CheckPrintfHandler::HandleInvalidAmount(
7494                                       const analyze_printf::PrintfSpecifier &FS,
7495                                       const analyze_printf::OptionalAmount &Amt,
7496                                       unsigned type,
7497                                       const char *startSpecifier,
7498                                       unsigned specifierLen) {
7499   const analyze_printf::PrintfConversionSpecifier &CS =
7500     FS.getConversionSpecifier();
7501 
7502   FixItHint fixit =
7503     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7504       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7505                                  Amt.getConstantLength()))
7506       : FixItHint();
7507 
7508   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7509                          << type << CS.toString(),
7510                        getLocationOfByte(Amt.getStart()),
7511                        /*IsStringLocation*/true,
7512                        getSpecifierRange(startSpecifier, specifierLen),
7513                        fixit);
7514 }
7515 
7516 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7517                                     const analyze_printf::OptionalFlag &flag,
7518                                     const char *startSpecifier,
7519                                     unsigned specifierLen) {
7520   // Warn about pointless flag with a fixit removal.
7521   const analyze_printf::PrintfConversionSpecifier &CS =
7522     FS.getConversionSpecifier();
7523   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7524                          << flag.toString() << CS.toString(),
7525                        getLocationOfByte(flag.getPosition()),
7526                        /*IsStringLocation*/true,
7527                        getSpecifierRange(startSpecifier, specifierLen),
7528                        FixItHint::CreateRemoval(
7529                          getSpecifierRange(flag.getPosition(), 1)));
7530 }
7531 
7532 void CheckPrintfHandler::HandleIgnoredFlag(
7533                                 const analyze_printf::PrintfSpecifier &FS,
7534                                 const analyze_printf::OptionalFlag &ignoredFlag,
7535                                 const analyze_printf::OptionalFlag &flag,
7536                                 const char *startSpecifier,
7537                                 unsigned specifierLen) {
7538   // Warn about ignored flag with a fixit removal.
7539   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7540                          << ignoredFlag.toString() << flag.toString(),
7541                        getLocationOfByte(ignoredFlag.getPosition()),
7542                        /*IsStringLocation*/true,
7543                        getSpecifierRange(startSpecifier, specifierLen),
7544                        FixItHint::CreateRemoval(
7545                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7546 }
7547 
7548 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7549                                                      unsigned flagLen) {
7550   // Warn about an empty flag.
7551   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7552                        getLocationOfByte(startFlag),
7553                        /*IsStringLocation*/true,
7554                        getSpecifierRange(startFlag, flagLen));
7555 }
7556 
7557 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7558                                                        unsigned flagLen) {
7559   // Warn about an invalid flag.
7560   auto Range = getSpecifierRange(startFlag, flagLen);
7561   StringRef flag(startFlag, flagLen);
7562   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7563                       getLocationOfByte(startFlag),
7564                       /*IsStringLocation*/true,
7565                       Range, FixItHint::CreateRemoval(Range));
7566 }
7567 
7568 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7569     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7570     // Warn about using '[...]' without a '@' conversion.
7571     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7572     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7573     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7574                          getLocationOfByte(conversionPosition),
7575                          /*IsStringLocation*/true,
7576                          Range, FixItHint::CreateRemoval(Range));
7577 }
7578 
7579 // Determines if the specified is a C++ class or struct containing
7580 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7581 // "c_str()").
7582 template<typename MemberKind>
7583 static llvm::SmallPtrSet<MemberKind*, 1>
7584 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7585   const RecordType *RT = Ty->getAs<RecordType>();
7586   llvm::SmallPtrSet<MemberKind*, 1> Results;
7587 
7588   if (!RT)
7589     return Results;
7590   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7591   if (!RD || !RD->getDefinition())
7592     return Results;
7593 
7594   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7595                  Sema::LookupMemberName);
7596   R.suppressDiagnostics();
7597 
7598   // We just need to include all members of the right kind turned up by the
7599   // filter, at this point.
7600   if (S.LookupQualifiedName(R, RT->getDecl()))
7601     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7602       NamedDecl *decl = (*I)->getUnderlyingDecl();
7603       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7604         Results.insert(FK);
7605     }
7606   return Results;
7607 }
7608 
7609 /// Check if we could call '.c_str()' on an object.
7610 ///
7611 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7612 /// allow the call, or if it would be ambiguous).
7613 bool Sema::hasCStrMethod(const Expr *E) {
7614   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7615 
7616   MethodSet Results =
7617       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7618   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7619        MI != ME; ++MI)
7620     if ((*MI)->getMinRequiredArguments() == 0)
7621       return true;
7622   return false;
7623 }
7624 
7625 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7626 // better diagnostic if so. AT is assumed to be valid.
7627 // Returns true when a c_str() conversion method is found.
7628 bool CheckPrintfHandler::checkForCStrMembers(
7629     const analyze_printf::ArgType &AT, const Expr *E) {
7630   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7631 
7632   MethodSet Results =
7633       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7634 
7635   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7636        MI != ME; ++MI) {
7637     const CXXMethodDecl *Method = *MI;
7638     if (Method->getMinRequiredArguments() == 0 &&
7639         AT.matchesType(S.Context, Method->getReturnType())) {
7640       // FIXME: Suggest parens if the expression needs them.
7641       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7642       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7643           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7644       return true;
7645     }
7646   }
7647 
7648   return false;
7649 }
7650 
7651 bool
7652 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7653                                             &FS,
7654                                           const char *startSpecifier,
7655                                           unsigned specifierLen) {
7656   using namespace analyze_format_string;
7657   using namespace analyze_printf;
7658 
7659   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7660 
7661   if (FS.consumesDataArgument()) {
7662     if (atFirstArg) {
7663         atFirstArg = false;
7664         usesPositionalArgs = FS.usesPositionalArg();
7665     }
7666     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7667       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7668                                         startSpecifier, specifierLen);
7669       return false;
7670     }
7671   }
7672 
7673   // First check if the field width, precision, and conversion specifier
7674   // have matching data arguments.
7675   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7676                     startSpecifier, specifierLen)) {
7677     return false;
7678   }
7679 
7680   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7681                     startSpecifier, specifierLen)) {
7682     return false;
7683   }
7684 
7685   if (!CS.consumesDataArgument()) {
7686     // FIXME: Technically specifying a precision or field width here
7687     // makes no sense.  Worth issuing a warning at some point.
7688     return true;
7689   }
7690 
7691   // Consume the argument.
7692   unsigned argIndex = FS.getArgIndex();
7693   if (argIndex < NumDataArgs) {
7694     // The check to see if the argIndex is valid will come later.
7695     // We set the bit here because we may exit early from this
7696     // function if we encounter some other error.
7697     CoveredArgs.set(argIndex);
7698   }
7699 
7700   // FreeBSD kernel extensions.
7701   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7702       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7703     // We need at least two arguments.
7704     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7705       return false;
7706 
7707     // Claim the second argument.
7708     CoveredArgs.set(argIndex + 1);
7709 
7710     // Type check the first argument (int for %b, pointer for %D)
7711     const Expr *Ex = getDataArg(argIndex);
7712     const analyze_printf::ArgType &AT =
7713       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7714         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7715     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7716       EmitFormatDiagnostic(
7717           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7718               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7719               << false << Ex->getSourceRange(),
7720           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7721           getSpecifierRange(startSpecifier, specifierLen));
7722 
7723     // Type check the second argument (char * for both %b and %D)
7724     Ex = getDataArg(argIndex + 1);
7725     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7726     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7727       EmitFormatDiagnostic(
7728           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7729               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7730               << false << Ex->getSourceRange(),
7731           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7732           getSpecifierRange(startSpecifier, specifierLen));
7733 
7734      return true;
7735   }
7736 
7737   // Check for using an Objective-C specific conversion specifier
7738   // in a non-ObjC literal.
7739   if (!allowsObjCArg() && CS.isObjCArg()) {
7740     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7741                                                   specifierLen);
7742   }
7743 
7744   // %P can only be used with os_log.
7745   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7746     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7747                                                   specifierLen);
7748   }
7749 
7750   // %n is not allowed with os_log.
7751   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7752     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7753                          getLocationOfByte(CS.getStart()),
7754                          /*IsStringLocation*/ false,
7755                          getSpecifierRange(startSpecifier, specifierLen));
7756 
7757     return true;
7758   }
7759 
7760   // Only scalars are allowed for os_trace.
7761   if (FSType == Sema::FST_OSTrace &&
7762       (CS.getKind() == ConversionSpecifier::PArg ||
7763        CS.getKind() == ConversionSpecifier::sArg ||
7764        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7765     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7766                                                   specifierLen);
7767   }
7768 
7769   // Check for use of public/private annotation outside of os_log().
7770   if (FSType != Sema::FST_OSLog) {
7771     if (FS.isPublic().isSet()) {
7772       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7773                                << "public",
7774                            getLocationOfByte(FS.isPublic().getPosition()),
7775                            /*IsStringLocation*/ false,
7776                            getSpecifierRange(startSpecifier, specifierLen));
7777     }
7778     if (FS.isPrivate().isSet()) {
7779       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7780                                << "private",
7781                            getLocationOfByte(FS.isPrivate().getPosition()),
7782                            /*IsStringLocation*/ false,
7783                            getSpecifierRange(startSpecifier, specifierLen));
7784     }
7785   }
7786 
7787   // Check for invalid use of field width
7788   if (!FS.hasValidFieldWidth()) {
7789     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7790         startSpecifier, specifierLen);
7791   }
7792 
7793   // Check for invalid use of precision
7794   if (!FS.hasValidPrecision()) {
7795     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7796         startSpecifier, specifierLen);
7797   }
7798 
7799   // Precision is mandatory for %P specifier.
7800   if (CS.getKind() == ConversionSpecifier::PArg &&
7801       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7802     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7803                          getLocationOfByte(startSpecifier),
7804                          /*IsStringLocation*/ false,
7805                          getSpecifierRange(startSpecifier, specifierLen));
7806   }
7807 
7808   // Check each flag does not conflict with any other component.
7809   if (!FS.hasValidThousandsGroupingPrefix())
7810     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7811   if (!FS.hasValidLeadingZeros())
7812     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7813   if (!FS.hasValidPlusPrefix())
7814     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7815   if (!FS.hasValidSpacePrefix())
7816     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7817   if (!FS.hasValidAlternativeForm())
7818     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7819   if (!FS.hasValidLeftJustified())
7820     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7821 
7822   // Check that flags are not ignored by another flag
7823   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7824     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7825         startSpecifier, specifierLen);
7826   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7827     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7828             startSpecifier, specifierLen);
7829 
7830   // Check the length modifier is valid with the given conversion specifier.
7831   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7832                                  S.getLangOpts()))
7833     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7834                                 diag::warn_format_nonsensical_length);
7835   else if (!FS.hasStandardLengthModifier())
7836     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7837   else if (!FS.hasStandardLengthConversionCombination())
7838     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7839                                 diag::warn_format_non_standard_conversion_spec);
7840 
7841   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7842     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7843 
7844   // The remaining checks depend on the data arguments.
7845   if (HasVAListArg)
7846     return true;
7847 
7848   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7849     return false;
7850 
7851   const Expr *Arg = getDataArg(argIndex);
7852   if (!Arg)
7853     return true;
7854 
7855   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7856 }
7857 
7858 static bool requiresParensToAddCast(const Expr *E) {
7859   // FIXME: We should have a general way to reason about operator
7860   // precedence and whether parens are actually needed here.
7861   // Take care of a few common cases where they aren't.
7862   const Expr *Inside = E->IgnoreImpCasts();
7863   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7864     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7865 
7866   switch (Inside->getStmtClass()) {
7867   case Stmt::ArraySubscriptExprClass:
7868   case Stmt::CallExprClass:
7869   case Stmt::CharacterLiteralClass:
7870   case Stmt::CXXBoolLiteralExprClass:
7871   case Stmt::DeclRefExprClass:
7872   case Stmt::FloatingLiteralClass:
7873   case Stmt::IntegerLiteralClass:
7874   case Stmt::MemberExprClass:
7875   case Stmt::ObjCArrayLiteralClass:
7876   case Stmt::ObjCBoolLiteralExprClass:
7877   case Stmt::ObjCBoxedExprClass:
7878   case Stmt::ObjCDictionaryLiteralClass:
7879   case Stmt::ObjCEncodeExprClass:
7880   case Stmt::ObjCIvarRefExprClass:
7881   case Stmt::ObjCMessageExprClass:
7882   case Stmt::ObjCPropertyRefExprClass:
7883   case Stmt::ObjCStringLiteralClass:
7884   case Stmt::ObjCSubscriptRefExprClass:
7885   case Stmt::ParenExprClass:
7886   case Stmt::StringLiteralClass:
7887   case Stmt::UnaryOperatorClass:
7888     return false;
7889   default:
7890     return true;
7891   }
7892 }
7893 
7894 static std::pair<QualType, StringRef>
7895 shouldNotPrintDirectly(const ASTContext &Context,
7896                        QualType IntendedTy,
7897                        const Expr *E) {
7898   // Use a 'while' to peel off layers of typedefs.
7899   QualType TyTy = IntendedTy;
7900   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7901     StringRef Name = UserTy->getDecl()->getName();
7902     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7903       .Case("CFIndex", Context.getNSIntegerType())
7904       .Case("NSInteger", Context.getNSIntegerType())
7905       .Case("NSUInteger", Context.getNSUIntegerType())
7906       .Case("SInt32", Context.IntTy)
7907       .Case("UInt32", Context.UnsignedIntTy)
7908       .Default(QualType());
7909 
7910     if (!CastTy.isNull())
7911       return std::make_pair(CastTy, Name);
7912 
7913     TyTy = UserTy->desugar();
7914   }
7915 
7916   // Strip parens if necessary.
7917   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7918     return shouldNotPrintDirectly(Context,
7919                                   PE->getSubExpr()->getType(),
7920                                   PE->getSubExpr());
7921 
7922   // If this is a conditional expression, then its result type is constructed
7923   // via usual arithmetic conversions and thus there might be no necessary
7924   // typedef sugar there.  Recurse to operands to check for NSInteger &
7925   // Co. usage condition.
7926   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7927     QualType TrueTy, FalseTy;
7928     StringRef TrueName, FalseName;
7929 
7930     std::tie(TrueTy, TrueName) =
7931       shouldNotPrintDirectly(Context,
7932                              CO->getTrueExpr()->getType(),
7933                              CO->getTrueExpr());
7934     std::tie(FalseTy, FalseName) =
7935       shouldNotPrintDirectly(Context,
7936                              CO->getFalseExpr()->getType(),
7937                              CO->getFalseExpr());
7938 
7939     if (TrueTy == FalseTy)
7940       return std::make_pair(TrueTy, TrueName);
7941     else if (TrueTy.isNull())
7942       return std::make_pair(FalseTy, FalseName);
7943     else if (FalseTy.isNull())
7944       return std::make_pair(TrueTy, TrueName);
7945   }
7946 
7947   return std::make_pair(QualType(), StringRef());
7948 }
7949 
7950 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7951 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7952 /// type do not count.
7953 static bool
7954 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7955   QualType From = ICE->getSubExpr()->getType();
7956   QualType To = ICE->getType();
7957   // It's an integer promotion if the destination type is the promoted
7958   // source type.
7959   if (ICE->getCastKind() == CK_IntegralCast &&
7960       From->isPromotableIntegerType() &&
7961       S.Context.getPromotedIntegerType(From) == To)
7962     return true;
7963   // Look through vector types, since we do default argument promotion for
7964   // those in OpenCL.
7965   if (const auto *VecTy = From->getAs<ExtVectorType>())
7966     From = VecTy->getElementType();
7967   if (const auto *VecTy = To->getAs<ExtVectorType>())
7968     To = VecTy->getElementType();
7969   // It's a floating promotion if the source type is a lower rank.
7970   return ICE->getCastKind() == CK_FloatingCast &&
7971          S.Context.getFloatingTypeOrder(From, To) < 0;
7972 }
7973 
7974 bool
7975 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7976                                     const char *StartSpecifier,
7977                                     unsigned SpecifierLen,
7978                                     const Expr *E) {
7979   using namespace analyze_format_string;
7980   using namespace analyze_printf;
7981 
7982   // Now type check the data expression that matches the
7983   // format specifier.
7984   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7985   if (!AT.isValid())
7986     return true;
7987 
7988   QualType ExprTy = E->getType();
7989   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7990     ExprTy = TET->getUnderlyingExpr()->getType();
7991   }
7992 
7993   // Diagnose attempts to print a boolean value as a character. Unlike other
7994   // -Wformat diagnostics, this is fine from a type perspective, but it still
7995   // doesn't make sense.
7996   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
7997       E->isKnownToHaveBooleanValue()) {
7998     const CharSourceRange &CSR =
7999         getSpecifierRange(StartSpecifier, SpecifierLen);
8000     SmallString<4> FSString;
8001     llvm::raw_svector_ostream os(FSString);
8002     FS.toString(os);
8003     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8004                              << FSString,
8005                          E->getExprLoc(), false, CSR);
8006     return true;
8007   }
8008 
8009   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8010   if (Match == analyze_printf::ArgType::Match)
8011     return true;
8012 
8013   // Look through argument promotions for our error message's reported type.
8014   // This includes the integral and floating promotions, but excludes array
8015   // and function pointer decay (seeing that an argument intended to be a
8016   // string has type 'char [6]' is probably more confusing than 'char *') and
8017   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8018   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8019     if (isArithmeticArgumentPromotion(S, ICE)) {
8020       E = ICE->getSubExpr();
8021       ExprTy = E->getType();
8022 
8023       // Check if we didn't match because of an implicit cast from a 'char'
8024       // or 'short' to an 'int'.  This is done because printf is a varargs
8025       // function.
8026       if (ICE->getType() == S.Context.IntTy ||
8027           ICE->getType() == S.Context.UnsignedIntTy) {
8028         // All further checking is done on the subexpression
8029         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8030             AT.matchesType(S.Context, ExprTy);
8031         if (ImplicitMatch == analyze_printf::ArgType::Match)
8032           return true;
8033         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8034             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8035           Match = ImplicitMatch;
8036       }
8037     }
8038   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8039     // Special case for 'a', which has type 'int' in C.
8040     // Note, however, that we do /not/ want to treat multibyte constants like
8041     // 'MooV' as characters! This form is deprecated but still exists.
8042     if (ExprTy == S.Context.IntTy)
8043       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8044         ExprTy = S.Context.CharTy;
8045   }
8046 
8047   // Look through enums to their underlying type.
8048   bool IsEnum = false;
8049   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8050     ExprTy = EnumTy->getDecl()->getIntegerType();
8051     IsEnum = true;
8052   }
8053 
8054   // %C in an Objective-C context prints a unichar, not a wchar_t.
8055   // If the argument is an integer of some kind, believe the %C and suggest
8056   // a cast instead of changing the conversion specifier.
8057   QualType IntendedTy = ExprTy;
8058   if (isObjCContext() &&
8059       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8060     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8061         !ExprTy->isCharType()) {
8062       // 'unichar' is defined as a typedef of unsigned short, but we should
8063       // prefer using the typedef if it is visible.
8064       IntendedTy = S.Context.UnsignedShortTy;
8065 
8066       // While we are here, check if the value is an IntegerLiteral that happens
8067       // to be within the valid range.
8068       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8069         const llvm::APInt &V = IL->getValue();
8070         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8071           return true;
8072       }
8073 
8074       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8075                           Sema::LookupOrdinaryName);
8076       if (S.LookupName(Result, S.getCurScope())) {
8077         NamedDecl *ND = Result.getFoundDecl();
8078         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8079           if (TD->getUnderlyingType() == IntendedTy)
8080             IntendedTy = S.Context.getTypedefType(TD);
8081       }
8082     }
8083   }
8084 
8085   // Special-case some of Darwin's platform-independence types by suggesting
8086   // casts to primitive types that are known to be large enough.
8087   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8088   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8089     QualType CastTy;
8090     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8091     if (!CastTy.isNull()) {
8092       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8093       // (long in ASTContext). Only complain to pedants.
8094       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8095           (AT.isSizeT() || AT.isPtrdiffT()) &&
8096           AT.matchesType(S.Context, CastTy))
8097         Match = ArgType::NoMatchPedantic;
8098       IntendedTy = CastTy;
8099       ShouldNotPrintDirectly = true;
8100     }
8101   }
8102 
8103   // We may be able to offer a FixItHint if it is a supported type.
8104   PrintfSpecifier fixedFS = FS;
8105   bool Success =
8106       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8107 
8108   if (Success) {
8109     // Get the fix string from the fixed format specifier
8110     SmallString<16> buf;
8111     llvm::raw_svector_ostream os(buf);
8112     fixedFS.toString(os);
8113 
8114     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8115 
8116     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8117       unsigned Diag;
8118       switch (Match) {
8119       case ArgType::Match: llvm_unreachable("expected non-matching");
8120       case ArgType::NoMatchPedantic:
8121         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8122         break;
8123       case ArgType::NoMatchTypeConfusion:
8124         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8125         break;
8126       case ArgType::NoMatch:
8127         Diag = diag::warn_format_conversion_argument_type_mismatch;
8128         break;
8129       }
8130 
8131       // In this case, the specifier is wrong and should be changed to match
8132       // the argument.
8133       EmitFormatDiagnostic(S.PDiag(Diag)
8134                                << AT.getRepresentativeTypeName(S.Context)
8135                                << IntendedTy << IsEnum << E->getSourceRange(),
8136                            E->getBeginLoc(),
8137                            /*IsStringLocation*/ false, SpecRange,
8138                            FixItHint::CreateReplacement(SpecRange, os.str()));
8139     } else {
8140       // The canonical type for formatting this value is different from the
8141       // actual type of the expression. (This occurs, for example, with Darwin's
8142       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8143       // should be printed as 'long' for 64-bit compatibility.)
8144       // Rather than emitting a normal format/argument mismatch, we want to
8145       // add a cast to the recommended type (and correct the format string
8146       // if necessary).
8147       SmallString<16> CastBuf;
8148       llvm::raw_svector_ostream CastFix(CastBuf);
8149       CastFix << "(";
8150       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8151       CastFix << ")";
8152 
8153       SmallVector<FixItHint,4> Hints;
8154       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8155         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8156 
8157       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8158         // If there's already a cast present, just replace it.
8159         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8160         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8161 
8162       } else if (!requiresParensToAddCast(E)) {
8163         // If the expression has high enough precedence,
8164         // just write the C-style cast.
8165         Hints.push_back(
8166             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8167       } else {
8168         // Otherwise, add parens around the expression as well as the cast.
8169         CastFix << "(";
8170         Hints.push_back(
8171             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8172 
8173         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8174         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8175       }
8176 
8177       if (ShouldNotPrintDirectly) {
8178         // The expression has a type that should not be printed directly.
8179         // We extract the name from the typedef because we don't want to show
8180         // the underlying type in the diagnostic.
8181         StringRef Name;
8182         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8183           Name = TypedefTy->getDecl()->getName();
8184         else
8185           Name = CastTyName;
8186         unsigned Diag = Match == ArgType::NoMatchPedantic
8187                             ? diag::warn_format_argument_needs_cast_pedantic
8188                             : diag::warn_format_argument_needs_cast;
8189         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8190                                            << E->getSourceRange(),
8191                              E->getBeginLoc(), /*IsStringLocation=*/false,
8192                              SpecRange, Hints);
8193       } else {
8194         // In this case, the expression could be printed using a different
8195         // specifier, but we've decided that the specifier is probably correct
8196         // and we should cast instead. Just use the normal warning message.
8197         EmitFormatDiagnostic(
8198             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8199                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8200                 << E->getSourceRange(),
8201             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8202       }
8203     }
8204   } else {
8205     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8206                                                    SpecifierLen);
8207     // Since the warning for passing non-POD types to variadic functions
8208     // was deferred until now, we emit a warning for non-POD
8209     // arguments here.
8210     switch (S.isValidVarArgType(ExprTy)) {
8211     case Sema::VAK_Valid:
8212     case Sema::VAK_ValidInCXX11: {
8213       unsigned Diag;
8214       switch (Match) {
8215       case ArgType::Match: llvm_unreachable("expected non-matching");
8216       case ArgType::NoMatchPedantic:
8217         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8218         break;
8219       case ArgType::NoMatchTypeConfusion:
8220         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8221         break;
8222       case ArgType::NoMatch:
8223         Diag = diag::warn_format_conversion_argument_type_mismatch;
8224         break;
8225       }
8226 
8227       EmitFormatDiagnostic(
8228           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8229                         << IsEnum << CSR << E->getSourceRange(),
8230           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8231       break;
8232     }
8233     case Sema::VAK_Undefined:
8234     case Sema::VAK_MSVCUndefined:
8235       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8236                                << S.getLangOpts().CPlusPlus11 << ExprTy
8237                                << CallType
8238                                << AT.getRepresentativeTypeName(S.Context) << CSR
8239                                << E->getSourceRange(),
8240                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8241       checkForCStrMembers(AT, E);
8242       break;
8243 
8244     case Sema::VAK_Invalid:
8245       if (ExprTy->isObjCObjectType())
8246         EmitFormatDiagnostic(
8247             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8248                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8249                 << AT.getRepresentativeTypeName(S.Context) << CSR
8250                 << E->getSourceRange(),
8251             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8252       else
8253         // FIXME: If this is an initializer list, suggest removing the braces
8254         // or inserting a cast to the target type.
8255         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8256             << isa<InitListExpr>(E) << ExprTy << CallType
8257             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8258       break;
8259     }
8260 
8261     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8262            "format string specifier index out of range");
8263     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8264   }
8265 
8266   return true;
8267 }
8268 
8269 //===--- CHECK: Scanf format string checking ------------------------------===//
8270 
8271 namespace {
8272 
8273 class CheckScanfHandler : public CheckFormatHandler {
8274 public:
8275   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8276                     const Expr *origFormatExpr, Sema::FormatStringType type,
8277                     unsigned firstDataArg, unsigned numDataArgs,
8278                     const char *beg, bool hasVAListArg,
8279                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8280                     bool inFunctionCall, Sema::VariadicCallType CallType,
8281                     llvm::SmallBitVector &CheckedVarArgs,
8282                     UncoveredArgHandler &UncoveredArg)
8283       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8284                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8285                            inFunctionCall, CallType, CheckedVarArgs,
8286                            UncoveredArg) {}
8287 
8288   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8289                             const char *startSpecifier,
8290                             unsigned specifierLen) override;
8291 
8292   bool HandleInvalidScanfConversionSpecifier(
8293           const analyze_scanf::ScanfSpecifier &FS,
8294           const char *startSpecifier,
8295           unsigned specifierLen) override;
8296 
8297   void HandleIncompleteScanList(const char *start, const char *end) override;
8298 };
8299 
8300 } // namespace
8301 
8302 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8303                                                  const char *end) {
8304   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8305                        getLocationOfByte(end), /*IsStringLocation*/true,
8306                        getSpecifierRange(start, end - start));
8307 }
8308 
8309 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8310                                         const analyze_scanf::ScanfSpecifier &FS,
8311                                         const char *startSpecifier,
8312                                         unsigned specifierLen) {
8313   const analyze_scanf::ScanfConversionSpecifier &CS =
8314     FS.getConversionSpecifier();
8315 
8316   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8317                                           getLocationOfByte(CS.getStart()),
8318                                           startSpecifier, specifierLen,
8319                                           CS.getStart(), CS.getLength());
8320 }
8321 
8322 bool CheckScanfHandler::HandleScanfSpecifier(
8323                                        const analyze_scanf::ScanfSpecifier &FS,
8324                                        const char *startSpecifier,
8325                                        unsigned specifierLen) {
8326   using namespace analyze_scanf;
8327   using namespace analyze_format_string;
8328 
8329   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8330 
8331   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8332   // be used to decide if we are using positional arguments consistently.
8333   if (FS.consumesDataArgument()) {
8334     if (atFirstArg) {
8335       atFirstArg = false;
8336       usesPositionalArgs = FS.usesPositionalArg();
8337     }
8338     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8339       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8340                                         startSpecifier, specifierLen);
8341       return false;
8342     }
8343   }
8344 
8345   // Check if the field with is non-zero.
8346   const OptionalAmount &Amt = FS.getFieldWidth();
8347   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8348     if (Amt.getConstantAmount() == 0) {
8349       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8350                                                    Amt.getConstantLength());
8351       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8352                            getLocationOfByte(Amt.getStart()),
8353                            /*IsStringLocation*/true, R,
8354                            FixItHint::CreateRemoval(R));
8355     }
8356   }
8357 
8358   if (!FS.consumesDataArgument()) {
8359     // FIXME: Technically specifying a precision or field width here
8360     // makes no sense.  Worth issuing a warning at some point.
8361     return true;
8362   }
8363 
8364   // Consume the argument.
8365   unsigned argIndex = FS.getArgIndex();
8366   if (argIndex < NumDataArgs) {
8367       // The check to see if the argIndex is valid will come later.
8368       // We set the bit here because we may exit early from this
8369       // function if we encounter some other error.
8370     CoveredArgs.set(argIndex);
8371   }
8372 
8373   // Check the length modifier is valid with the given conversion specifier.
8374   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8375                                  S.getLangOpts()))
8376     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8377                                 diag::warn_format_nonsensical_length);
8378   else if (!FS.hasStandardLengthModifier())
8379     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8380   else if (!FS.hasStandardLengthConversionCombination())
8381     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8382                                 diag::warn_format_non_standard_conversion_spec);
8383 
8384   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8385     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8386 
8387   // The remaining checks depend on the data arguments.
8388   if (HasVAListArg)
8389     return true;
8390 
8391   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8392     return false;
8393 
8394   // Check that the argument type matches the format specifier.
8395   const Expr *Ex = getDataArg(argIndex);
8396   if (!Ex)
8397     return true;
8398 
8399   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8400 
8401   if (!AT.isValid()) {
8402     return true;
8403   }
8404 
8405   analyze_format_string::ArgType::MatchKind Match =
8406       AT.matchesType(S.Context, Ex->getType());
8407   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8408   if (Match == analyze_format_string::ArgType::Match)
8409     return true;
8410 
8411   ScanfSpecifier fixedFS = FS;
8412   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8413                                  S.getLangOpts(), S.Context);
8414 
8415   unsigned Diag =
8416       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8417                : diag::warn_format_conversion_argument_type_mismatch;
8418 
8419   if (Success) {
8420     // Get the fix string from the fixed format specifier.
8421     SmallString<128> buf;
8422     llvm::raw_svector_ostream os(buf);
8423     fixedFS.toString(os);
8424 
8425     EmitFormatDiagnostic(
8426         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8427                       << Ex->getType() << false << Ex->getSourceRange(),
8428         Ex->getBeginLoc(),
8429         /*IsStringLocation*/ false,
8430         getSpecifierRange(startSpecifier, specifierLen),
8431         FixItHint::CreateReplacement(
8432             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8433   } else {
8434     EmitFormatDiagnostic(S.PDiag(Diag)
8435                              << AT.getRepresentativeTypeName(S.Context)
8436                              << Ex->getType() << false << Ex->getSourceRange(),
8437                          Ex->getBeginLoc(),
8438                          /*IsStringLocation*/ false,
8439                          getSpecifierRange(startSpecifier, specifierLen));
8440   }
8441 
8442   return true;
8443 }
8444 
8445 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8446                               const Expr *OrigFormatExpr,
8447                               ArrayRef<const Expr *> Args,
8448                               bool HasVAListArg, unsigned format_idx,
8449                               unsigned firstDataArg,
8450                               Sema::FormatStringType Type,
8451                               bool inFunctionCall,
8452                               Sema::VariadicCallType CallType,
8453                               llvm::SmallBitVector &CheckedVarArgs,
8454                               UncoveredArgHandler &UncoveredArg,
8455                               bool IgnoreStringsWithoutSpecifiers) {
8456   // CHECK: is the format string a wide literal?
8457   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8458     CheckFormatHandler::EmitFormatDiagnostic(
8459         S, inFunctionCall, Args[format_idx],
8460         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8461         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8462     return;
8463   }
8464 
8465   // Str - The format string.  NOTE: this is NOT null-terminated!
8466   StringRef StrRef = FExpr->getString();
8467   const char *Str = StrRef.data();
8468   // Account for cases where the string literal is truncated in a declaration.
8469   const ConstantArrayType *T =
8470     S.Context.getAsConstantArrayType(FExpr->getType());
8471   assert(T && "String literal not of constant array type!");
8472   size_t TypeSize = T->getSize().getZExtValue();
8473   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8474   const unsigned numDataArgs = Args.size() - firstDataArg;
8475 
8476   if (IgnoreStringsWithoutSpecifiers &&
8477       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8478           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8479     return;
8480 
8481   // Emit a warning if the string literal is truncated and does not contain an
8482   // embedded null character.
8483   if (TypeSize <= StrRef.size() &&
8484       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8485     CheckFormatHandler::EmitFormatDiagnostic(
8486         S, inFunctionCall, Args[format_idx],
8487         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8488         FExpr->getBeginLoc(),
8489         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8490     return;
8491   }
8492 
8493   // CHECK: empty format string?
8494   if (StrLen == 0 && numDataArgs > 0) {
8495     CheckFormatHandler::EmitFormatDiagnostic(
8496         S, inFunctionCall, Args[format_idx],
8497         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8498         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8499     return;
8500   }
8501 
8502   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8503       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8504       Type == Sema::FST_OSTrace) {
8505     CheckPrintfHandler H(
8506         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8507         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8508         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8509         CheckedVarArgs, UncoveredArg);
8510 
8511     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8512                                                   S.getLangOpts(),
8513                                                   S.Context.getTargetInfo(),
8514                                             Type == Sema::FST_FreeBSDKPrintf))
8515       H.DoneProcessing();
8516   } else if (Type == Sema::FST_Scanf) {
8517     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8518                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8519                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8520 
8521     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8522                                                  S.getLangOpts(),
8523                                                  S.Context.getTargetInfo()))
8524       H.DoneProcessing();
8525   } // TODO: handle other formats
8526 }
8527 
8528 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8529   // Str - The format string.  NOTE: this is NOT null-terminated!
8530   StringRef StrRef = FExpr->getString();
8531   const char *Str = StrRef.data();
8532   // Account for cases where the string literal is truncated in a declaration.
8533   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8534   assert(T && "String literal not of constant array type!");
8535   size_t TypeSize = T->getSize().getZExtValue();
8536   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8537   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8538                                                          getLangOpts(),
8539                                                          Context.getTargetInfo());
8540 }
8541 
8542 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8543 
8544 // Returns the related absolute value function that is larger, of 0 if one
8545 // does not exist.
8546 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8547   switch (AbsFunction) {
8548   default:
8549     return 0;
8550 
8551   case Builtin::BI__builtin_abs:
8552     return Builtin::BI__builtin_labs;
8553   case Builtin::BI__builtin_labs:
8554     return Builtin::BI__builtin_llabs;
8555   case Builtin::BI__builtin_llabs:
8556     return 0;
8557 
8558   case Builtin::BI__builtin_fabsf:
8559     return Builtin::BI__builtin_fabs;
8560   case Builtin::BI__builtin_fabs:
8561     return Builtin::BI__builtin_fabsl;
8562   case Builtin::BI__builtin_fabsl:
8563     return 0;
8564 
8565   case Builtin::BI__builtin_cabsf:
8566     return Builtin::BI__builtin_cabs;
8567   case Builtin::BI__builtin_cabs:
8568     return Builtin::BI__builtin_cabsl;
8569   case Builtin::BI__builtin_cabsl:
8570     return 0;
8571 
8572   case Builtin::BIabs:
8573     return Builtin::BIlabs;
8574   case Builtin::BIlabs:
8575     return Builtin::BIllabs;
8576   case Builtin::BIllabs:
8577     return 0;
8578 
8579   case Builtin::BIfabsf:
8580     return Builtin::BIfabs;
8581   case Builtin::BIfabs:
8582     return Builtin::BIfabsl;
8583   case Builtin::BIfabsl:
8584     return 0;
8585 
8586   case Builtin::BIcabsf:
8587    return Builtin::BIcabs;
8588   case Builtin::BIcabs:
8589     return Builtin::BIcabsl;
8590   case Builtin::BIcabsl:
8591     return 0;
8592   }
8593 }
8594 
8595 // Returns the argument type of the absolute value function.
8596 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8597                                              unsigned AbsType) {
8598   if (AbsType == 0)
8599     return QualType();
8600 
8601   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8602   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8603   if (Error != ASTContext::GE_None)
8604     return QualType();
8605 
8606   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8607   if (!FT)
8608     return QualType();
8609 
8610   if (FT->getNumParams() != 1)
8611     return QualType();
8612 
8613   return FT->getParamType(0);
8614 }
8615 
8616 // Returns the best absolute value function, or zero, based on type and
8617 // current absolute value function.
8618 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8619                                    unsigned AbsFunctionKind) {
8620   unsigned BestKind = 0;
8621   uint64_t ArgSize = Context.getTypeSize(ArgType);
8622   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8623        Kind = getLargerAbsoluteValueFunction(Kind)) {
8624     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8625     if (Context.getTypeSize(ParamType) >= ArgSize) {
8626       if (BestKind == 0)
8627         BestKind = Kind;
8628       else if (Context.hasSameType(ParamType, ArgType)) {
8629         BestKind = Kind;
8630         break;
8631       }
8632     }
8633   }
8634   return BestKind;
8635 }
8636 
8637 enum AbsoluteValueKind {
8638   AVK_Integer,
8639   AVK_Floating,
8640   AVK_Complex
8641 };
8642 
8643 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8644   if (T->isIntegralOrEnumerationType())
8645     return AVK_Integer;
8646   if (T->isRealFloatingType())
8647     return AVK_Floating;
8648   if (T->isAnyComplexType())
8649     return AVK_Complex;
8650 
8651   llvm_unreachable("Type not integer, floating, or complex");
8652 }
8653 
8654 // Changes the absolute value function to a different type.  Preserves whether
8655 // the function is a builtin.
8656 static unsigned changeAbsFunction(unsigned AbsKind,
8657                                   AbsoluteValueKind ValueKind) {
8658   switch (ValueKind) {
8659   case AVK_Integer:
8660     switch (AbsKind) {
8661     default:
8662       return 0;
8663     case Builtin::BI__builtin_fabsf:
8664     case Builtin::BI__builtin_fabs:
8665     case Builtin::BI__builtin_fabsl:
8666     case Builtin::BI__builtin_cabsf:
8667     case Builtin::BI__builtin_cabs:
8668     case Builtin::BI__builtin_cabsl:
8669       return Builtin::BI__builtin_abs;
8670     case Builtin::BIfabsf:
8671     case Builtin::BIfabs:
8672     case Builtin::BIfabsl:
8673     case Builtin::BIcabsf:
8674     case Builtin::BIcabs:
8675     case Builtin::BIcabsl:
8676       return Builtin::BIabs;
8677     }
8678   case AVK_Floating:
8679     switch (AbsKind) {
8680     default:
8681       return 0;
8682     case Builtin::BI__builtin_abs:
8683     case Builtin::BI__builtin_labs:
8684     case Builtin::BI__builtin_llabs:
8685     case Builtin::BI__builtin_cabsf:
8686     case Builtin::BI__builtin_cabs:
8687     case Builtin::BI__builtin_cabsl:
8688       return Builtin::BI__builtin_fabsf;
8689     case Builtin::BIabs:
8690     case Builtin::BIlabs:
8691     case Builtin::BIllabs:
8692     case Builtin::BIcabsf:
8693     case Builtin::BIcabs:
8694     case Builtin::BIcabsl:
8695       return Builtin::BIfabsf;
8696     }
8697   case AVK_Complex:
8698     switch (AbsKind) {
8699     default:
8700       return 0;
8701     case Builtin::BI__builtin_abs:
8702     case Builtin::BI__builtin_labs:
8703     case Builtin::BI__builtin_llabs:
8704     case Builtin::BI__builtin_fabsf:
8705     case Builtin::BI__builtin_fabs:
8706     case Builtin::BI__builtin_fabsl:
8707       return Builtin::BI__builtin_cabsf;
8708     case Builtin::BIabs:
8709     case Builtin::BIlabs:
8710     case Builtin::BIllabs:
8711     case Builtin::BIfabsf:
8712     case Builtin::BIfabs:
8713     case Builtin::BIfabsl:
8714       return Builtin::BIcabsf;
8715     }
8716   }
8717   llvm_unreachable("Unable to convert function");
8718 }
8719 
8720 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8721   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8722   if (!FnInfo)
8723     return 0;
8724 
8725   switch (FDecl->getBuiltinID()) {
8726   default:
8727     return 0;
8728   case Builtin::BI__builtin_abs:
8729   case Builtin::BI__builtin_fabs:
8730   case Builtin::BI__builtin_fabsf:
8731   case Builtin::BI__builtin_fabsl:
8732   case Builtin::BI__builtin_labs:
8733   case Builtin::BI__builtin_llabs:
8734   case Builtin::BI__builtin_cabs:
8735   case Builtin::BI__builtin_cabsf:
8736   case Builtin::BI__builtin_cabsl:
8737   case Builtin::BIabs:
8738   case Builtin::BIlabs:
8739   case Builtin::BIllabs:
8740   case Builtin::BIfabs:
8741   case Builtin::BIfabsf:
8742   case Builtin::BIfabsl:
8743   case Builtin::BIcabs:
8744   case Builtin::BIcabsf:
8745   case Builtin::BIcabsl:
8746     return FDecl->getBuiltinID();
8747   }
8748   llvm_unreachable("Unknown Builtin type");
8749 }
8750 
8751 // If the replacement is valid, emit a note with replacement function.
8752 // Additionally, suggest including the proper header if not already included.
8753 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8754                             unsigned AbsKind, QualType ArgType) {
8755   bool EmitHeaderHint = true;
8756   const char *HeaderName = nullptr;
8757   const char *FunctionName = nullptr;
8758   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8759     FunctionName = "std::abs";
8760     if (ArgType->isIntegralOrEnumerationType()) {
8761       HeaderName = "cstdlib";
8762     } else if (ArgType->isRealFloatingType()) {
8763       HeaderName = "cmath";
8764     } else {
8765       llvm_unreachable("Invalid Type");
8766     }
8767 
8768     // Lookup all std::abs
8769     if (NamespaceDecl *Std = S.getStdNamespace()) {
8770       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8771       R.suppressDiagnostics();
8772       S.LookupQualifiedName(R, Std);
8773 
8774       for (const auto *I : R) {
8775         const FunctionDecl *FDecl = nullptr;
8776         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8777           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8778         } else {
8779           FDecl = dyn_cast<FunctionDecl>(I);
8780         }
8781         if (!FDecl)
8782           continue;
8783 
8784         // Found std::abs(), check that they are the right ones.
8785         if (FDecl->getNumParams() != 1)
8786           continue;
8787 
8788         // Check that the parameter type can handle the argument.
8789         QualType ParamType = FDecl->getParamDecl(0)->getType();
8790         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8791             S.Context.getTypeSize(ArgType) <=
8792                 S.Context.getTypeSize(ParamType)) {
8793           // Found a function, don't need the header hint.
8794           EmitHeaderHint = false;
8795           break;
8796         }
8797       }
8798     }
8799   } else {
8800     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8801     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8802 
8803     if (HeaderName) {
8804       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8805       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8806       R.suppressDiagnostics();
8807       S.LookupName(R, S.getCurScope());
8808 
8809       if (R.isSingleResult()) {
8810         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8811         if (FD && FD->getBuiltinID() == AbsKind) {
8812           EmitHeaderHint = false;
8813         } else {
8814           return;
8815         }
8816       } else if (!R.empty()) {
8817         return;
8818       }
8819     }
8820   }
8821 
8822   S.Diag(Loc, diag::note_replace_abs_function)
8823       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8824 
8825   if (!HeaderName)
8826     return;
8827 
8828   if (!EmitHeaderHint)
8829     return;
8830 
8831   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8832                                                     << FunctionName;
8833 }
8834 
8835 template <std::size_t StrLen>
8836 static bool IsStdFunction(const FunctionDecl *FDecl,
8837                           const char (&Str)[StrLen]) {
8838   if (!FDecl)
8839     return false;
8840   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8841     return false;
8842   if (!FDecl->isInStdNamespace())
8843     return false;
8844 
8845   return true;
8846 }
8847 
8848 // Warn when using the wrong abs() function.
8849 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8850                                       const FunctionDecl *FDecl) {
8851   if (Call->getNumArgs() != 1)
8852     return;
8853 
8854   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8855   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8856   if (AbsKind == 0 && !IsStdAbs)
8857     return;
8858 
8859   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8860   QualType ParamType = Call->getArg(0)->getType();
8861 
8862   // Unsigned types cannot be negative.  Suggest removing the absolute value
8863   // function call.
8864   if (ArgType->isUnsignedIntegerType()) {
8865     const char *FunctionName =
8866         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8867     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8868     Diag(Call->getExprLoc(), diag::note_remove_abs)
8869         << FunctionName
8870         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8871     return;
8872   }
8873 
8874   // Taking the absolute value of a pointer is very suspicious, they probably
8875   // wanted to index into an array, dereference a pointer, call a function, etc.
8876   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8877     unsigned DiagType = 0;
8878     if (ArgType->isFunctionType())
8879       DiagType = 1;
8880     else if (ArgType->isArrayType())
8881       DiagType = 2;
8882 
8883     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8884     return;
8885   }
8886 
8887   // std::abs has overloads which prevent most of the absolute value problems
8888   // from occurring.
8889   if (IsStdAbs)
8890     return;
8891 
8892   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8893   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8894 
8895   // The argument and parameter are the same kind.  Check if they are the right
8896   // size.
8897   if (ArgValueKind == ParamValueKind) {
8898     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8899       return;
8900 
8901     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8902     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8903         << FDecl << ArgType << ParamType;
8904 
8905     if (NewAbsKind == 0)
8906       return;
8907 
8908     emitReplacement(*this, Call->getExprLoc(),
8909                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8910     return;
8911   }
8912 
8913   // ArgValueKind != ParamValueKind
8914   // The wrong type of absolute value function was used.  Attempt to find the
8915   // proper one.
8916   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8917   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8918   if (NewAbsKind == 0)
8919     return;
8920 
8921   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8922       << FDecl << ParamValueKind << ArgValueKind;
8923 
8924   emitReplacement(*this, Call->getExprLoc(),
8925                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8926 }
8927 
8928 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8929 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8930                                 const FunctionDecl *FDecl) {
8931   if (!Call || !FDecl) return;
8932 
8933   // Ignore template specializations and macros.
8934   if (inTemplateInstantiation()) return;
8935   if (Call->getExprLoc().isMacroID()) return;
8936 
8937   // Only care about the one template argument, two function parameter std::max
8938   if (Call->getNumArgs() != 2) return;
8939   if (!IsStdFunction(FDecl, "max")) return;
8940   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8941   if (!ArgList) return;
8942   if (ArgList->size() != 1) return;
8943 
8944   // Check that template type argument is unsigned integer.
8945   const auto& TA = ArgList->get(0);
8946   if (TA.getKind() != TemplateArgument::Type) return;
8947   QualType ArgType = TA.getAsType();
8948   if (!ArgType->isUnsignedIntegerType()) return;
8949 
8950   // See if either argument is a literal zero.
8951   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8952     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8953     if (!MTE) return false;
8954     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
8955     if (!Num) return false;
8956     if (Num->getValue() != 0) return false;
8957     return true;
8958   };
8959 
8960   const Expr *FirstArg = Call->getArg(0);
8961   const Expr *SecondArg = Call->getArg(1);
8962   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8963   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8964 
8965   // Only warn when exactly one argument is zero.
8966   if (IsFirstArgZero == IsSecondArgZero) return;
8967 
8968   SourceRange FirstRange = FirstArg->getSourceRange();
8969   SourceRange SecondRange = SecondArg->getSourceRange();
8970 
8971   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8972 
8973   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8974       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8975 
8976   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8977   SourceRange RemovalRange;
8978   if (IsFirstArgZero) {
8979     RemovalRange = SourceRange(FirstRange.getBegin(),
8980                                SecondRange.getBegin().getLocWithOffset(-1));
8981   } else {
8982     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8983                                SecondRange.getEnd());
8984   }
8985 
8986   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8987         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8988         << FixItHint::CreateRemoval(RemovalRange);
8989 }
8990 
8991 //===--- CHECK: Standard memory functions ---------------------------------===//
8992 
8993 /// Takes the expression passed to the size_t parameter of functions
8994 /// such as memcmp, strncat, etc and warns if it's a comparison.
8995 ///
8996 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8997 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8998                                            IdentifierInfo *FnName,
8999                                            SourceLocation FnLoc,
9000                                            SourceLocation RParenLoc) {
9001   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9002   if (!Size)
9003     return false;
9004 
9005   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9006   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9007     return false;
9008 
9009   SourceRange SizeRange = Size->getSourceRange();
9010   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9011       << SizeRange << FnName;
9012   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9013       << FnName
9014       << FixItHint::CreateInsertion(
9015              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9016       << FixItHint::CreateRemoval(RParenLoc);
9017   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9018       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9019       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9020                                     ")");
9021 
9022   return true;
9023 }
9024 
9025 /// Determine whether the given type is or contains a dynamic class type
9026 /// (e.g., whether it has a vtable).
9027 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9028                                                      bool &IsContained) {
9029   // Look through array types while ignoring qualifiers.
9030   const Type *Ty = T->getBaseElementTypeUnsafe();
9031   IsContained = false;
9032 
9033   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9034   RD = RD ? RD->getDefinition() : nullptr;
9035   if (!RD || RD->isInvalidDecl())
9036     return nullptr;
9037 
9038   if (RD->isDynamicClass())
9039     return RD;
9040 
9041   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9042   // It's impossible for a class to transitively contain itself by value, so
9043   // infinite recursion is impossible.
9044   for (auto *FD : RD->fields()) {
9045     bool SubContained;
9046     if (const CXXRecordDecl *ContainedRD =
9047             getContainedDynamicClass(FD->getType(), SubContained)) {
9048       IsContained = true;
9049       return ContainedRD;
9050     }
9051   }
9052 
9053   return nullptr;
9054 }
9055 
9056 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9057   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9058     if (Unary->getKind() == UETT_SizeOf)
9059       return Unary;
9060   return nullptr;
9061 }
9062 
9063 /// If E is a sizeof expression, returns its argument expression,
9064 /// otherwise returns NULL.
9065 static const Expr *getSizeOfExprArg(const Expr *E) {
9066   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9067     if (!SizeOf->isArgumentType())
9068       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9069   return nullptr;
9070 }
9071 
9072 /// If E is a sizeof expression, returns its argument type.
9073 static QualType getSizeOfArgType(const Expr *E) {
9074   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9075     return SizeOf->getTypeOfArgument();
9076   return QualType();
9077 }
9078 
9079 namespace {
9080 
9081 struct SearchNonTrivialToInitializeField
9082     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9083   using Super =
9084       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9085 
9086   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9087 
9088   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9089                      SourceLocation SL) {
9090     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9091       asDerived().visitArray(PDIK, AT, SL);
9092       return;
9093     }
9094 
9095     Super::visitWithKind(PDIK, FT, SL);
9096   }
9097 
9098   void visitARCStrong(QualType FT, SourceLocation SL) {
9099     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9100   }
9101   void visitARCWeak(QualType FT, SourceLocation SL) {
9102     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9103   }
9104   void visitStruct(QualType FT, SourceLocation SL) {
9105     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9106       visit(FD->getType(), FD->getLocation());
9107   }
9108   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9109                   const ArrayType *AT, SourceLocation SL) {
9110     visit(getContext().getBaseElementType(AT), SL);
9111   }
9112   void visitTrivial(QualType FT, SourceLocation SL) {}
9113 
9114   static void diag(QualType RT, const Expr *E, Sema &S) {
9115     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9116   }
9117 
9118   ASTContext &getContext() { return S.getASTContext(); }
9119 
9120   const Expr *E;
9121   Sema &S;
9122 };
9123 
9124 struct SearchNonTrivialToCopyField
9125     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9126   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9127 
9128   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9129 
9130   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9131                      SourceLocation SL) {
9132     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9133       asDerived().visitArray(PCK, AT, SL);
9134       return;
9135     }
9136 
9137     Super::visitWithKind(PCK, FT, SL);
9138   }
9139 
9140   void visitARCStrong(QualType FT, SourceLocation SL) {
9141     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9142   }
9143   void visitARCWeak(QualType FT, SourceLocation SL) {
9144     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9145   }
9146   void visitStruct(QualType FT, SourceLocation SL) {
9147     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9148       visit(FD->getType(), FD->getLocation());
9149   }
9150   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9151                   SourceLocation SL) {
9152     visit(getContext().getBaseElementType(AT), SL);
9153   }
9154   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9155                 SourceLocation SL) {}
9156   void visitTrivial(QualType FT, SourceLocation SL) {}
9157   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9158 
9159   static void diag(QualType RT, const Expr *E, Sema &S) {
9160     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9161   }
9162 
9163   ASTContext &getContext() { return S.getASTContext(); }
9164 
9165   const Expr *E;
9166   Sema &S;
9167 };
9168 
9169 }
9170 
9171 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9172 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9173   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9174 
9175   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9176     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9177       return false;
9178 
9179     return doesExprLikelyComputeSize(BO->getLHS()) ||
9180            doesExprLikelyComputeSize(BO->getRHS());
9181   }
9182 
9183   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9184 }
9185 
9186 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9187 ///
9188 /// \code
9189 ///   #define MACRO 0
9190 ///   foo(MACRO);
9191 ///   foo(0);
9192 /// \endcode
9193 ///
9194 /// This should return true for the first call to foo, but not for the second
9195 /// (regardless of whether foo is a macro or function).
9196 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9197                                         SourceLocation CallLoc,
9198                                         SourceLocation ArgLoc) {
9199   if (!CallLoc.isMacroID())
9200     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9201 
9202   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9203          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9204 }
9205 
9206 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9207 /// last two arguments transposed.
9208 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9209   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9210     return;
9211 
9212   const Expr *SizeArg =
9213     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9214 
9215   auto isLiteralZero = [](const Expr *E) {
9216     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9217   };
9218 
9219   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9220   SourceLocation CallLoc = Call->getRParenLoc();
9221   SourceManager &SM = S.getSourceManager();
9222   if (isLiteralZero(SizeArg) &&
9223       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9224 
9225     SourceLocation DiagLoc = SizeArg->getExprLoc();
9226 
9227     // Some platforms #define bzero to __builtin_memset. See if this is the
9228     // case, and if so, emit a better diagnostic.
9229     if (BId == Builtin::BIbzero ||
9230         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9231                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9232       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9233       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9234     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9235       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9236       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9237     }
9238     return;
9239   }
9240 
9241   // If the second argument to a memset is a sizeof expression and the third
9242   // isn't, this is also likely an error. This should catch
9243   // 'memset(buf, sizeof(buf), 0xff)'.
9244   if (BId == Builtin::BImemset &&
9245       doesExprLikelyComputeSize(Call->getArg(1)) &&
9246       !doesExprLikelyComputeSize(Call->getArg(2))) {
9247     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9248     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9249     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9250     return;
9251   }
9252 }
9253 
9254 /// Check for dangerous or invalid arguments to memset().
9255 ///
9256 /// This issues warnings on known problematic, dangerous or unspecified
9257 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9258 /// function calls.
9259 ///
9260 /// \param Call The call expression to diagnose.
9261 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9262                                    unsigned BId,
9263                                    IdentifierInfo *FnName) {
9264   assert(BId != 0);
9265 
9266   // It is possible to have a non-standard definition of memset.  Validate
9267   // we have enough arguments, and if not, abort further checking.
9268   unsigned ExpectedNumArgs =
9269       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9270   if (Call->getNumArgs() < ExpectedNumArgs)
9271     return;
9272 
9273   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9274                       BId == Builtin::BIstrndup ? 1 : 2);
9275   unsigned LenArg =
9276       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9277   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9278 
9279   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9280                                      Call->getBeginLoc(), Call->getRParenLoc()))
9281     return;
9282 
9283   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9284   CheckMemaccessSize(*this, BId, Call);
9285 
9286   // We have special checking when the length is a sizeof expression.
9287   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9288   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9289   llvm::FoldingSetNodeID SizeOfArgID;
9290 
9291   // Although widely used, 'bzero' is not a standard function. Be more strict
9292   // with the argument types before allowing diagnostics and only allow the
9293   // form bzero(ptr, sizeof(...)).
9294   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9295   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9296     return;
9297 
9298   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9299     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9300     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9301 
9302     QualType DestTy = Dest->getType();
9303     QualType PointeeTy;
9304     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9305       PointeeTy = DestPtrTy->getPointeeType();
9306 
9307       // Never warn about void type pointers. This can be used to suppress
9308       // false positives.
9309       if (PointeeTy->isVoidType())
9310         continue;
9311 
9312       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9313       // actually comparing the expressions for equality. Because computing the
9314       // expression IDs can be expensive, we only do this if the diagnostic is
9315       // enabled.
9316       if (SizeOfArg &&
9317           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9318                            SizeOfArg->getExprLoc())) {
9319         // We only compute IDs for expressions if the warning is enabled, and
9320         // cache the sizeof arg's ID.
9321         if (SizeOfArgID == llvm::FoldingSetNodeID())
9322           SizeOfArg->Profile(SizeOfArgID, Context, true);
9323         llvm::FoldingSetNodeID DestID;
9324         Dest->Profile(DestID, Context, true);
9325         if (DestID == SizeOfArgID) {
9326           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9327           //       over sizeof(src) as well.
9328           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9329           StringRef ReadableName = FnName->getName();
9330 
9331           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9332             if (UnaryOp->getOpcode() == UO_AddrOf)
9333               ActionIdx = 1; // If its an address-of operator, just remove it.
9334           if (!PointeeTy->isIncompleteType() &&
9335               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9336             ActionIdx = 2; // If the pointee's size is sizeof(char),
9337                            // suggest an explicit length.
9338 
9339           // If the function is defined as a builtin macro, do not show macro
9340           // expansion.
9341           SourceLocation SL = SizeOfArg->getExprLoc();
9342           SourceRange DSR = Dest->getSourceRange();
9343           SourceRange SSR = SizeOfArg->getSourceRange();
9344           SourceManager &SM = getSourceManager();
9345 
9346           if (SM.isMacroArgExpansion(SL)) {
9347             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9348             SL = SM.getSpellingLoc(SL);
9349             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9350                              SM.getSpellingLoc(DSR.getEnd()));
9351             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9352                              SM.getSpellingLoc(SSR.getEnd()));
9353           }
9354 
9355           DiagRuntimeBehavior(SL, SizeOfArg,
9356                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9357                                 << ReadableName
9358                                 << PointeeTy
9359                                 << DestTy
9360                                 << DSR
9361                                 << SSR);
9362           DiagRuntimeBehavior(SL, SizeOfArg,
9363                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9364                                 << ActionIdx
9365                                 << SSR);
9366 
9367           break;
9368         }
9369       }
9370 
9371       // Also check for cases where the sizeof argument is the exact same
9372       // type as the memory argument, and where it points to a user-defined
9373       // record type.
9374       if (SizeOfArgTy != QualType()) {
9375         if (PointeeTy->isRecordType() &&
9376             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9377           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9378                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9379                                 << FnName << SizeOfArgTy << ArgIdx
9380                                 << PointeeTy << Dest->getSourceRange()
9381                                 << LenExpr->getSourceRange());
9382           break;
9383         }
9384       }
9385     } else if (DestTy->isArrayType()) {
9386       PointeeTy = DestTy;
9387     }
9388 
9389     if (PointeeTy == QualType())
9390       continue;
9391 
9392     // Always complain about dynamic classes.
9393     bool IsContained;
9394     if (const CXXRecordDecl *ContainedRD =
9395             getContainedDynamicClass(PointeeTy, IsContained)) {
9396 
9397       unsigned OperationType = 0;
9398       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9399       // "overwritten" if we're warning about the destination for any call
9400       // but memcmp; otherwise a verb appropriate to the call.
9401       if (ArgIdx != 0 || IsCmp) {
9402         if (BId == Builtin::BImemcpy)
9403           OperationType = 1;
9404         else if(BId == Builtin::BImemmove)
9405           OperationType = 2;
9406         else if (IsCmp)
9407           OperationType = 3;
9408       }
9409 
9410       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9411                           PDiag(diag::warn_dyn_class_memaccess)
9412                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9413                               << IsContained << ContainedRD << OperationType
9414                               << Call->getCallee()->getSourceRange());
9415     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9416              BId != Builtin::BImemset)
9417       DiagRuntimeBehavior(
9418         Dest->getExprLoc(), Dest,
9419         PDiag(diag::warn_arc_object_memaccess)
9420           << ArgIdx << FnName << PointeeTy
9421           << Call->getCallee()->getSourceRange());
9422     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9423       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9424           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9425         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9426                             PDiag(diag::warn_cstruct_memaccess)
9427                                 << ArgIdx << FnName << PointeeTy << 0);
9428         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9429       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9430                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9431         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9432                             PDiag(diag::warn_cstruct_memaccess)
9433                                 << ArgIdx << FnName << PointeeTy << 1);
9434         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9435       } else {
9436         continue;
9437       }
9438     } else
9439       continue;
9440 
9441     DiagRuntimeBehavior(
9442       Dest->getExprLoc(), Dest,
9443       PDiag(diag::note_bad_memaccess_silence)
9444         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9445     break;
9446   }
9447 }
9448 
9449 // A little helper routine: ignore addition and subtraction of integer literals.
9450 // This intentionally does not ignore all integer constant expressions because
9451 // we don't want to remove sizeof().
9452 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9453   Ex = Ex->IgnoreParenCasts();
9454 
9455   while (true) {
9456     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9457     if (!BO || !BO->isAdditiveOp())
9458       break;
9459 
9460     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9461     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9462 
9463     if (isa<IntegerLiteral>(RHS))
9464       Ex = LHS;
9465     else if (isa<IntegerLiteral>(LHS))
9466       Ex = RHS;
9467     else
9468       break;
9469   }
9470 
9471   return Ex;
9472 }
9473 
9474 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9475                                                       ASTContext &Context) {
9476   // Only handle constant-sized or VLAs, but not flexible members.
9477   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9478     // Only issue the FIXIT for arrays of size > 1.
9479     if (CAT->getSize().getSExtValue() <= 1)
9480       return false;
9481   } else if (!Ty->isVariableArrayType()) {
9482     return false;
9483   }
9484   return true;
9485 }
9486 
9487 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9488 // be the size of the source, instead of the destination.
9489 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9490                                     IdentifierInfo *FnName) {
9491 
9492   // Don't crash if the user has the wrong number of arguments
9493   unsigned NumArgs = Call->getNumArgs();
9494   if ((NumArgs != 3) && (NumArgs != 4))
9495     return;
9496 
9497   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9498   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9499   const Expr *CompareWithSrc = nullptr;
9500 
9501   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9502                                      Call->getBeginLoc(), Call->getRParenLoc()))
9503     return;
9504 
9505   // Look for 'strlcpy(dst, x, sizeof(x))'
9506   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9507     CompareWithSrc = Ex;
9508   else {
9509     // Look for 'strlcpy(dst, x, strlen(x))'
9510     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9511       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9512           SizeCall->getNumArgs() == 1)
9513         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9514     }
9515   }
9516 
9517   if (!CompareWithSrc)
9518     return;
9519 
9520   // Determine if the argument to sizeof/strlen is equal to the source
9521   // argument.  In principle there's all kinds of things you could do
9522   // here, for instance creating an == expression and evaluating it with
9523   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9524   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9525   if (!SrcArgDRE)
9526     return;
9527 
9528   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9529   if (!CompareWithSrcDRE ||
9530       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9531     return;
9532 
9533   const Expr *OriginalSizeArg = Call->getArg(2);
9534   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9535       << OriginalSizeArg->getSourceRange() << FnName;
9536 
9537   // Output a FIXIT hint if the destination is an array (rather than a
9538   // pointer to an array).  This could be enhanced to handle some
9539   // pointers if we know the actual size, like if DstArg is 'array+2'
9540   // we could say 'sizeof(array)-2'.
9541   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9542   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9543     return;
9544 
9545   SmallString<128> sizeString;
9546   llvm::raw_svector_ostream OS(sizeString);
9547   OS << "sizeof(";
9548   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9549   OS << ")";
9550 
9551   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9552       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9553                                       OS.str());
9554 }
9555 
9556 /// Check if two expressions refer to the same declaration.
9557 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9558   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9559     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9560       return D1->getDecl() == D2->getDecl();
9561   return false;
9562 }
9563 
9564 static const Expr *getStrlenExprArg(const Expr *E) {
9565   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9566     const FunctionDecl *FD = CE->getDirectCallee();
9567     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9568       return nullptr;
9569     return CE->getArg(0)->IgnoreParenCasts();
9570   }
9571   return nullptr;
9572 }
9573 
9574 // Warn on anti-patterns as the 'size' argument to strncat.
9575 // The correct size argument should look like following:
9576 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9577 void Sema::CheckStrncatArguments(const CallExpr *CE,
9578                                  IdentifierInfo *FnName) {
9579   // Don't crash if the user has the wrong number of arguments.
9580   if (CE->getNumArgs() < 3)
9581     return;
9582   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9583   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9584   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9585 
9586   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9587                                      CE->getRParenLoc()))
9588     return;
9589 
9590   // Identify common expressions, which are wrongly used as the size argument
9591   // to strncat and may lead to buffer overflows.
9592   unsigned PatternType = 0;
9593   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9594     // - sizeof(dst)
9595     if (referToTheSameDecl(SizeOfArg, DstArg))
9596       PatternType = 1;
9597     // - sizeof(src)
9598     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9599       PatternType = 2;
9600   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9601     if (BE->getOpcode() == BO_Sub) {
9602       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9603       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9604       // - sizeof(dst) - strlen(dst)
9605       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9606           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9607         PatternType = 1;
9608       // - sizeof(src) - (anything)
9609       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9610         PatternType = 2;
9611     }
9612   }
9613 
9614   if (PatternType == 0)
9615     return;
9616 
9617   // Generate the diagnostic.
9618   SourceLocation SL = LenArg->getBeginLoc();
9619   SourceRange SR = LenArg->getSourceRange();
9620   SourceManager &SM = getSourceManager();
9621 
9622   // If the function is defined as a builtin macro, do not show macro expansion.
9623   if (SM.isMacroArgExpansion(SL)) {
9624     SL = SM.getSpellingLoc(SL);
9625     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9626                      SM.getSpellingLoc(SR.getEnd()));
9627   }
9628 
9629   // Check if the destination is an array (rather than a pointer to an array).
9630   QualType DstTy = DstArg->getType();
9631   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9632                                                                     Context);
9633   if (!isKnownSizeArray) {
9634     if (PatternType == 1)
9635       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9636     else
9637       Diag(SL, diag::warn_strncat_src_size) << SR;
9638     return;
9639   }
9640 
9641   if (PatternType == 1)
9642     Diag(SL, diag::warn_strncat_large_size) << SR;
9643   else
9644     Diag(SL, diag::warn_strncat_src_size) << SR;
9645 
9646   SmallString<128> sizeString;
9647   llvm::raw_svector_ostream OS(sizeString);
9648   OS << "sizeof(";
9649   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9650   OS << ") - ";
9651   OS << "strlen(";
9652   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9653   OS << ") - 1";
9654 
9655   Diag(SL, diag::note_strncat_wrong_size)
9656     << FixItHint::CreateReplacement(SR, OS.str());
9657 }
9658 
9659 void
9660 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9661                          SourceLocation ReturnLoc,
9662                          bool isObjCMethod,
9663                          const AttrVec *Attrs,
9664                          const FunctionDecl *FD) {
9665   // Check if the return value is null but should not be.
9666   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9667        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9668       CheckNonNullExpr(*this, RetValExp))
9669     Diag(ReturnLoc, diag::warn_null_ret)
9670       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9671 
9672   // C++11 [basic.stc.dynamic.allocation]p4:
9673   //   If an allocation function declared with a non-throwing
9674   //   exception-specification fails to allocate storage, it shall return
9675   //   a null pointer. Any other allocation function that fails to allocate
9676   //   storage shall indicate failure only by throwing an exception [...]
9677   if (FD) {
9678     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9679     if (Op == OO_New || Op == OO_Array_New) {
9680       const FunctionProtoType *Proto
9681         = FD->getType()->castAs<FunctionProtoType>();
9682       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9683           CheckNonNullExpr(*this, RetValExp))
9684         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9685           << FD << getLangOpts().CPlusPlus11;
9686     }
9687   }
9688 }
9689 
9690 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9691 
9692 /// Check for comparisons of floating point operands using != and ==.
9693 /// Issue a warning if these are no self-comparisons, as they are not likely
9694 /// to do what the programmer intended.
9695 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9696   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9697   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9698 
9699   // Special case: check for x == x (which is OK).
9700   // Do not emit warnings for such cases.
9701   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9702     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9703       if (DRL->getDecl() == DRR->getDecl())
9704         return;
9705 
9706   // Special case: check for comparisons against literals that can be exactly
9707   //  represented by APFloat.  In such cases, do not emit a warning.  This
9708   //  is a heuristic: often comparison against such literals are used to
9709   //  detect if a value in a variable has not changed.  This clearly can
9710   //  lead to false negatives.
9711   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9712     if (FLL->isExact())
9713       return;
9714   } else
9715     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9716       if (FLR->isExact())
9717         return;
9718 
9719   // Check for comparisons with builtin types.
9720   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9721     if (CL->getBuiltinCallee())
9722       return;
9723 
9724   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9725     if (CR->getBuiltinCallee())
9726       return;
9727 
9728   // Emit the diagnostic.
9729   Diag(Loc, diag::warn_floatingpoint_eq)
9730     << LHS->getSourceRange() << RHS->getSourceRange();
9731 }
9732 
9733 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9734 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9735 
9736 namespace {
9737 
9738 /// Structure recording the 'active' range of an integer-valued
9739 /// expression.
9740 struct IntRange {
9741   /// The number of bits active in the int.
9742   unsigned Width;
9743 
9744   /// True if the int is known not to have negative values.
9745   bool NonNegative;
9746 
9747   IntRange(unsigned Width, bool NonNegative)
9748       : Width(Width), NonNegative(NonNegative) {}
9749 
9750   /// Returns the range of the bool type.
9751   static IntRange forBoolType() {
9752     return IntRange(1, true);
9753   }
9754 
9755   /// Returns the range of an opaque value of the given integral type.
9756   static IntRange forValueOfType(ASTContext &C, QualType T) {
9757     return forValueOfCanonicalType(C,
9758                           T->getCanonicalTypeInternal().getTypePtr());
9759   }
9760 
9761   /// Returns the range of an opaque value of a canonical integral type.
9762   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9763     assert(T->isCanonicalUnqualified());
9764 
9765     if (const VectorType *VT = dyn_cast<VectorType>(T))
9766       T = VT->getElementType().getTypePtr();
9767     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9768       T = CT->getElementType().getTypePtr();
9769     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9770       T = AT->getValueType().getTypePtr();
9771 
9772     if (!C.getLangOpts().CPlusPlus) {
9773       // For enum types in C code, use the underlying datatype.
9774       if (const EnumType *ET = dyn_cast<EnumType>(T))
9775         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9776     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9777       // For enum types in C++, use the known bit width of the enumerators.
9778       EnumDecl *Enum = ET->getDecl();
9779       // In C++11, enums can have a fixed underlying type. Use this type to
9780       // compute the range.
9781       if (Enum->isFixed()) {
9782         return IntRange(C.getIntWidth(QualType(T, 0)),
9783                         !ET->isSignedIntegerOrEnumerationType());
9784       }
9785 
9786       unsigned NumPositive = Enum->getNumPositiveBits();
9787       unsigned NumNegative = Enum->getNumNegativeBits();
9788 
9789       if (NumNegative == 0)
9790         return IntRange(NumPositive, true/*NonNegative*/);
9791       else
9792         return IntRange(std::max(NumPositive + 1, NumNegative),
9793                         false/*NonNegative*/);
9794     }
9795 
9796     const BuiltinType *BT = cast<BuiltinType>(T);
9797     assert(BT->isInteger());
9798 
9799     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9800   }
9801 
9802   /// Returns the "target" range of a canonical integral type, i.e.
9803   /// the range of values expressible in the type.
9804   ///
9805   /// This matches forValueOfCanonicalType except that enums have the
9806   /// full range of their type, not the range of their enumerators.
9807   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9808     assert(T->isCanonicalUnqualified());
9809 
9810     if (const VectorType *VT = dyn_cast<VectorType>(T))
9811       T = VT->getElementType().getTypePtr();
9812     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9813       T = CT->getElementType().getTypePtr();
9814     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9815       T = AT->getValueType().getTypePtr();
9816     if (const EnumType *ET = dyn_cast<EnumType>(T))
9817       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9818 
9819     const BuiltinType *BT = cast<BuiltinType>(T);
9820     assert(BT->isInteger());
9821 
9822     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9823   }
9824 
9825   /// Returns the supremum of two ranges: i.e. their conservative merge.
9826   static IntRange join(IntRange L, IntRange R) {
9827     return IntRange(std::max(L.Width, R.Width),
9828                     L.NonNegative && R.NonNegative);
9829   }
9830 
9831   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9832   static IntRange meet(IntRange L, IntRange R) {
9833     return IntRange(std::min(L.Width, R.Width),
9834                     L.NonNegative || R.NonNegative);
9835   }
9836 };
9837 
9838 } // namespace
9839 
9840 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9841                               unsigned MaxWidth) {
9842   if (value.isSigned() && value.isNegative())
9843     return IntRange(value.getMinSignedBits(), false);
9844 
9845   if (value.getBitWidth() > MaxWidth)
9846     value = value.trunc(MaxWidth);
9847 
9848   // isNonNegative() just checks the sign bit without considering
9849   // signedness.
9850   return IntRange(value.getActiveBits(), true);
9851 }
9852 
9853 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9854                               unsigned MaxWidth) {
9855   if (result.isInt())
9856     return GetValueRange(C, result.getInt(), MaxWidth);
9857 
9858   if (result.isVector()) {
9859     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9860     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9861       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9862       R = IntRange::join(R, El);
9863     }
9864     return R;
9865   }
9866 
9867   if (result.isComplexInt()) {
9868     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9869     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9870     return IntRange::join(R, I);
9871   }
9872 
9873   // This can happen with lossless casts to intptr_t of "based" lvalues.
9874   // Assume it might use arbitrary bits.
9875   // FIXME: The only reason we need to pass the type in here is to get
9876   // the sign right on this one case.  It would be nice if APValue
9877   // preserved this.
9878   assert(result.isLValue() || result.isAddrLabelDiff());
9879   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9880 }
9881 
9882 static QualType GetExprType(const Expr *E) {
9883   QualType Ty = E->getType();
9884   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9885     Ty = AtomicRHS->getValueType();
9886   return Ty;
9887 }
9888 
9889 /// Pseudo-evaluate the given integer expression, estimating the
9890 /// range of values it might take.
9891 ///
9892 /// \param MaxWidth - the width to which the value will be truncated
9893 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
9894                              bool InConstantContext) {
9895   E = E->IgnoreParens();
9896 
9897   // Try a full evaluation first.
9898   Expr::EvalResult result;
9899   if (E->EvaluateAsRValue(result, C, InConstantContext))
9900     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9901 
9902   // I think we only want to look through implicit casts here; if the
9903   // user has an explicit widening cast, we should treat the value as
9904   // being of the new, wider type.
9905   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9906     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9907       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
9908 
9909     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9910 
9911     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9912                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9913 
9914     // Assume that non-integer casts can span the full range of the type.
9915     if (!isIntegerCast)
9916       return OutputTypeRange;
9917 
9918     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
9919                                      std::min(MaxWidth, OutputTypeRange.Width),
9920                                      InConstantContext);
9921 
9922     // Bail out if the subexpr's range is as wide as the cast type.
9923     if (SubRange.Width >= OutputTypeRange.Width)
9924       return OutputTypeRange;
9925 
9926     // Otherwise, we take the smaller width, and we're non-negative if
9927     // either the output type or the subexpr is.
9928     return IntRange(SubRange.Width,
9929                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9930   }
9931 
9932   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9933     // If we can fold the condition, just take that operand.
9934     bool CondResult;
9935     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9936       return GetExprRange(C,
9937                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
9938                           MaxWidth, InConstantContext);
9939 
9940     // Otherwise, conservatively merge.
9941     IntRange L =
9942         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
9943     IntRange R =
9944         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
9945     return IntRange::join(L, R);
9946   }
9947 
9948   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9949     switch (BO->getOpcode()) {
9950     case BO_Cmp:
9951       llvm_unreachable("builtin <=> should have class type");
9952 
9953     // Boolean-valued operations are single-bit and positive.
9954     case BO_LAnd:
9955     case BO_LOr:
9956     case BO_LT:
9957     case BO_GT:
9958     case BO_LE:
9959     case BO_GE:
9960     case BO_EQ:
9961     case BO_NE:
9962       return IntRange::forBoolType();
9963 
9964     // The type of the assignments is the type of the LHS, so the RHS
9965     // is not necessarily the same type.
9966     case BO_MulAssign:
9967     case BO_DivAssign:
9968     case BO_RemAssign:
9969     case BO_AddAssign:
9970     case BO_SubAssign:
9971     case BO_XorAssign:
9972     case BO_OrAssign:
9973       // TODO: bitfields?
9974       return IntRange::forValueOfType(C, GetExprType(E));
9975 
9976     // Simple assignments just pass through the RHS, which will have
9977     // been coerced to the LHS type.
9978     case BO_Assign:
9979       // TODO: bitfields?
9980       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
9981 
9982     // Operations with opaque sources are black-listed.
9983     case BO_PtrMemD:
9984     case BO_PtrMemI:
9985       return IntRange::forValueOfType(C, GetExprType(E));
9986 
9987     // Bitwise-and uses the *infinum* of the two source ranges.
9988     case BO_And:
9989     case BO_AndAssign:
9990       return IntRange::meet(
9991           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
9992           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
9993 
9994     // Left shift gets black-listed based on a judgement call.
9995     case BO_Shl:
9996       // ...except that we want to treat '1 << (blah)' as logically
9997       // positive.  It's an important idiom.
9998       if (IntegerLiteral *I
9999             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10000         if (I->getValue() == 1) {
10001           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10002           return IntRange(R.Width, /*NonNegative*/ true);
10003         }
10004       }
10005       LLVM_FALLTHROUGH;
10006 
10007     case BO_ShlAssign:
10008       return IntRange::forValueOfType(C, GetExprType(E));
10009 
10010     // Right shift by a constant can narrow its left argument.
10011     case BO_Shr:
10012     case BO_ShrAssign: {
10013       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10014 
10015       // If the shift amount is a positive constant, drop the width by
10016       // that much.
10017       llvm::APSInt shift;
10018       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10019           shift.isNonNegative()) {
10020         unsigned zext = shift.getZExtValue();
10021         if (zext >= L.Width)
10022           L.Width = (L.NonNegative ? 0 : 1);
10023         else
10024           L.Width -= zext;
10025       }
10026 
10027       return L;
10028     }
10029 
10030     // Comma acts as its right operand.
10031     case BO_Comma:
10032       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10033 
10034     // Black-list pointer subtractions.
10035     case BO_Sub:
10036       if (BO->getLHS()->getType()->isPointerType())
10037         return IntRange::forValueOfType(C, GetExprType(E));
10038       break;
10039 
10040     // The width of a division result is mostly determined by the size
10041     // of the LHS.
10042     case BO_Div: {
10043       // Don't 'pre-truncate' the operands.
10044       unsigned opWidth = C.getIntWidth(GetExprType(E));
10045       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10046 
10047       // If the divisor is constant, use that.
10048       llvm::APSInt divisor;
10049       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10050         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10051         if (log2 >= L.Width)
10052           L.Width = (L.NonNegative ? 0 : 1);
10053         else
10054           L.Width = std::min(L.Width - log2, MaxWidth);
10055         return L;
10056       }
10057 
10058       // Otherwise, just use the LHS's width.
10059       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10060       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10061     }
10062 
10063     // The result of a remainder can't be larger than the result of
10064     // either side.
10065     case BO_Rem: {
10066       // Don't 'pre-truncate' the operands.
10067       unsigned opWidth = C.getIntWidth(GetExprType(E));
10068       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10069       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10070 
10071       IntRange meet = IntRange::meet(L, R);
10072       meet.Width = std::min(meet.Width, MaxWidth);
10073       return meet;
10074     }
10075 
10076     // The default behavior is okay for these.
10077     case BO_Mul:
10078     case BO_Add:
10079     case BO_Xor:
10080     case BO_Or:
10081       break;
10082     }
10083 
10084     // The default case is to treat the operation as if it were closed
10085     // on the narrowest type that encompasses both operands.
10086     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10087     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10088     return IntRange::join(L, R);
10089   }
10090 
10091   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10092     switch (UO->getOpcode()) {
10093     // Boolean-valued operations are white-listed.
10094     case UO_LNot:
10095       return IntRange::forBoolType();
10096 
10097     // Operations with opaque sources are black-listed.
10098     case UO_Deref:
10099     case UO_AddrOf: // should be impossible
10100       return IntRange::forValueOfType(C, GetExprType(E));
10101 
10102     default:
10103       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10104     }
10105   }
10106 
10107   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10108     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10109 
10110   if (const auto *BitField = E->getSourceBitField())
10111     return IntRange(BitField->getBitWidthValue(C),
10112                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10113 
10114   return IntRange::forValueOfType(C, GetExprType(E));
10115 }
10116 
10117 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10118                              bool InConstantContext) {
10119   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10120 }
10121 
10122 /// Checks whether the given value, which currently has the given
10123 /// source semantics, has the same value when coerced through the
10124 /// target semantics.
10125 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10126                                  const llvm::fltSemantics &Src,
10127                                  const llvm::fltSemantics &Tgt) {
10128   llvm::APFloat truncated = value;
10129 
10130   bool ignored;
10131   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10132   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10133 
10134   return truncated.bitwiseIsEqual(value);
10135 }
10136 
10137 /// Checks whether the given value, which currently has the given
10138 /// source semantics, has the same value when coerced through the
10139 /// target semantics.
10140 ///
10141 /// The value might be a vector of floats (or a complex number).
10142 static bool IsSameFloatAfterCast(const APValue &value,
10143                                  const llvm::fltSemantics &Src,
10144                                  const llvm::fltSemantics &Tgt) {
10145   if (value.isFloat())
10146     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10147 
10148   if (value.isVector()) {
10149     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10150       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10151         return false;
10152     return true;
10153   }
10154 
10155   assert(value.isComplexFloat());
10156   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10157           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10158 }
10159 
10160 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10161                                        bool IsListInit = false);
10162 
10163 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10164   // Suppress cases where we are comparing against an enum constant.
10165   if (const DeclRefExpr *DR =
10166       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10167     if (isa<EnumConstantDecl>(DR->getDecl()))
10168       return true;
10169 
10170   // Suppress cases where the value is expanded from a macro, unless that macro
10171   // is how a language represents a boolean literal. This is the case in both C
10172   // and Objective-C.
10173   SourceLocation BeginLoc = E->getBeginLoc();
10174   if (BeginLoc.isMacroID()) {
10175     StringRef MacroName = Lexer::getImmediateMacroName(
10176         BeginLoc, S.getSourceManager(), S.getLangOpts());
10177     return MacroName != "YES" && MacroName != "NO" &&
10178            MacroName != "true" && MacroName != "false";
10179   }
10180 
10181   return false;
10182 }
10183 
10184 static bool isKnownToHaveUnsignedValue(Expr *E) {
10185   return E->getType()->isIntegerType() &&
10186          (!E->getType()->isSignedIntegerType() ||
10187           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10188 }
10189 
10190 namespace {
10191 /// The promoted range of values of a type. In general this has the
10192 /// following structure:
10193 ///
10194 ///     |-----------| . . . |-----------|
10195 ///     ^           ^       ^           ^
10196 ///    Min       HoleMin  HoleMax      Max
10197 ///
10198 /// ... where there is only a hole if a signed type is promoted to unsigned
10199 /// (in which case Min and Max are the smallest and largest representable
10200 /// values).
10201 struct PromotedRange {
10202   // Min, or HoleMax if there is a hole.
10203   llvm::APSInt PromotedMin;
10204   // Max, or HoleMin if there is a hole.
10205   llvm::APSInt PromotedMax;
10206 
10207   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10208     if (R.Width == 0)
10209       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10210     else if (R.Width >= BitWidth && !Unsigned) {
10211       // Promotion made the type *narrower*. This happens when promoting
10212       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10213       // Treat all values of 'signed int' as being in range for now.
10214       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10215       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10216     } else {
10217       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10218                         .extOrTrunc(BitWidth);
10219       PromotedMin.setIsUnsigned(Unsigned);
10220 
10221       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10222                         .extOrTrunc(BitWidth);
10223       PromotedMax.setIsUnsigned(Unsigned);
10224     }
10225   }
10226 
10227   // Determine whether this range is contiguous (has no hole).
10228   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10229 
10230   // Where a constant value is within the range.
10231   enum ComparisonResult {
10232     LT = 0x1,
10233     LE = 0x2,
10234     GT = 0x4,
10235     GE = 0x8,
10236     EQ = 0x10,
10237     NE = 0x20,
10238     InRangeFlag = 0x40,
10239 
10240     Less = LE | LT | NE,
10241     Min = LE | InRangeFlag,
10242     InRange = InRangeFlag,
10243     Max = GE | InRangeFlag,
10244     Greater = GE | GT | NE,
10245 
10246     OnlyValue = LE | GE | EQ | InRangeFlag,
10247     InHole = NE
10248   };
10249 
10250   ComparisonResult compare(const llvm::APSInt &Value) const {
10251     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10252            Value.isUnsigned() == PromotedMin.isUnsigned());
10253     if (!isContiguous()) {
10254       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10255       if (Value.isMinValue()) return Min;
10256       if (Value.isMaxValue()) return Max;
10257       if (Value >= PromotedMin) return InRange;
10258       if (Value <= PromotedMax) return InRange;
10259       return InHole;
10260     }
10261 
10262     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10263     case -1: return Less;
10264     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10265     case 1:
10266       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10267       case -1: return InRange;
10268       case 0: return Max;
10269       case 1: return Greater;
10270       }
10271     }
10272 
10273     llvm_unreachable("impossible compare result");
10274   }
10275 
10276   static llvm::Optional<StringRef>
10277   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10278     if (Op == BO_Cmp) {
10279       ComparisonResult LTFlag = LT, GTFlag = GT;
10280       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10281 
10282       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10283       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10284       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10285       return llvm::None;
10286     }
10287 
10288     ComparisonResult TrueFlag, FalseFlag;
10289     if (Op == BO_EQ) {
10290       TrueFlag = EQ;
10291       FalseFlag = NE;
10292     } else if (Op == BO_NE) {
10293       TrueFlag = NE;
10294       FalseFlag = EQ;
10295     } else {
10296       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10297         TrueFlag = LT;
10298         FalseFlag = GE;
10299       } else {
10300         TrueFlag = GT;
10301         FalseFlag = LE;
10302       }
10303       if (Op == BO_GE || Op == BO_LE)
10304         std::swap(TrueFlag, FalseFlag);
10305     }
10306     if (R & TrueFlag)
10307       return StringRef("true");
10308     if (R & FalseFlag)
10309       return StringRef("false");
10310     return llvm::None;
10311   }
10312 };
10313 }
10314 
10315 static bool HasEnumType(Expr *E) {
10316   // Strip off implicit integral promotions.
10317   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10318     if (ICE->getCastKind() != CK_IntegralCast &&
10319         ICE->getCastKind() != CK_NoOp)
10320       break;
10321     E = ICE->getSubExpr();
10322   }
10323 
10324   return E->getType()->isEnumeralType();
10325 }
10326 
10327 static int classifyConstantValue(Expr *Constant) {
10328   // The values of this enumeration are used in the diagnostics
10329   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10330   enum ConstantValueKind {
10331     Miscellaneous = 0,
10332     LiteralTrue,
10333     LiteralFalse
10334   };
10335   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10336     return BL->getValue() ? ConstantValueKind::LiteralTrue
10337                           : ConstantValueKind::LiteralFalse;
10338   return ConstantValueKind::Miscellaneous;
10339 }
10340 
10341 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10342                                         Expr *Constant, Expr *Other,
10343                                         const llvm::APSInt &Value,
10344                                         bool RhsConstant) {
10345   if (S.inTemplateInstantiation())
10346     return false;
10347 
10348   Expr *OriginalOther = Other;
10349 
10350   Constant = Constant->IgnoreParenImpCasts();
10351   Other = Other->IgnoreParenImpCasts();
10352 
10353   // Suppress warnings on tautological comparisons between values of the same
10354   // enumeration type. There are only two ways we could warn on this:
10355   //  - If the constant is outside the range of representable values of
10356   //    the enumeration. In such a case, we should warn about the cast
10357   //    to enumeration type, not about the comparison.
10358   //  - If the constant is the maximum / minimum in-range value. For an
10359   //    enumeratin type, such comparisons can be meaningful and useful.
10360   if (Constant->getType()->isEnumeralType() &&
10361       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10362     return false;
10363 
10364   // TODO: Investigate using GetExprRange() to get tighter bounds
10365   // on the bit ranges.
10366   QualType OtherT = Other->getType();
10367   if (const auto *AT = OtherT->getAs<AtomicType>())
10368     OtherT = AT->getValueType();
10369   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10370 
10371   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10372   // (Namely, macOS).
10373   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10374                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10375                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10376 
10377   // Whether we're treating Other as being a bool because of the form of
10378   // expression despite it having another type (typically 'int' in C).
10379   bool OtherIsBooleanDespiteType =
10380       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10381   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10382     OtherRange = IntRange::forBoolType();
10383 
10384   // Determine the promoted range of the other type and see if a comparison of
10385   // the constant against that range is tautological.
10386   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10387                                    Value.isUnsigned());
10388   auto Cmp = OtherPromotedRange.compare(Value);
10389   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10390   if (!Result)
10391     return false;
10392 
10393   // Suppress the diagnostic for an in-range comparison if the constant comes
10394   // from a macro or enumerator. We don't want to diagnose
10395   //
10396   //   some_long_value <= INT_MAX
10397   //
10398   // when sizeof(int) == sizeof(long).
10399   bool InRange = Cmp & PromotedRange::InRangeFlag;
10400   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10401     return false;
10402 
10403   // If this is a comparison to an enum constant, include that
10404   // constant in the diagnostic.
10405   const EnumConstantDecl *ED = nullptr;
10406   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10407     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10408 
10409   // Should be enough for uint128 (39 decimal digits)
10410   SmallString<64> PrettySourceValue;
10411   llvm::raw_svector_ostream OS(PrettySourceValue);
10412   if (ED) {
10413     OS << '\'' << *ED << "' (" << Value << ")";
10414   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10415                Constant->IgnoreParenImpCasts())) {
10416     OS << (BL->getValue() ? "YES" : "NO");
10417   } else {
10418     OS << Value;
10419   }
10420 
10421   if (IsObjCSignedCharBool) {
10422     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10423                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10424                               << OS.str() << *Result);
10425     return true;
10426   }
10427 
10428   // FIXME: We use a somewhat different formatting for the in-range cases and
10429   // cases involving boolean values for historical reasons. We should pick a
10430   // consistent way of presenting these diagnostics.
10431   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10432 
10433     S.DiagRuntimeBehavior(
10434         E->getOperatorLoc(), E,
10435         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10436                          : diag::warn_tautological_bool_compare)
10437             << OS.str() << classifyConstantValue(Constant) << OtherT
10438             << OtherIsBooleanDespiteType << *Result
10439             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10440   } else {
10441     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10442                         ? (HasEnumType(OriginalOther)
10443                                ? diag::warn_unsigned_enum_always_true_comparison
10444                                : diag::warn_unsigned_always_true_comparison)
10445                         : diag::warn_tautological_constant_compare;
10446 
10447     S.Diag(E->getOperatorLoc(), Diag)
10448         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10449         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10450   }
10451 
10452   return true;
10453 }
10454 
10455 /// Analyze the operands of the given comparison.  Implements the
10456 /// fallback case from AnalyzeComparison.
10457 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10458   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10459   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10460 }
10461 
10462 /// Implements -Wsign-compare.
10463 ///
10464 /// \param E the binary operator to check for warnings
10465 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10466   // The type the comparison is being performed in.
10467   QualType T = E->getLHS()->getType();
10468 
10469   // Only analyze comparison operators where both sides have been converted to
10470   // the same type.
10471   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10472     return AnalyzeImpConvsInComparison(S, E);
10473 
10474   // Don't analyze value-dependent comparisons directly.
10475   if (E->isValueDependent())
10476     return AnalyzeImpConvsInComparison(S, E);
10477 
10478   Expr *LHS = E->getLHS();
10479   Expr *RHS = E->getRHS();
10480 
10481   if (T->isIntegralType(S.Context)) {
10482     llvm::APSInt RHSValue;
10483     llvm::APSInt LHSValue;
10484 
10485     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10486     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10487 
10488     // We don't care about expressions whose result is a constant.
10489     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10490       return AnalyzeImpConvsInComparison(S, E);
10491 
10492     // We only care about expressions where just one side is literal
10493     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10494       // Is the constant on the RHS or LHS?
10495       const bool RhsConstant = IsRHSIntegralLiteral;
10496       Expr *Const = RhsConstant ? RHS : LHS;
10497       Expr *Other = RhsConstant ? LHS : RHS;
10498       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10499 
10500       // Check whether an integer constant comparison results in a value
10501       // of 'true' or 'false'.
10502       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10503         return AnalyzeImpConvsInComparison(S, E);
10504     }
10505   }
10506 
10507   if (!T->hasUnsignedIntegerRepresentation()) {
10508     // We don't do anything special if this isn't an unsigned integral
10509     // comparison:  we're only interested in integral comparisons, and
10510     // signed comparisons only happen in cases we don't care to warn about.
10511     return AnalyzeImpConvsInComparison(S, E);
10512   }
10513 
10514   LHS = LHS->IgnoreParenImpCasts();
10515   RHS = RHS->IgnoreParenImpCasts();
10516 
10517   if (!S.getLangOpts().CPlusPlus) {
10518     // Avoid warning about comparison of integers with different signs when
10519     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10520     // the type of `E`.
10521     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10522       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10523     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10524       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10525   }
10526 
10527   // Check to see if one of the (unmodified) operands is of different
10528   // signedness.
10529   Expr *signedOperand, *unsignedOperand;
10530   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10531     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10532            "unsigned comparison between two signed integer expressions?");
10533     signedOperand = LHS;
10534     unsignedOperand = RHS;
10535   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10536     signedOperand = RHS;
10537     unsignedOperand = LHS;
10538   } else {
10539     return AnalyzeImpConvsInComparison(S, E);
10540   }
10541 
10542   // Otherwise, calculate the effective range of the signed operand.
10543   IntRange signedRange =
10544       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10545 
10546   // Go ahead and analyze implicit conversions in the operands.  Note
10547   // that we skip the implicit conversions on both sides.
10548   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10549   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10550 
10551   // If the signed range is non-negative, -Wsign-compare won't fire.
10552   if (signedRange.NonNegative)
10553     return;
10554 
10555   // For (in)equality comparisons, if the unsigned operand is a
10556   // constant which cannot collide with a overflowed signed operand,
10557   // then reinterpreting the signed operand as unsigned will not
10558   // change the result of the comparison.
10559   if (E->isEqualityOp()) {
10560     unsigned comparisonWidth = S.Context.getIntWidth(T);
10561     IntRange unsignedRange =
10562         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10563 
10564     // We should never be unable to prove that the unsigned operand is
10565     // non-negative.
10566     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10567 
10568     if (unsignedRange.Width < comparisonWidth)
10569       return;
10570   }
10571 
10572   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10573                         S.PDiag(diag::warn_mixed_sign_comparison)
10574                             << LHS->getType() << RHS->getType()
10575                             << LHS->getSourceRange() << RHS->getSourceRange());
10576 }
10577 
10578 /// Analyzes an attempt to assign the given value to a bitfield.
10579 ///
10580 /// Returns true if there was something fishy about the attempt.
10581 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10582                                       SourceLocation InitLoc) {
10583   assert(Bitfield->isBitField());
10584   if (Bitfield->isInvalidDecl())
10585     return false;
10586 
10587   // White-list bool bitfields.
10588   QualType BitfieldType = Bitfield->getType();
10589   if (BitfieldType->isBooleanType())
10590      return false;
10591 
10592   if (BitfieldType->isEnumeralType()) {
10593     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10594     // If the underlying enum type was not explicitly specified as an unsigned
10595     // type and the enum contain only positive values, MSVC++ will cause an
10596     // inconsistency by storing this as a signed type.
10597     if (S.getLangOpts().CPlusPlus11 &&
10598         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10599         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10600         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10601       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10602         << BitfieldEnumDecl->getNameAsString();
10603     }
10604   }
10605 
10606   if (Bitfield->getType()->isBooleanType())
10607     return false;
10608 
10609   // Ignore value- or type-dependent expressions.
10610   if (Bitfield->getBitWidth()->isValueDependent() ||
10611       Bitfield->getBitWidth()->isTypeDependent() ||
10612       Init->isValueDependent() ||
10613       Init->isTypeDependent())
10614     return false;
10615 
10616   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10617   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10618 
10619   Expr::EvalResult Result;
10620   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10621                                    Expr::SE_AllowSideEffects)) {
10622     // The RHS is not constant.  If the RHS has an enum type, make sure the
10623     // bitfield is wide enough to hold all the values of the enum without
10624     // truncation.
10625     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10626       EnumDecl *ED = EnumTy->getDecl();
10627       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10628 
10629       // Enum types are implicitly signed on Windows, so check if there are any
10630       // negative enumerators to see if the enum was intended to be signed or
10631       // not.
10632       bool SignedEnum = ED->getNumNegativeBits() > 0;
10633 
10634       // Check for surprising sign changes when assigning enum values to a
10635       // bitfield of different signedness.  If the bitfield is signed and we
10636       // have exactly the right number of bits to store this unsigned enum,
10637       // suggest changing the enum to an unsigned type. This typically happens
10638       // on Windows where unfixed enums always use an underlying type of 'int'.
10639       unsigned DiagID = 0;
10640       if (SignedEnum && !SignedBitfield) {
10641         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10642       } else if (SignedBitfield && !SignedEnum &&
10643                  ED->getNumPositiveBits() == FieldWidth) {
10644         DiagID = diag::warn_signed_bitfield_enum_conversion;
10645       }
10646 
10647       if (DiagID) {
10648         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10649         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10650         SourceRange TypeRange =
10651             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10652         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10653             << SignedEnum << TypeRange;
10654       }
10655 
10656       // Compute the required bitwidth. If the enum has negative values, we need
10657       // one more bit than the normal number of positive bits to represent the
10658       // sign bit.
10659       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10660                                                   ED->getNumNegativeBits())
10661                                        : ED->getNumPositiveBits();
10662 
10663       // Check the bitwidth.
10664       if (BitsNeeded > FieldWidth) {
10665         Expr *WidthExpr = Bitfield->getBitWidth();
10666         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10667             << Bitfield << ED;
10668         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10669             << BitsNeeded << ED << WidthExpr->getSourceRange();
10670       }
10671     }
10672 
10673     return false;
10674   }
10675 
10676   llvm::APSInt Value = Result.Val.getInt();
10677 
10678   unsigned OriginalWidth = Value.getBitWidth();
10679 
10680   if (!Value.isSigned() || Value.isNegative())
10681     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10682       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10683         OriginalWidth = Value.getMinSignedBits();
10684 
10685   if (OriginalWidth <= FieldWidth)
10686     return false;
10687 
10688   // Compute the value which the bitfield will contain.
10689   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10690   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10691 
10692   // Check whether the stored value is equal to the original value.
10693   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10694   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10695     return false;
10696 
10697   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10698   // therefore don't strictly fit into a signed bitfield of width 1.
10699   if (FieldWidth == 1 && Value == 1)
10700     return false;
10701 
10702   std::string PrettyValue = Value.toString(10);
10703   std::string PrettyTrunc = TruncatedValue.toString(10);
10704 
10705   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10706     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10707     << Init->getSourceRange();
10708 
10709   return true;
10710 }
10711 
10712 /// Analyze the given simple or compound assignment for warning-worthy
10713 /// operations.
10714 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10715   // Just recurse on the LHS.
10716   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10717 
10718   // We want to recurse on the RHS as normal unless we're assigning to
10719   // a bitfield.
10720   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10721     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10722                                   E->getOperatorLoc())) {
10723       // Recurse, ignoring any implicit conversions on the RHS.
10724       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10725                                         E->getOperatorLoc());
10726     }
10727   }
10728 
10729   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10730 
10731   // Diagnose implicitly sequentially-consistent atomic assignment.
10732   if (E->getLHS()->getType()->isAtomicType())
10733     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10734 }
10735 
10736 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10737 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10738                             SourceLocation CContext, unsigned diag,
10739                             bool pruneControlFlow = false) {
10740   if (pruneControlFlow) {
10741     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10742                           S.PDiag(diag)
10743                               << SourceType << T << E->getSourceRange()
10744                               << SourceRange(CContext));
10745     return;
10746   }
10747   S.Diag(E->getExprLoc(), diag)
10748     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10749 }
10750 
10751 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10752 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10753                             SourceLocation CContext,
10754                             unsigned diag, bool pruneControlFlow = false) {
10755   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10756 }
10757 
10758 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10759   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10760       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10761 }
10762 
10763 static void adornObjCBoolConversionDiagWithTernaryFixit(
10764     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10765   Expr *Ignored = SourceExpr->IgnoreImplicit();
10766   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10767     Ignored = OVE->getSourceExpr();
10768   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10769                      isa<BinaryOperator>(Ignored) ||
10770                      isa<CXXOperatorCallExpr>(Ignored);
10771   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10772   if (NeedsParens)
10773     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10774             << FixItHint::CreateInsertion(EndLoc, ")");
10775   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10776 }
10777 
10778 /// Diagnose an implicit cast from a floating point value to an integer value.
10779 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10780                                     SourceLocation CContext) {
10781   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10782   const bool PruneWarnings = S.inTemplateInstantiation();
10783 
10784   Expr *InnerE = E->IgnoreParenImpCasts();
10785   // We also want to warn on, e.g., "int i = -1.234"
10786   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10787     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10788       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10789 
10790   const bool IsLiteral =
10791       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10792 
10793   llvm::APFloat Value(0.0);
10794   bool IsConstant =
10795     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10796   if (!IsConstant) {
10797     if (isObjCSignedCharBool(S, T)) {
10798       return adornObjCBoolConversionDiagWithTernaryFixit(
10799           S, E,
10800           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10801               << E->getType());
10802     }
10803 
10804     return DiagnoseImpCast(S, E, T, CContext,
10805                            diag::warn_impcast_float_integer, PruneWarnings);
10806   }
10807 
10808   bool isExact = false;
10809 
10810   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10811                             T->hasUnsignedIntegerRepresentation());
10812   llvm::APFloat::opStatus Result = Value.convertToInteger(
10813       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10814 
10815   // FIXME: Force the precision of the source value down so we don't print
10816   // digits which are usually useless (we don't really care here if we
10817   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10818   // would automatically print the shortest representation, but it's a bit
10819   // tricky to implement.
10820   SmallString<16> PrettySourceValue;
10821   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10822   precision = (precision * 59 + 195) / 196;
10823   Value.toString(PrettySourceValue, precision);
10824 
10825   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10826     return adornObjCBoolConversionDiagWithTernaryFixit(
10827         S, E,
10828         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10829             << PrettySourceValue);
10830   }
10831 
10832   if (Result == llvm::APFloat::opOK && isExact) {
10833     if (IsLiteral) return;
10834     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10835                            PruneWarnings);
10836   }
10837 
10838   // Conversion of a floating-point value to a non-bool integer where the
10839   // integral part cannot be represented by the integer type is undefined.
10840   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10841     return DiagnoseImpCast(
10842         S, E, T, CContext,
10843         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10844                   : diag::warn_impcast_float_to_integer_out_of_range,
10845         PruneWarnings);
10846 
10847   unsigned DiagID = 0;
10848   if (IsLiteral) {
10849     // Warn on floating point literal to integer.
10850     DiagID = diag::warn_impcast_literal_float_to_integer;
10851   } else if (IntegerValue == 0) {
10852     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10853       return DiagnoseImpCast(S, E, T, CContext,
10854                              diag::warn_impcast_float_integer, PruneWarnings);
10855     }
10856     // Warn on non-zero to zero conversion.
10857     DiagID = diag::warn_impcast_float_to_integer_zero;
10858   } else {
10859     if (IntegerValue.isUnsigned()) {
10860       if (!IntegerValue.isMaxValue()) {
10861         return DiagnoseImpCast(S, E, T, CContext,
10862                                diag::warn_impcast_float_integer, PruneWarnings);
10863       }
10864     } else {  // IntegerValue.isSigned()
10865       if (!IntegerValue.isMaxSignedValue() &&
10866           !IntegerValue.isMinSignedValue()) {
10867         return DiagnoseImpCast(S, E, T, CContext,
10868                                diag::warn_impcast_float_integer, PruneWarnings);
10869       }
10870     }
10871     // Warn on evaluatable floating point expression to integer conversion.
10872     DiagID = diag::warn_impcast_float_to_integer;
10873   }
10874 
10875   SmallString<16> PrettyTargetValue;
10876   if (IsBool)
10877     PrettyTargetValue = Value.isZero() ? "false" : "true";
10878   else
10879     IntegerValue.toString(PrettyTargetValue);
10880 
10881   if (PruneWarnings) {
10882     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10883                           S.PDiag(DiagID)
10884                               << E->getType() << T.getUnqualifiedType()
10885                               << PrettySourceValue << PrettyTargetValue
10886                               << E->getSourceRange() << SourceRange(CContext));
10887   } else {
10888     S.Diag(E->getExprLoc(), DiagID)
10889         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10890         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10891   }
10892 }
10893 
10894 /// Analyze the given compound assignment for the possible losing of
10895 /// floating-point precision.
10896 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10897   assert(isa<CompoundAssignOperator>(E) &&
10898          "Must be compound assignment operation");
10899   // Recurse on the LHS and RHS in here
10900   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10901   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10902 
10903   if (E->getLHS()->getType()->isAtomicType())
10904     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10905 
10906   // Now check the outermost expression
10907   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10908   const auto *RBT = cast<CompoundAssignOperator>(E)
10909                         ->getComputationResultType()
10910                         ->getAs<BuiltinType>();
10911 
10912   // The below checks assume source is floating point.
10913   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10914 
10915   // If source is floating point but target is an integer.
10916   if (ResultBT->isInteger())
10917     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10918                            E->getExprLoc(), diag::warn_impcast_float_integer);
10919 
10920   if (!ResultBT->isFloatingPoint())
10921     return;
10922 
10923   // If both source and target are floating points, warn about losing precision.
10924   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10925       QualType(ResultBT, 0), QualType(RBT, 0));
10926   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10927     // warn about dropping FP rank.
10928     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10929                     diag::warn_impcast_float_result_precision);
10930 }
10931 
10932 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10933                                       IntRange Range) {
10934   if (!Range.Width) return "0";
10935 
10936   llvm::APSInt ValueInRange = Value;
10937   ValueInRange.setIsSigned(!Range.NonNegative);
10938   ValueInRange = ValueInRange.trunc(Range.Width);
10939   return ValueInRange.toString(10);
10940 }
10941 
10942 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10943   if (!isa<ImplicitCastExpr>(Ex))
10944     return false;
10945 
10946   Expr *InnerE = Ex->IgnoreParenImpCasts();
10947   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10948   const Type *Source =
10949     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10950   if (Target->isDependentType())
10951     return false;
10952 
10953   const BuiltinType *FloatCandidateBT =
10954     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10955   const Type *BoolCandidateType = ToBool ? Target : Source;
10956 
10957   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10958           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10959 }
10960 
10961 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10962                                              SourceLocation CC) {
10963   unsigned NumArgs = TheCall->getNumArgs();
10964   for (unsigned i = 0; i < NumArgs; ++i) {
10965     Expr *CurrA = TheCall->getArg(i);
10966     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10967       continue;
10968 
10969     bool IsSwapped = ((i > 0) &&
10970         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10971     IsSwapped |= ((i < (NumArgs - 1)) &&
10972         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10973     if (IsSwapped) {
10974       // Warn on this floating-point to bool conversion.
10975       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10976                       CurrA->getType(), CC,
10977                       diag::warn_impcast_floating_point_to_bool);
10978     }
10979   }
10980 }
10981 
10982 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10983                                    SourceLocation CC) {
10984   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10985                         E->getExprLoc()))
10986     return;
10987 
10988   // Don't warn on functions which have return type nullptr_t.
10989   if (isa<CallExpr>(E))
10990     return;
10991 
10992   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10993   const Expr::NullPointerConstantKind NullKind =
10994       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10995   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10996     return;
10997 
10998   // Return if target type is a safe conversion.
10999   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11000       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11001     return;
11002 
11003   SourceLocation Loc = E->getSourceRange().getBegin();
11004 
11005   // Venture through the macro stacks to get to the source of macro arguments.
11006   // The new location is a better location than the complete location that was
11007   // passed in.
11008   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11009   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11010 
11011   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11012   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11013     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11014         Loc, S.SourceMgr, S.getLangOpts());
11015     if (MacroName == "NULL")
11016       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11017   }
11018 
11019   // Only warn if the null and context location are in the same macro expansion.
11020   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11021     return;
11022 
11023   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11024       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11025       << FixItHint::CreateReplacement(Loc,
11026                                       S.getFixItZeroLiteralForType(T, Loc));
11027 }
11028 
11029 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11030                                   ObjCArrayLiteral *ArrayLiteral);
11031 
11032 static void
11033 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11034                            ObjCDictionaryLiteral *DictionaryLiteral);
11035 
11036 /// Check a single element within a collection literal against the
11037 /// target element type.
11038 static void checkObjCCollectionLiteralElement(Sema &S,
11039                                               QualType TargetElementType,
11040                                               Expr *Element,
11041                                               unsigned ElementKind) {
11042   // Skip a bitcast to 'id' or qualified 'id'.
11043   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11044     if (ICE->getCastKind() == CK_BitCast &&
11045         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11046       Element = ICE->getSubExpr();
11047   }
11048 
11049   QualType ElementType = Element->getType();
11050   ExprResult ElementResult(Element);
11051   if (ElementType->getAs<ObjCObjectPointerType>() &&
11052       S.CheckSingleAssignmentConstraints(TargetElementType,
11053                                          ElementResult,
11054                                          false, false)
11055         != Sema::Compatible) {
11056     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11057         << ElementType << ElementKind << TargetElementType
11058         << Element->getSourceRange();
11059   }
11060 
11061   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11062     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11063   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11064     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11065 }
11066 
11067 /// Check an Objective-C array literal being converted to the given
11068 /// target type.
11069 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11070                                   ObjCArrayLiteral *ArrayLiteral) {
11071   if (!S.NSArrayDecl)
11072     return;
11073 
11074   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11075   if (!TargetObjCPtr)
11076     return;
11077 
11078   if (TargetObjCPtr->isUnspecialized() ||
11079       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11080         != S.NSArrayDecl->getCanonicalDecl())
11081     return;
11082 
11083   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11084   if (TypeArgs.size() != 1)
11085     return;
11086 
11087   QualType TargetElementType = TypeArgs[0];
11088   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11089     checkObjCCollectionLiteralElement(S, TargetElementType,
11090                                       ArrayLiteral->getElement(I),
11091                                       0);
11092   }
11093 }
11094 
11095 /// Check an Objective-C dictionary literal being converted to the given
11096 /// target type.
11097 static void
11098 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11099                            ObjCDictionaryLiteral *DictionaryLiteral) {
11100   if (!S.NSDictionaryDecl)
11101     return;
11102 
11103   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11104   if (!TargetObjCPtr)
11105     return;
11106 
11107   if (TargetObjCPtr->isUnspecialized() ||
11108       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11109         != S.NSDictionaryDecl->getCanonicalDecl())
11110     return;
11111 
11112   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11113   if (TypeArgs.size() != 2)
11114     return;
11115 
11116   QualType TargetKeyType = TypeArgs[0];
11117   QualType TargetObjectType = TypeArgs[1];
11118   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11119     auto Element = DictionaryLiteral->getKeyValueElement(I);
11120     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11121     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11122   }
11123 }
11124 
11125 // Helper function to filter out cases for constant width constant conversion.
11126 // Don't warn on char array initialization or for non-decimal values.
11127 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11128                                           SourceLocation CC) {
11129   // If initializing from a constant, and the constant starts with '0',
11130   // then it is a binary, octal, or hexadecimal.  Allow these constants
11131   // to fill all the bits, even if there is a sign change.
11132   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11133     const char FirstLiteralCharacter =
11134         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11135     if (FirstLiteralCharacter == '0')
11136       return false;
11137   }
11138 
11139   // If the CC location points to a '{', and the type is char, then assume
11140   // assume it is an array initialization.
11141   if (CC.isValid() && T->isCharType()) {
11142     const char FirstContextCharacter =
11143         S.getSourceManager().getCharacterData(CC)[0];
11144     if (FirstContextCharacter == '{')
11145       return false;
11146   }
11147 
11148   return true;
11149 }
11150 
11151 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11152   const auto *IL = dyn_cast<IntegerLiteral>(E);
11153   if (!IL) {
11154     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11155       if (UO->getOpcode() == UO_Minus)
11156         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11157     }
11158   }
11159 
11160   return IL;
11161 }
11162 
11163 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11164   E = E->IgnoreParenImpCasts();
11165   SourceLocation ExprLoc = E->getExprLoc();
11166 
11167   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11168     BinaryOperator::Opcode Opc = BO->getOpcode();
11169     Expr::EvalResult Result;
11170     // Do not diagnose unsigned shifts.
11171     if (Opc == BO_Shl) {
11172       const auto *LHS = getIntegerLiteral(BO->getLHS());
11173       const auto *RHS = getIntegerLiteral(BO->getRHS());
11174       if (LHS && LHS->getValue() == 0)
11175         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11176       else if (!E->isValueDependent() && LHS && RHS &&
11177                RHS->getValue().isNonNegative() &&
11178                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11179         S.Diag(ExprLoc, diag::warn_left_shift_always)
11180             << (Result.Val.getInt() != 0);
11181       else if (E->getType()->isSignedIntegerType())
11182         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11183     }
11184   }
11185 
11186   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11187     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11188     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11189     if (!LHS || !RHS)
11190       return;
11191     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11192         (RHS->getValue() == 0 || RHS->getValue() == 1))
11193       // Do not diagnose common idioms.
11194       return;
11195     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11196       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11197   }
11198 }
11199 
11200 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11201                                     SourceLocation CC,
11202                                     bool *ICContext = nullptr,
11203                                     bool IsListInit = false) {
11204   if (E->isTypeDependent() || E->isValueDependent()) return;
11205 
11206   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11207   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11208   if (Source == Target) return;
11209   if (Target->isDependentType()) return;
11210 
11211   // If the conversion context location is invalid don't complain. We also
11212   // don't want to emit a warning if the issue occurs from the expansion of
11213   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11214   // delay this check as long as possible. Once we detect we are in that
11215   // scenario, we just return.
11216   if (CC.isInvalid())
11217     return;
11218 
11219   if (Source->isAtomicType())
11220     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11221 
11222   // Diagnose implicit casts to bool.
11223   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11224     if (isa<StringLiteral>(E))
11225       // Warn on string literal to bool.  Checks for string literals in logical
11226       // and expressions, for instance, assert(0 && "error here"), are
11227       // prevented by a check in AnalyzeImplicitConversions().
11228       return DiagnoseImpCast(S, E, T, CC,
11229                              diag::warn_impcast_string_literal_to_bool);
11230     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11231         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11232       // This covers the literal expressions that evaluate to Objective-C
11233       // objects.
11234       return DiagnoseImpCast(S, E, T, CC,
11235                              diag::warn_impcast_objective_c_literal_to_bool);
11236     }
11237     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11238       // Warn on pointer to bool conversion that is always true.
11239       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11240                                      SourceRange(CC));
11241     }
11242   }
11243 
11244   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11245   // is a typedef for signed char (macOS), then that constant value has to be 1
11246   // or 0.
11247   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11248     Expr::EvalResult Result;
11249     if (E->EvaluateAsInt(Result, S.getASTContext(),
11250                          Expr::SE_AllowSideEffects)) {
11251       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11252         adornObjCBoolConversionDiagWithTernaryFixit(
11253             S, E,
11254             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11255                 << Result.Val.getInt().toString(10));
11256       }
11257       return;
11258     }
11259   }
11260 
11261   // Check implicit casts from Objective-C collection literals to specialized
11262   // collection types, e.g., NSArray<NSString *> *.
11263   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11264     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11265   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11266     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11267 
11268   // Strip vector types.
11269   if (isa<VectorType>(Source)) {
11270     if (!isa<VectorType>(Target)) {
11271       if (S.SourceMgr.isInSystemMacro(CC))
11272         return;
11273       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11274     }
11275 
11276     // If the vector cast is cast between two vectors of the same size, it is
11277     // a bitcast, not a conversion.
11278     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11279       return;
11280 
11281     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11282     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11283   }
11284   if (auto VecTy = dyn_cast<VectorType>(Target))
11285     Target = VecTy->getElementType().getTypePtr();
11286 
11287   // Strip complex types.
11288   if (isa<ComplexType>(Source)) {
11289     if (!isa<ComplexType>(Target)) {
11290       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11291         return;
11292 
11293       return DiagnoseImpCast(S, E, T, CC,
11294                              S.getLangOpts().CPlusPlus
11295                                  ? diag::err_impcast_complex_scalar
11296                                  : diag::warn_impcast_complex_scalar);
11297     }
11298 
11299     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11300     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11301   }
11302 
11303   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11304   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11305 
11306   // If the source is floating point...
11307   if (SourceBT && SourceBT->isFloatingPoint()) {
11308     // ...and the target is floating point...
11309     if (TargetBT && TargetBT->isFloatingPoint()) {
11310       // ...then warn if we're dropping FP rank.
11311 
11312       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11313           QualType(SourceBT, 0), QualType(TargetBT, 0));
11314       if (Order > 0) {
11315         // Don't warn about float constants that are precisely
11316         // representable in the target type.
11317         Expr::EvalResult result;
11318         if (E->EvaluateAsRValue(result, S.Context)) {
11319           // Value might be a float, a float vector, or a float complex.
11320           if (IsSameFloatAfterCast(result.Val,
11321                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11322                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11323             return;
11324         }
11325 
11326         if (S.SourceMgr.isInSystemMacro(CC))
11327           return;
11328 
11329         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11330       }
11331       // ... or possibly if we're increasing rank, too
11332       else if (Order < 0) {
11333         if (S.SourceMgr.isInSystemMacro(CC))
11334           return;
11335 
11336         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11337       }
11338       return;
11339     }
11340 
11341     // If the target is integral, always warn.
11342     if (TargetBT && TargetBT->isInteger()) {
11343       if (S.SourceMgr.isInSystemMacro(CC))
11344         return;
11345 
11346       DiagnoseFloatingImpCast(S, E, T, CC);
11347     }
11348 
11349     // Detect the case where a call result is converted from floating-point to
11350     // to bool, and the final argument to the call is converted from bool, to
11351     // discover this typo:
11352     //
11353     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11354     //
11355     // FIXME: This is an incredibly special case; is there some more general
11356     // way to detect this class of misplaced-parentheses bug?
11357     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11358       // Check last argument of function call to see if it is an
11359       // implicit cast from a type matching the type the result
11360       // is being cast to.
11361       CallExpr *CEx = cast<CallExpr>(E);
11362       if (unsigned NumArgs = CEx->getNumArgs()) {
11363         Expr *LastA = CEx->getArg(NumArgs - 1);
11364         Expr *InnerE = LastA->IgnoreParenImpCasts();
11365         if (isa<ImplicitCastExpr>(LastA) &&
11366             InnerE->getType()->isBooleanType()) {
11367           // Warn on this floating-point to bool conversion
11368           DiagnoseImpCast(S, E, T, CC,
11369                           diag::warn_impcast_floating_point_to_bool);
11370         }
11371       }
11372     }
11373     return;
11374   }
11375 
11376   // Valid casts involving fixed point types should be accounted for here.
11377   if (Source->isFixedPointType()) {
11378     if (Target->isUnsaturatedFixedPointType()) {
11379       Expr::EvalResult Result;
11380       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11381                                   S.isConstantEvaluated())) {
11382         APFixedPoint Value = Result.Val.getFixedPoint();
11383         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11384         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11385         if (Value > MaxVal || Value < MinVal) {
11386           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11387                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11388                                     << Value.toString() << T
11389                                     << E->getSourceRange()
11390                                     << clang::SourceRange(CC));
11391           return;
11392         }
11393       }
11394     } else if (Target->isIntegerType()) {
11395       Expr::EvalResult Result;
11396       if (!S.isConstantEvaluated() &&
11397           E->EvaluateAsFixedPoint(Result, S.Context,
11398                                   Expr::SE_AllowSideEffects)) {
11399         APFixedPoint FXResult = Result.Val.getFixedPoint();
11400 
11401         bool Overflowed;
11402         llvm::APSInt IntResult = FXResult.convertToInt(
11403             S.Context.getIntWidth(T),
11404             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11405 
11406         if (Overflowed) {
11407           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11408                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11409                                     << FXResult.toString() << T
11410                                     << E->getSourceRange()
11411                                     << clang::SourceRange(CC));
11412           return;
11413         }
11414       }
11415     }
11416   } else if (Target->isUnsaturatedFixedPointType()) {
11417     if (Source->isIntegerType()) {
11418       Expr::EvalResult Result;
11419       if (!S.isConstantEvaluated() &&
11420           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11421         llvm::APSInt Value = Result.Val.getInt();
11422 
11423         bool Overflowed;
11424         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11425             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11426 
11427         if (Overflowed) {
11428           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11429                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11430                                     << Value.toString(/*Radix=*/10) << T
11431                                     << E->getSourceRange()
11432                                     << clang::SourceRange(CC));
11433           return;
11434         }
11435       }
11436     }
11437   }
11438 
11439   // If we are casting an integer type to a floating point type without
11440   // initialization-list syntax, we might lose accuracy if the floating
11441   // point type has a narrower significand than the integer type.
11442   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11443       TargetBT->isFloatingType() && !IsListInit) {
11444     // Determine the number of precision bits in the source integer type.
11445     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11446     unsigned int SourcePrecision = SourceRange.Width;
11447 
11448     // Determine the number of precision bits in the
11449     // target floating point type.
11450     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11451         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11452 
11453     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11454         SourcePrecision > TargetPrecision) {
11455 
11456       llvm::APSInt SourceInt;
11457       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11458         // If the source integer is a constant, convert it to the target
11459         // floating point type. Issue a warning if the value changes
11460         // during the whole conversion.
11461         llvm::APFloat TargetFloatValue(
11462             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11463         llvm::APFloat::opStatus ConversionStatus =
11464             TargetFloatValue.convertFromAPInt(
11465                 SourceInt, SourceBT->isSignedInteger(),
11466                 llvm::APFloat::rmNearestTiesToEven);
11467 
11468         if (ConversionStatus != llvm::APFloat::opOK) {
11469           std::string PrettySourceValue = SourceInt.toString(10);
11470           SmallString<32> PrettyTargetValue;
11471           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11472 
11473           S.DiagRuntimeBehavior(
11474               E->getExprLoc(), E,
11475               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11476                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11477                   << E->getSourceRange() << clang::SourceRange(CC));
11478         }
11479       } else {
11480         // Otherwise, the implicit conversion may lose precision.
11481         DiagnoseImpCast(S, E, T, CC,
11482                         diag::warn_impcast_integer_float_precision);
11483       }
11484     }
11485   }
11486 
11487   DiagnoseNullConversion(S, E, T, CC);
11488 
11489   S.DiscardMisalignedMemberAddress(Target, E);
11490 
11491   if (Target->isBooleanType())
11492     DiagnoseIntInBoolContext(S, E);
11493 
11494   if (!Source->isIntegerType() || !Target->isIntegerType())
11495     return;
11496 
11497   // TODO: remove this early return once the false positives for constant->bool
11498   // in templates, macros, etc, are reduced or removed.
11499   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11500     return;
11501 
11502   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11503       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11504     return adornObjCBoolConversionDiagWithTernaryFixit(
11505         S, E,
11506         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11507             << E->getType());
11508   }
11509 
11510   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11511   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11512 
11513   if (SourceRange.Width > TargetRange.Width) {
11514     // If the source is a constant, use a default-on diagnostic.
11515     // TODO: this should happen for bitfield stores, too.
11516     Expr::EvalResult Result;
11517     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11518                          S.isConstantEvaluated())) {
11519       llvm::APSInt Value(32);
11520       Value = Result.Val.getInt();
11521 
11522       if (S.SourceMgr.isInSystemMacro(CC))
11523         return;
11524 
11525       std::string PrettySourceValue = Value.toString(10);
11526       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11527 
11528       S.DiagRuntimeBehavior(
11529           E->getExprLoc(), E,
11530           S.PDiag(diag::warn_impcast_integer_precision_constant)
11531               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11532               << E->getSourceRange() << clang::SourceRange(CC));
11533       return;
11534     }
11535 
11536     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11537     if (S.SourceMgr.isInSystemMacro(CC))
11538       return;
11539 
11540     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11541       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11542                              /* pruneControlFlow */ true);
11543     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11544   }
11545 
11546   if (TargetRange.Width > SourceRange.Width) {
11547     if (auto *UO = dyn_cast<UnaryOperator>(E))
11548       if (UO->getOpcode() == UO_Minus)
11549         if (Source->isUnsignedIntegerType()) {
11550           if (Target->isUnsignedIntegerType())
11551             return DiagnoseImpCast(S, E, T, CC,
11552                                    diag::warn_impcast_high_order_zero_bits);
11553           if (Target->isSignedIntegerType())
11554             return DiagnoseImpCast(S, E, T, CC,
11555                                    diag::warn_impcast_nonnegative_result);
11556         }
11557   }
11558 
11559   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11560       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11561     // Warn when doing a signed to signed conversion, warn if the positive
11562     // source value is exactly the width of the target type, which will
11563     // cause a negative value to be stored.
11564 
11565     Expr::EvalResult Result;
11566     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11567         !S.SourceMgr.isInSystemMacro(CC)) {
11568       llvm::APSInt Value = Result.Val.getInt();
11569       if (isSameWidthConstantConversion(S, E, T, CC)) {
11570         std::string PrettySourceValue = Value.toString(10);
11571         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11572 
11573         S.DiagRuntimeBehavior(
11574             E->getExprLoc(), E,
11575             S.PDiag(diag::warn_impcast_integer_precision_constant)
11576                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11577                 << E->getSourceRange() << clang::SourceRange(CC));
11578         return;
11579       }
11580     }
11581 
11582     // Fall through for non-constants to give a sign conversion warning.
11583   }
11584 
11585   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11586       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11587        SourceRange.Width == TargetRange.Width)) {
11588     if (S.SourceMgr.isInSystemMacro(CC))
11589       return;
11590 
11591     unsigned DiagID = diag::warn_impcast_integer_sign;
11592 
11593     // Traditionally, gcc has warned about this under -Wsign-compare.
11594     // We also want to warn about it in -Wconversion.
11595     // So if -Wconversion is off, use a completely identical diagnostic
11596     // in the sign-compare group.
11597     // The conditional-checking code will
11598     if (ICContext) {
11599       DiagID = diag::warn_impcast_integer_sign_conditional;
11600       *ICContext = true;
11601     }
11602 
11603     return DiagnoseImpCast(S, E, T, CC, DiagID);
11604   }
11605 
11606   // Diagnose conversions between different enumeration types.
11607   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11608   // type, to give us better diagnostics.
11609   QualType SourceType = E->getType();
11610   if (!S.getLangOpts().CPlusPlus) {
11611     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11612       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11613         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11614         SourceType = S.Context.getTypeDeclType(Enum);
11615         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11616       }
11617   }
11618 
11619   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11620     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11621       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11622           TargetEnum->getDecl()->hasNameForLinkage() &&
11623           SourceEnum != TargetEnum) {
11624         if (S.SourceMgr.isInSystemMacro(CC))
11625           return;
11626 
11627         return DiagnoseImpCast(S, E, SourceType, T, CC,
11628                                diag::warn_impcast_different_enum_types);
11629       }
11630 }
11631 
11632 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11633                                      SourceLocation CC, QualType T);
11634 
11635 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11636                                     SourceLocation CC, bool &ICContext) {
11637   E = E->IgnoreParenImpCasts();
11638 
11639   if (isa<ConditionalOperator>(E))
11640     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11641 
11642   AnalyzeImplicitConversions(S, E, CC);
11643   if (E->getType() != T)
11644     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11645 }
11646 
11647 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11648                                      SourceLocation CC, QualType T) {
11649   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11650 
11651   bool Suspicious = false;
11652   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11653   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11654 
11655   if (T->isBooleanType())
11656     DiagnoseIntInBoolContext(S, E);
11657 
11658   // If -Wconversion would have warned about either of the candidates
11659   // for a signedness conversion to the context type...
11660   if (!Suspicious) return;
11661 
11662   // ...but it's currently ignored...
11663   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11664     return;
11665 
11666   // ...then check whether it would have warned about either of the
11667   // candidates for a signedness conversion to the condition type.
11668   if (E->getType() == T) return;
11669 
11670   Suspicious = false;
11671   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11672                           E->getType(), CC, &Suspicious);
11673   if (!Suspicious)
11674     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11675                             E->getType(), CC, &Suspicious);
11676 }
11677 
11678 /// Check conversion of given expression to boolean.
11679 /// Input argument E is a logical expression.
11680 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11681   if (S.getLangOpts().Bool)
11682     return;
11683   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11684     return;
11685   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11686 }
11687 
11688 namespace {
11689 struct AnalyzeImplicitConversionsWorkItem {
11690   Expr *E;
11691   SourceLocation CC;
11692   bool IsListInit;
11693 };
11694 }
11695 
11696 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11697 /// that should be visited are added to WorkList.
11698 static void AnalyzeImplicitConversions(
11699     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11700     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
11701   Expr *OrigE = Item.E;
11702   SourceLocation CC = Item.CC;
11703 
11704   QualType T = OrigE->getType();
11705   Expr *E = OrigE->IgnoreParenImpCasts();
11706 
11707   // Propagate whether we are in a C++ list initialization expression.
11708   // If so, we do not issue warnings for implicit int-float conversion
11709   // precision loss, because C++11 narrowing already handles it.
11710   bool IsListInit = Item.IsListInit ||
11711                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11712 
11713   if (E->isTypeDependent() || E->isValueDependent())
11714     return;
11715 
11716   Expr *SourceExpr = E;
11717   // Examine, but don't traverse into the source expression of an
11718   // OpaqueValueExpr, since it may have multiple parents and we don't want to
11719   // emit duplicate diagnostics. Its fine to examine the form or attempt to
11720   // evaluate it in the context of checking the specific conversion to T though.
11721   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11722     if (auto *Src = OVE->getSourceExpr())
11723       SourceExpr = Src;
11724 
11725   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11726     if (UO->getOpcode() == UO_Not &&
11727         UO->getSubExpr()->isKnownToHaveBooleanValue())
11728       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11729           << OrigE->getSourceRange() << T->isBooleanType()
11730           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11731 
11732   // For conditional operators, we analyze the arguments as if they
11733   // were being fed directly into the output.
11734   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
11735     CheckConditionalOperator(S, CO, CC, T);
11736     return;
11737   }
11738 
11739   // Check implicit argument conversions for function calls.
11740   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11741     CheckImplicitArgumentConversions(S, Call, CC);
11742 
11743   // Go ahead and check any implicit conversions we might have skipped.
11744   // The non-canonical typecheck is just an optimization;
11745   // CheckImplicitConversion will filter out dead implicit conversions.
11746   if (SourceExpr->getType() != T)
11747     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
11748 
11749   // Now continue drilling into this expression.
11750 
11751   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11752     // The bound subexpressions in a PseudoObjectExpr are not reachable
11753     // as transitive children.
11754     // FIXME: Use a more uniform representation for this.
11755     for (auto *SE : POE->semantics())
11756       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11757         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11758   }
11759 
11760   // Skip past explicit casts.
11761   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11762     E = CE->getSubExpr()->IgnoreParenImpCasts();
11763     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11764       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11765     WorkList.push_back({E, CC, IsListInit});
11766     return;
11767   }
11768 
11769   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11770     // Do a somewhat different check with comparison operators.
11771     if (BO->isComparisonOp())
11772       return AnalyzeComparison(S, BO);
11773 
11774     // And with simple assignments.
11775     if (BO->getOpcode() == BO_Assign)
11776       return AnalyzeAssignment(S, BO);
11777     // And with compound assignments.
11778     if (BO->isAssignmentOp())
11779       return AnalyzeCompoundAssignment(S, BO);
11780   }
11781 
11782   // These break the otherwise-useful invariant below.  Fortunately,
11783   // we don't really need to recurse into them, because any internal
11784   // expressions should have been analyzed already when they were
11785   // built into statements.
11786   if (isa<StmtExpr>(E)) return;
11787 
11788   // Don't descend into unevaluated contexts.
11789   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11790 
11791   // Now just recurse over the expression's children.
11792   CC = E->getExprLoc();
11793   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11794   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11795   for (Stmt *SubStmt : E->children()) {
11796     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11797     if (!ChildExpr)
11798       continue;
11799 
11800     if (IsLogicalAndOperator &&
11801         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11802       // Ignore checking string literals that are in logical and operators.
11803       // This is a common pattern for asserts.
11804       continue;
11805     WorkList.push_back({ChildExpr, CC, IsListInit});
11806   }
11807 
11808   if (BO && BO->isLogicalOp()) {
11809     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11810     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11811       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11812 
11813     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11814     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11815       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11816   }
11817 
11818   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11819     if (U->getOpcode() == UO_LNot) {
11820       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11821     } else if (U->getOpcode() != UO_AddrOf) {
11822       if (U->getSubExpr()->getType()->isAtomicType())
11823         S.Diag(U->getSubExpr()->getBeginLoc(),
11824                diag::warn_atomic_implicit_seq_cst);
11825     }
11826   }
11827 }
11828 
11829 /// AnalyzeImplicitConversions - Find and report any interesting
11830 /// implicit conversions in the given expression.  There are a couple
11831 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11832 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11833                                        bool IsListInit/*= false*/) {
11834   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
11835   WorkList.push_back({OrigE, CC, IsListInit});
11836   while (!WorkList.empty())
11837     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11838 }
11839 
11840 /// Diagnose integer type and any valid implicit conversion to it.
11841 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11842   // Taking into account implicit conversions,
11843   // allow any integer.
11844   if (!E->getType()->isIntegerType()) {
11845     S.Diag(E->getBeginLoc(),
11846            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11847     return true;
11848   }
11849   // Potentially emit standard warnings for implicit conversions if enabled
11850   // using -Wconversion.
11851   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11852   return false;
11853 }
11854 
11855 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11856 // Returns true when emitting a warning about taking the address of a reference.
11857 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11858                               const PartialDiagnostic &PD) {
11859   E = E->IgnoreParenImpCasts();
11860 
11861   const FunctionDecl *FD = nullptr;
11862 
11863   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11864     if (!DRE->getDecl()->getType()->isReferenceType())
11865       return false;
11866   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11867     if (!M->getMemberDecl()->getType()->isReferenceType())
11868       return false;
11869   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11870     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11871       return false;
11872     FD = Call->getDirectCallee();
11873   } else {
11874     return false;
11875   }
11876 
11877   SemaRef.Diag(E->getExprLoc(), PD);
11878 
11879   // If possible, point to location of function.
11880   if (FD) {
11881     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11882   }
11883 
11884   return true;
11885 }
11886 
11887 // Returns true if the SourceLocation is expanded from any macro body.
11888 // Returns false if the SourceLocation is invalid, is from not in a macro
11889 // expansion, or is from expanded from a top-level macro argument.
11890 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11891   if (Loc.isInvalid())
11892     return false;
11893 
11894   while (Loc.isMacroID()) {
11895     if (SM.isMacroBodyExpansion(Loc))
11896       return true;
11897     Loc = SM.getImmediateMacroCallerLoc(Loc);
11898   }
11899 
11900   return false;
11901 }
11902 
11903 /// Diagnose pointers that are always non-null.
11904 /// \param E the expression containing the pointer
11905 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11906 /// compared to a null pointer
11907 /// \param IsEqual True when the comparison is equal to a null pointer
11908 /// \param Range Extra SourceRange to highlight in the diagnostic
11909 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11910                                         Expr::NullPointerConstantKind NullKind,
11911                                         bool IsEqual, SourceRange Range) {
11912   if (!E)
11913     return;
11914 
11915   // Don't warn inside macros.
11916   if (E->getExprLoc().isMacroID()) {
11917     const SourceManager &SM = getSourceManager();
11918     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11919         IsInAnyMacroBody(SM, Range.getBegin()))
11920       return;
11921   }
11922   E = E->IgnoreImpCasts();
11923 
11924   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11925 
11926   if (isa<CXXThisExpr>(E)) {
11927     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11928                                 : diag::warn_this_bool_conversion;
11929     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11930     return;
11931   }
11932 
11933   bool IsAddressOf = false;
11934 
11935   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11936     if (UO->getOpcode() != UO_AddrOf)
11937       return;
11938     IsAddressOf = true;
11939     E = UO->getSubExpr();
11940   }
11941 
11942   if (IsAddressOf) {
11943     unsigned DiagID = IsCompare
11944                           ? diag::warn_address_of_reference_null_compare
11945                           : diag::warn_address_of_reference_bool_conversion;
11946     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11947                                          << IsEqual;
11948     if (CheckForReference(*this, E, PD)) {
11949       return;
11950     }
11951   }
11952 
11953   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11954     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11955     std::string Str;
11956     llvm::raw_string_ostream S(Str);
11957     E->printPretty(S, nullptr, getPrintingPolicy());
11958     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11959                                 : diag::warn_cast_nonnull_to_bool;
11960     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11961       << E->getSourceRange() << Range << IsEqual;
11962     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11963   };
11964 
11965   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11966   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11967     if (auto *Callee = Call->getDirectCallee()) {
11968       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11969         ComplainAboutNonnullParamOrCall(A);
11970         return;
11971       }
11972     }
11973   }
11974 
11975   // Expect to find a single Decl.  Skip anything more complicated.
11976   ValueDecl *D = nullptr;
11977   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11978     D = R->getDecl();
11979   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11980     D = M->getMemberDecl();
11981   }
11982 
11983   // Weak Decls can be null.
11984   if (!D || D->isWeak())
11985     return;
11986 
11987   // Check for parameter decl with nonnull attribute
11988   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11989     if (getCurFunction() &&
11990         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11991       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11992         ComplainAboutNonnullParamOrCall(A);
11993         return;
11994       }
11995 
11996       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11997         // Skip function template not specialized yet.
11998         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11999           return;
12000         auto ParamIter = llvm::find(FD->parameters(), PV);
12001         assert(ParamIter != FD->param_end());
12002         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12003 
12004         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12005           if (!NonNull->args_size()) {
12006               ComplainAboutNonnullParamOrCall(NonNull);
12007               return;
12008           }
12009 
12010           for (const ParamIdx &ArgNo : NonNull->args()) {
12011             if (ArgNo.getASTIndex() == ParamNo) {
12012               ComplainAboutNonnullParamOrCall(NonNull);
12013               return;
12014             }
12015           }
12016         }
12017       }
12018     }
12019   }
12020 
12021   QualType T = D->getType();
12022   const bool IsArray = T->isArrayType();
12023   const bool IsFunction = T->isFunctionType();
12024 
12025   // Address of function is used to silence the function warning.
12026   if (IsAddressOf && IsFunction) {
12027     return;
12028   }
12029 
12030   // Found nothing.
12031   if (!IsAddressOf && !IsFunction && !IsArray)
12032     return;
12033 
12034   // Pretty print the expression for the diagnostic.
12035   std::string Str;
12036   llvm::raw_string_ostream S(Str);
12037   E->printPretty(S, nullptr, getPrintingPolicy());
12038 
12039   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12040                               : diag::warn_impcast_pointer_to_bool;
12041   enum {
12042     AddressOf,
12043     FunctionPointer,
12044     ArrayPointer
12045   } DiagType;
12046   if (IsAddressOf)
12047     DiagType = AddressOf;
12048   else if (IsFunction)
12049     DiagType = FunctionPointer;
12050   else if (IsArray)
12051     DiagType = ArrayPointer;
12052   else
12053     llvm_unreachable("Could not determine diagnostic.");
12054   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12055                                 << Range << IsEqual;
12056 
12057   if (!IsFunction)
12058     return;
12059 
12060   // Suggest '&' to silence the function warning.
12061   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12062       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12063 
12064   // Check to see if '()' fixit should be emitted.
12065   QualType ReturnType;
12066   UnresolvedSet<4> NonTemplateOverloads;
12067   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12068   if (ReturnType.isNull())
12069     return;
12070 
12071   if (IsCompare) {
12072     // There are two cases here.  If there is null constant, the only suggest
12073     // for a pointer return type.  If the null is 0, then suggest if the return
12074     // type is a pointer or an integer type.
12075     if (!ReturnType->isPointerType()) {
12076       if (NullKind == Expr::NPCK_ZeroExpression ||
12077           NullKind == Expr::NPCK_ZeroLiteral) {
12078         if (!ReturnType->isIntegerType())
12079           return;
12080       } else {
12081         return;
12082       }
12083     }
12084   } else { // !IsCompare
12085     // For function to bool, only suggest if the function pointer has bool
12086     // return type.
12087     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12088       return;
12089   }
12090   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12091       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12092 }
12093 
12094 /// Diagnoses "dangerous" implicit conversions within the given
12095 /// expression (which is a full expression).  Implements -Wconversion
12096 /// and -Wsign-compare.
12097 ///
12098 /// \param CC the "context" location of the implicit conversion, i.e.
12099 ///   the most location of the syntactic entity requiring the implicit
12100 ///   conversion
12101 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12102   // Don't diagnose in unevaluated contexts.
12103   if (isUnevaluatedContext())
12104     return;
12105 
12106   // Don't diagnose for value- or type-dependent expressions.
12107   if (E->isTypeDependent() || E->isValueDependent())
12108     return;
12109 
12110   // Check for array bounds violations in cases where the check isn't triggered
12111   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12112   // ArraySubscriptExpr is on the RHS of a variable initialization.
12113   CheckArrayAccess(E);
12114 
12115   // This is not the right CC for (e.g.) a variable initialization.
12116   AnalyzeImplicitConversions(*this, E, CC);
12117 }
12118 
12119 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12120 /// Input argument E is a logical expression.
12121 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12122   ::CheckBoolLikeConversion(*this, E, CC);
12123 }
12124 
12125 /// Diagnose when expression is an integer constant expression and its evaluation
12126 /// results in integer overflow
12127 void Sema::CheckForIntOverflow (Expr *E) {
12128   // Use a work list to deal with nested struct initializers.
12129   SmallVector<Expr *, 2> Exprs(1, E);
12130 
12131   do {
12132     Expr *OriginalE = Exprs.pop_back_val();
12133     Expr *E = OriginalE->IgnoreParenCasts();
12134 
12135     if (isa<BinaryOperator>(E)) {
12136       E->EvaluateForOverflow(Context);
12137       continue;
12138     }
12139 
12140     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12141       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12142     else if (isa<ObjCBoxedExpr>(OriginalE))
12143       E->EvaluateForOverflow(Context);
12144     else if (auto Call = dyn_cast<CallExpr>(E))
12145       Exprs.append(Call->arg_begin(), Call->arg_end());
12146     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12147       Exprs.append(Message->arg_begin(), Message->arg_end());
12148   } while (!Exprs.empty());
12149 }
12150 
12151 namespace {
12152 
12153 /// Visitor for expressions which looks for unsequenced operations on the
12154 /// same object.
12155 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12156   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12157 
12158   /// A tree of sequenced regions within an expression. Two regions are
12159   /// unsequenced if one is an ancestor or a descendent of the other. When we
12160   /// finish processing an expression with sequencing, such as a comma
12161   /// expression, we fold its tree nodes into its parent, since they are
12162   /// unsequenced with respect to nodes we will visit later.
12163   class SequenceTree {
12164     struct Value {
12165       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12166       unsigned Parent : 31;
12167       unsigned Merged : 1;
12168     };
12169     SmallVector<Value, 8> Values;
12170 
12171   public:
12172     /// A region within an expression which may be sequenced with respect
12173     /// to some other region.
12174     class Seq {
12175       friend class SequenceTree;
12176 
12177       unsigned Index;
12178 
12179       explicit Seq(unsigned N) : Index(N) {}
12180 
12181     public:
12182       Seq() : Index(0) {}
12183     };
12184 
12185     SequenceTree() { Values.push_back(Value(0)); }
12186     Seq root() const { return Seq(0); }
12187 
12188     /// Create a new sequence of operations, which is an unsequenced
12189     /// subset of \p Parent. This sequence of operations is sequenced with
12190     /// respect to other children of \p Parent.
12191     Seq allocate(Seq Parent) {
12192       Values.push_back(Value(Parent.Index));
12193       return Seq(Values.size() - 1);
12194     }
12195 
12196     /// Merge a sequence of operations into its parent.
12197     void merge(Seq S) {
12198       Values[S.Index].Merged = true;
12199     }
12200 
12201     /// Determine whether two operations are unsequenced. This operation
12202     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12203     /// should have been merged into its parent as appropriate.
12204     bool isUnsequenced(Seq Cur, Seq Old) {
12205       unsigned C = representative(Cur.Index);
12206       unsigned Target = representative(Old.Index);
12207       while (C >= Target) {
12208         if (C == Target)
12209           return true;
12210         C = Values[C].Parent;
12211       }
12212       return false;
12213     }
12214 
12215   private:
12216     /// Pick a representative for a sequence.
12217     unsigned representative(unsigned K) {
12218       if (Values[K].Merged)
12219         // Perform path compression as we go.
12220         return Values[K].Parent = representative(Values[K].Parent);
12221       return K;
12222     }
12223   };
12224 
12225   /// An object for which we can track unsequenced uses.
12226   using Object = const NamedDecl *;
12227 
12228   /// Different flavors of object usage which we track. We only track the
12229   /// least-sequenced usage of each kind.
12230   enum UsageKind {
12231     /// A read of an object. Multiple unsequenced reads are OK.
12232     UK_Use,
12233 
12234     /// A modification of an object which is sequenced before the value
12235     /// computation of the expression, such as ++n in C++.
12236     UK_ModAsValue,
12237 
12238     /// A modification of an object which is not sequenced before the value
12239     /// computation of the expression, such as n++.
12240     UK_ModAsSideEffect,
12241 
12242     UK_Count = UK_ModAsSideEffect + 1
12243   };
12244 
12245   /// Bundle together a sequencing region and the expression corresponding
12246   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12247   struct Usage {
12248     const Expr *UsageExpr;
12249     SequenceTree::Seq Seq;
12250 
12251     Usage() : UsageExpr(nullptr), Seq() {}
12252   };
12253 
12254   struct UsageInfo {
12255     Usage Uses[UK_Count];
12256 
12257     /// Have we issued a diagnostic for this object already?
12258     bool Diagnosed;
12259 
12260     UsageInfo() : Uses(), Diagnosed(false) {}
12261   };
12262   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12263 
12264   Sema &SemaRef;
12265 
12266   /// Sequenced regions within the expression.
12267   SequenceTree Tree;
12268 
12269   /// Declaration modifications and references which we have seen.
12270   UsageInfoMap UsageMap;
12271 
12272   /// The region we are currently within.
12273   SequenceTree::Seq Region;
12274 
12275   /// Filled in with declarations which were modified as a side-effect
12276   /// (that is, post-increment operations).
12277   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12278 
12279   /// Expressions to check later. We defer checking these to reduce
12280   /// stack usage.
12281   SmallVectorImpl<const Expr *> &WorkList;
12282 
12283   /// RAII object wrapping the visitation of a sequenced subexpression of an
12284   /// expression. At the end of this process, the side-effects of the evaluation
12285   /// become sequenced with respect to the value computation of the result, so
12286   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12287   /// UK_ModAsValue.
12288   struct SequencedSubexpression {
12289     SequencedSubexpression(SequenceChecker &Self)
12290       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12291       Self.ModAsSideEffect = &ModAsSideEffect;
12292     }
12293 
12294     ~SequencedSubexpression() {
12295       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12296         // Add a new usage with usage kind UK_ModAsValue, and then restore
12297         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12298         // the previous one was empty).
12299         UsageInfo &UI = Self.UsageMap[M.first];
12300         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12301         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12302         SideEffectUsage = M.second;
12303       }
12304       Self.ModAsSideEffect = OldModAsSideEffect;
12305     }
12306 
12307     SequenceChecker &Self;
12308     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12309     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12310   };
12311 
12312   /// RAII object wrapping the visitation of a subexpression which we might
12313   /// choose to evaluate as a constant. If any subexpression is evaluated and
12314   /// found to be non-constant, this allows us to suppress the evaluation of
12315   /// the outer expression.
12316   class EvaluationTracker {
12317   public:
12318     EvaluationTracker(SequenceChecker &Self)
12319         : Self(Self), Prev(Self.EvalTracker) {
12320       Self.EvalTracker = this;
12321     }
12322 
12323     ~EvaluationTracker() {
12324       Self.EvalTracker = Prev;
12325       if (Prev)
12326         Prev->EvalOK &= EvalOK;
12327     }
12328 
12329     bool evaluate(const Expr *E, bool &Result) {
12330       if (!EvalOK || E->isValueDependent())
12331         return false;
12332       EvalOK = E->EvaluateAsBooleanCondition(
12333           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12334       return EvalOK;
12335     }
12336 
12337   private:
12338     SequenceChecker &Self;
12339     EvaluationTracker *Prev;
12340     bool EvalOK = true;
12341   } *EvalTracker = nullptr;
12342 
12343   /// Find the object which is produced by the specified expression,
12344   /// if any.
12345   Object getObject(const Expr *E, bool Mod) const {
12346     E = E->IgnoreParenCasts();
12347     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12348       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12349         return getObject(UO->getSubExpr(), Mod);
12350     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12351       if (BO->getOpcode() == BO_Comma)
12352         return getObject(BO->getRHS(), Mod);
12353       if (Mod && BO->isAssignmentOp())
12354         return getObject(BO->getLHS(), Mod);
12355     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12356       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12357       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12358         return ME->getMemberDecl();
12359     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12360       // FIXME: If this is a reference, map through to its value.
12361       return DRE->getDecl();
12362     return nullptr;
12363   }
12364 
12365   /// Note that an object \p O was modified or used by an expression
12366   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12367   /// the object \p O as obtained via the \p UsageMap.
12368   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12369     // Get the old usage for the given object and usage kind.
12370     Usage &U = UI.Uses[UK];
12371     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12372       // If we have a modification as side effect and are in a sequenced
12373       // subexpression, save the old Usage so that we can restore it later
12374       // in SequencedSubexpression::~SequencedSubexpression.
12375       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12376         ModAsSideEffect->push_back(std::make_pair(O, U));
12377       // Then record the new usage with the current sequencing region.
12378       U.UsageExpr = UsageExpr;
12379       U.Seq = Region;
12380     }
12381   }
12382 
12383   /// Check whether a modification or use of an object \p O in an expression
12384   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12385   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12386   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12387   /// usage and false we are checking for a mod-use unsequenced usage.
12388   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12389                   UsageKind OtherKind, bool IsModMod) {
12390     if (UI.Diagnosed)
12391       return;
12392 
12393     const Usage &U = UI.Uses[OtherKind];
12394     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12395       return;
12396 
12397     const Expr *Mod = U.UsageExpr;
12398     const Expr *ModOrUse = UsageExpr;
12399     if (OtherKind == UK_Use)
12400       std::swap(Mod, ModOrUse);
12401 
12402     SemaRef.DiagRuntimeBehavior(
12403         Mod->getExprLoc(), {Mod, ModOrUse},
12404         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12405                                : diag::warn_unsequenced_mod_use)
12406             << O << SourceRange(ModOrUse->getExprLoc()));
12407     UI.Diagnosed = true;
12408   }
12409 
12410   // A note on note{Pre, Post}{Use, Mod}:
12411   //
12412   // (It helps to follow the algorithm with an expression such as
12413   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12414   //  operations before C++17 and both are well-defined in C++17).
12415   //
12416   // When visiting a node which uses/modify an object we first call notePreUse
12417   // or notePreMod before visiting its sub-expression(s). At this point the
12418   // children of the current node have not yet been visited and so the eventual
12419   // uses/modifications resulting from the children of the current node have not
12420   // been recorded yet.
12421   //
12422   // We then visit the children of the current node. After that notePostUse or
12423   // notePostMod is called. These will 1) detect an unsequenced modification
12424   // as side effect (as in "k++ + k") and 2) add a new usage with the
12425   // appropriate usage kind.
12426   //
12427   // We also have to be careful that some operation sequences modification as
12428   // side effect as well (for example: || or ,). To account for this we wrap
12429   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12430   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12431   // which record usages which are modifications as side effect, and then
12432   // downgrade them (or more accurately restore the previous usage which was a
12433   // modification as side effect) when exiting the scope of the sequenced
12434   // subexpression.
12435 
12436   void notePreUse(Object O, const Expr *UseExpr) {
12437     UsageInfo &UI = UsageMap[O];
12438     // Uses conflict with other modifications.
12439     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12440   }
12441 
12442   void notePostUse(Object O, const Expr *UseExpr) {
12443     UsageInfo &UI = UsageMap[O];
12444     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12445                /*IsModMod=*/false);
12446     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12447   }
12448 
12449   void notePreMod(Object O, const Expr *ModExpr) {
12450     UsageInfo &UI = UsageMap[O];
12451     // Modifications conflict with other modifications and with uses.
12452     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12453     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12454   }
12455 
12456   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12457     UsageInfo &UI = UsageMap[O];
12458     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12459                /*IsModMod=*/true);
12460     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12461   }
12462 
12463 public:
12464   SequenceChecker(Sema &S, const Expr *E,
12465                   SmallVectorImpl<const Expr *> &WorkList)
12466       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12467     Visit(E);
12468     // Silence a -Wunused-private-field since WorkList is now unused.
12469     // TODO: Evaluate if it can be used, and if not remove it.
12470     (void)this->WorkList;
12471   }
12472 
12473   void VisitStmt(const Stmt *S) {
12474     // Skip all statements which aren't expressions for now.
12475   }
12476 
12477   void VisitExpr(const Expr *E) {
12478     // By default, just recurse to evaluated subexpressions.
12479     Base::VisitStmt(E);
12480   }
12481 
12482   void VisitCastExpr(const CastExpr *E) {
12483     Object O = Object();
12484     if (E->getCastKind() == CK_LValueToRValue)
12485       O = getObject(E->getSubExpr(), false);
12486 
12487     if (O)
12488       notePreUse(O, E);
12489     VisitExpr(E);
12490     if (O)
12491       notePostUse(O, E);
12492   }
12493 
12494   void VisitSequencedExpressions(const Expr *SequencedBefore,
12495                                  const Expr *SequencedAfter) {
12496     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12497     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12498     SequenceTree::Seq OldRegion = Region;
12499 
12500     {
12501       SequencedSubexpression SeqBefore(*this);
12502       Region = BeforeRegion;
12503       Visit(SequencedBefore);
12504     }
12505 
12506     Region = AfterRegion;
12507     Visit(SequencedAfter);
12508 
12509     Region = OldRegion;
12510 
12511     Tree.merge(BeforeRegion);
12512     Tree.merge(AfterRegion);
12513   }
12514 
12515   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12516     // C++17 [expr.sub]p1:
12517     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12518     //   expression E1 is sequenced before the expression E2.
12519     if (SemaRef.getLangOpts().CPlusPlus17)
12520       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12521     else {
12522       Visit(ASE->getLHS());
12523       Visit(ASE->getRHS());
12524     }
12525   }
12526 
12527   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12528   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12529   void VisitBinPtrMem(const BinaryOperator *BO) {
12530     // C++17 [expr.mptr.oper]p4:
12531     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12532     //  the expression E1 is sequenced before the expression E2.
12533     if (SemaRef.getLangOpts().CPlusPlus17)
12534       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12535     else {
12536       Visit(BO->getLHS());
12537       Visit(BO->getRHS());
12538     }
12539   }
12540 
12541   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12542   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12543   void VisitBinShlShr(const BinaryOperator *BO) {
12544     // C++17 [expr.shift]p4:
12545     //  The expression E1 is sequenced before the expression E2.
12546     if (SemaRef.getLangOpts().CPlusPlus17)
12547       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12548     else {
12549       Visit(BO->getLHS());
12550       Visit(BO->getRHS());
12551     }
12552   }
12553 
12554   void VisitBinComma(const BinaryOperator *BO) {
12555     // C++11 [expr.comma]p1:
12556     //   Every value computation and side effect associated with the left
12557     //   expression is sequenced before every value computation and side
12558     //   effect associated with the right expression.
12559     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12560   }
12561 
12562   void VisitBinAssign(const BinaryOperator *BO) {
12563     SequenceTree::Seq RHSRegion;
12564     SequenceTree::Seq LHSRegion;
12565     if (SemaRef.getLangOpts().CPlusPlus17) {
12566       RHSRegion = Tree.allocate(Region);
12567       LHSRegion = Tree.allocate(Region);
12568     } else {
12569       RHSRegion = Region;
12570       LHSRegion = Region;
12571     }
12572     SequenceTree::Seq OldRegion = Region;
12573 
12574     // C++11 [expr.ass]p1:
12575     //  [...] the assignment is sequenced after the value computation
12576     //  of the right and left operands, [...]
12577     //
12578     // so check it before inspecting the operands and update the
12579     // map afterwards.
12580     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12581     if (O)
12582       notePreMod(O, BO);
12583 
12584     if (SemaRef.getLangOpts().CPlusPlus17) {
12585       // C++17 [expr.ass]p1:
12586       //  [...] The right operand is sequenced before the left operand. [...]
12587       {
12588         SequencedSubexpression SeqBefore(*this);
12589         Region = RHSRegion;
12590         Visit(BO->getRHS());
12591       }
12592 
12593       Region = LHSRegion;
12594       Visit(BO->getLHS());
12595 
12596       if (O && isa<CompoundAssignOperator>(BO))
12597         notePostUse(O, BO);
12598 
12599     } else {
12600       // C++11 does not specify any sequencing between the LHS and RHS.
12601       Region = LHSRegion;
12602       Visit(BO->getLHS());
12603 
12604       if (O && isa<CompoundAssignOperator>(BO))
12605         notePostUse(O, BO);
12606 
12607       Region = RHSRegion;
12608       Visit(BO->getRHS());
12609     }
12610 
12611     // C++11 [expr.ass]p1:
12612     //  the assignment is sequenced [...] before the value computation of the
12613     //  assignment expression.
12614     // C11 6.5.16/3 has no such rule.
12615     Region = OldRegion;
12616     if (O)
12617       notePostMod(O, BO,
12618                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12619                                                   : UK_ModAsSideEffect);
12620     if (SemaRef.getLangOpts().CPlusPlus17) {
12621       Tree.merge(RHSRegion);
12622       Tree.merge(LHSRegion);
12623     }
12624   }
12625 
12626   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12627     VisitBinAssign(CAO);
12628   }
12629 
12630   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12631   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12632   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12633     Object O = getObject(UO->getSubExpr(), true);
12634     if (!O)
12635       return VisitExpr(UO);
12636 
12637     notePreMod(O, UO);
12638     Visit(UO->getSubExpr());
12639     // C++11 [expr.pre.incr]p1:
12640     //   the expression ++x is equivalent to x+=1
12641     notePostMod(O, UO,
12642                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12643                                                 : UK_ModAsSideEffect);
12644   }
12645 
12646   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12647   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12648   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12649     Object O = getObject(UO->getSubExpr(), true);
12650     if (!O)
12651       return VisitExpr(UO);
12652 
12653     notePreMod(O, UO);
12654     Visit(UO->getSubExpr());
12655     notePostMod(O, UO, UK_ModAsSideEffect);
12656   }
12657 
12658   void VisitBinLOr(const BinaryOperator *BO) {
12659     // C++11 [expr.log.or]p2:
12660     //  If the second expression is evaluated, every value computation and
12661     //  side effect associated with the first expression is sequenced before
12662     //  every value computation and side effect associated with the
12663     //  second expression.
12664     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12665     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12666     SequenceTree::Seq OldRegion = Region;
12667 
12668     EvaluationTracker Eval(*this);
12669     {
12670       SequencedSubexpression Sequenced(*this);
12671       Region = LHSRegion;
12672       Visit(BO->getLHS());
12673     }
12674 
12675     // C++11 [expr.log.or]p1:
12676     //  [...] the second operand is not evaluated if the first operand
12677     //  evaluates to true.
12678     bool EvalResult = false;
12679     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12680     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12681     if (ShouldVisitRHS) {
12682       Region = RHSRegion;
12683       Visit(BO->getRHS());
12684     }
12685 
12686     Region = OldRegion;
12687     Tree.merge(LHSRegion);
12688     Tree.merge(RHSRegion);
12689   }
12690 
12691   void VisitBinLAnd(const BinaryOperator *BO) {
12692     // C++11 [expr.log.and]p2:
12693     //  If the second expression is evaluated, every value computation and
12694     //  side effect associated with the first expression is sequenced before
12695     //  every value computation and side effect associated with the
12696     //  second expression.
12697     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12698     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12699     SequenceTree::Seq OldRegion = Region;
12700 
12701     EvaluationTracker Eval(*this);
12702     {
12703       SequencedSubexpression Sequenced(*this);
12704       Region = LHSRegion;
12705       Visit(BO->getLHS());
12706     }
12707 
12708     // C++11 [expr.log.and]p1:
12709     //  [...] the second operand is not evaluated if the first operand is false.
12710     bool EvalResult = false;
12711     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12712     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12713     if (ShouldVisitRHS) {
12714       Region = RHSRegion;
12715       Visit(BO->getRHS());
12716     }
12717 
12718     Region = OldRegion;
12719     Tree.merge(LHSRegion);
12720     Tree.merge(RHSRegion);
12721   }
12722 
12723   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12724     // C++11 [expr.cond]p1:
12725     //  [...] Every value computation and side effect associated with the first
12726     //  expression is sequenced before every value computation and side effect
12727     //  associated with the second or third expression.
12728     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12729 
12730     // No sequencing is specified between the true and false expression.
12731     // However since exactly one of both is going to be evaluated we can
12732     // consider them to be sequenced. This is needed to avoid warning on
12733     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12734     // both the true and false expressions because we can't evaluate x.
12735     // This will still allow us to detect an expression like (pre C++17)
12736     // "(x ? y += 1 : y += 2) = y".
12737     //
12738     // We don't wrap the visitation of the true and false expression with
12739     // SequencedSubexpression because we don't want to downgrade modifications
12740     // as side effect in the true and false expressions after the visition
12741     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12742     // not warn between the two "y++", but we should warn between the "y++"
12743     // and the "y".
12744     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12745     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12746     SequenceTree::Seq OldRegion = Region;
12747 
12748     EvaluationTracker Eval(*this);
12749     {
12750       SequencedSubexpression Sequenced(*this);
12751       Region = ConditionRegion;
12752       Visit(CO->getCond());
12753     }
12754 
12755     // C++11 [expr.cond]p1:
12756     // [...] The first expression is contextually converted to bool (Clause 4).
12757     // It is evaluated and if it is true, the result of the conditional
12758     // expression is the value of the second expression, otherwise that of the
12759     // third expression. Only one of the second and third expressions is
12760     // evaluated. [...]
12761     bool EvalResult = false;
12762     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12763     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12764     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12765     if (ShouldVisitTrueExpr) {
12766       Region = TrueRegion;
12767       Visit(CO->getTrueExpr());
12768     }
12769     if (ShouldVisitFalseExpr) {
12770       Region = FalseRegion;
12771       Visit(CO->getFalseExpr());
12772     }
12773 
12774     Region = OldRegion;
12775     Tree.merge(ConditionRegion);
12776     Tree.merge(TrueRegion);
12777     Tree.merge(FalseRegion);
12778   }
12779 
12780   void VisitCallExpr(const CallExpr *CE) {
12781     // C++11 [intro.execution]p15:
12782     //   When calling a function [...], every value computation and side effect
12783     //   associated with any argument expression, or with the postfix expression
12784     //   designating the called function, is sequenced before execution of every
12785     //   expression or statement in the body of the function [and thus before
12786     //   the value computation of its result].
12787     SequencedSubexpression Sequenced(*this);
12788     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(),
12789                                         [&] { Base::VisitCallExpr(CE); });
12790 
12791     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12792   }
12793 
12794   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12795     // This is a call, so all subexpressions are sequenced before the result.
12796     SequencedSubexpression Sequenced(*this);
12797 
12798     if (!CCE->isListInitialization())
12799       return VisitExpr(CCE);
12800 
12801     // In C++11, list initializations are sequenced.
12802     SmallVector<SequenceTree::Seq, 32> Elts;
12803     SequenceTree::Seq Parent = Region;
12804     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
12805                                               E = CCE->arg_end();
12806          I != E; ++I) {
12807       Region = Tree.allocate(Parent);
12808       Elts.push_back(Region);
12809       Visit(*I);
12810     }
12811 
12812     // Forget that the initializers are sequenced.
12813     Region = Parent;
12814     for (unsigned I = 0; I < Elts.size(); ++I)
12815       Tree.merge(Elts[I]);
12816   }
12817 
12818   void VisitInitListExpr(const InitListExpr *ILE) {
12819     if (!SemaRef.getLangOpts().CPlusPlus11)
12820       return VisitExpr(ILE);
12821 
12822     // In C++11, list initializations are sequenced.
12823     SmallVector<SequenceTree::Seq, 32> Elts;
12824     SequenceTree::Seq Parent = Region;
12825     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12826       const Expr *E = ILE->getInit(I);
12827       if (!E)
12828         continue;
12829       Region = Tree.allocate(Parent);
12830       Elts.push_back(Region);
12831       Visit(E);
12832     }
12833 
12834     // Forget that the initializers are sequenced.
12835     Region = Parent;
12836     for (unsigned I = 0; I < Elts.size(); ++I)
12837       Tree.merge(Elts[I]);
12838   }
12839 };
12840 
12841 } // namespace
12842 
12843 void Sema::CheckUnsequencedOperations(const Expr *E) {
12844   SmallVector<const Expr *, 8> WorkList;
12845   WorkList.push_back(E);
12846   while (!WorkList.empty()) {
12847     const Expr *Item = WorkList.pop_back_val();
12848     SequenceChecker(*this, Item, WorkList);
12849   }
12850 }
12851 
12852 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12853                               bool IsConstexpr) {
12854   llvm::SaveAndRestore<bool> ConstantContext(
12855       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12856   CheckImplicitConversions(E, CheckLoc);
12857   if (!E->isInstantiationDependent())
12858     CheckUnsequencedOperations(E);
12859   if (!IsConstexpr && !E->isValueDependent())
12860     CheckForIntOverflow(E);
12861   DiagnoseMisalignedMembers();
12862 }
12863 
12864 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12865                                        FieldDecl *BitField,
12866                                        Expr *Init) {
12867   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12868 }
12869 
12870 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12871                                          SourceLocation Loc) {
12872   if (!PType->isVariablyModifiedType())
12873     return;
12874   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12875     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12876     return;
12877   }
12878   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12879     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12880     return;
12881   }
12882   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12883     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12884     return;
12885   }
12886 
12887   const ArrayType *AT = S.Context.getAsArrayType(PType);
12888   if (!AT)
12889     return;
12890 
12891   if (AT->getSizeModifier() != ArrayType::Star) {
12892     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12893     return;
12894   }
12895 
12896   S.Diag(Loc, diag::err_array_star_in_function_definition);
12897 }
12898 
12899 /// CheckParmsForFunctionDef - Check that the parameters of the given
12900 /// function are appropriate for the definition of a function. This
12901 /// takes care of any checks that cannot be performed on the
12902 /// declaration itself, e.g., that the types of each of the function
12903 /// parameters are complete.
12904 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12905                                     bool CheckParameterNames) {
12906   bool HasInvalidParm = false;
12907   for (ParmVarDecl *Param : Parameters) {
12908     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12909     // function declarator that is part of a function definition of
12910     // that function shall not have incomplete type.
12911     //
12912     // This is also C++ [dcl.fct]p6.
12913     if (!Param->isInvalidDecl() &&
12914         RequireCompleteType(Param->getLocation(), Param->getType(),
12915                             diag::err_typecheck_decl_incomplete_type)) {
12916       Param->setInvalidDecl();
12917       HasInvalidParm = true;
12918     }
12919 
12920     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12921     // declaration of each parameter shall include an identifier.
12922     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
12923         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
12924       // Diagnose this as an extension in C17 and earlier.
12925       if (!getLangOpts().C2x)
12926         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
12927     }
12928 
12929     // C99 6.7.5.3p12:
12930     //   If the function declarator is not part of a definition of that
12931     //   function, parameters may have incomplete type and may use the [*]
12932     //   notation in their sequences of declarator specifiers to specify
12933     //   variable length array types.
12934     QualType PType = Param->getOriginalType();
12935     // FIXME: This diagnostic should point the '[*]' if source-location
12936     // information is added for it.
12937     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12938 
12939     // If the parameter is a c++ class type and it has to be destructed in the
12940     // callee function, declare the destructor so that it can be called by the
12941     // callee function. Do not perform any direct access check on the dtor here.
12942     if (!Param->isInvalidDecl()) {
12943       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12944         if (!ClassDecl->isInvalidDecl() &&
12945             !ClassDecl->hasIrrelevantDestructor() &&
12946             !ClassDecl->isDependentContext() &&
12947             ClassDecl->isParamDestroyedInCallee()) {
12948           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12949           MarkFunctionReferenced(Param->getLocation(), Destructor);
12950           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12951         }
12952       }
12953     }
12954 
12955     // Parameters with the pass_object_size attribute only need to be marked
12956     // constant at function definitions. Because we lack information about
12957     // whether we're on a declaration or definition when we're instantiating the
12958     // attribute, we need to check for constness here.
12959     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12960       if (!Param->getType().isConstQualified())
12961         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12962             << Attr->getSpelling() << 1;
12963 
12964     // Check for parameter names shadowing fields from the class.
12965     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12966       // The owning context for the parameter should be the function, but we
12967       // want to see if this function's declaration context is a record.
12968       DeclContext *DC = Param->getDeclContext();
12969       if (DC && DC->isFunctionOrMethod()) {
12970         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12971           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12972                                      RD, /*DeclIsField*/ false);
12973       }
12974     }
12975   }
12976 
12977   return HasInvalidParm;
12978 }
12979 
12980 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12981 /// or MemberExpr.
12982 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12983                               ASTContext &Context) {
12984   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12985     return Context.getDeclAlign(DRE->getDecl());
12986 
12987   if (const auto *ME = dyn_cast<MemberExpr>(E))
12988     return Context.getDeclAlign(ME->getMemberDecl());
12989 
12990   return TypeAlign;
12991 }
12992 
12993 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12994 /// pointer cast increases the alignment requirements.
12995 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12996   // This is actually a lot of work to potentially be doing on every
12997   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12998   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12999     return;
13000 
13001   // Ignore dependent types.
13002   if (T->isDependentType() || Op->getType()->isDependentType())
13003     return;
13004 
13005   // Require that the destination be a pointer type.
13006   const PointerType *DestPtr = T->getAs<PointerType>();
13007   if (!DestPtr) return;
13008 
13009   // If the destination has alignment 1, we're done.
13010   QualType DestPointee = DestPtr->getPointeeType();
13011   if (DestPointee->isIncompleteType()) return;
13012   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13013   if (DestAlign.isOne()) return;
13014 
13015   // Require that the source be a pointer type.
13016   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13017   if (!SrcPtr) return;
13018   QualType SrcPointee = SrcPtr->getPointeeType();
13019 
13020   // Whitelist casts from cv void*.  We already implicitly
13021   // whitelisted casts to cv void*, since they have alignment 1.
13022   // Also whitelist casts involving incomplete types, which implicitly
13023   // includes 'void'.
13024   if (SrcPointee->isIncompleteType()) return;
13025 
13026   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13027 
13028   if (auto *CE = dyn_cast<CastExpr>(Op)) {
13029     if (CE->getCastKind() == CK_ArrayToPointerDecay)
13030       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13031   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13032     if (UO->getOpcode() == UO_AddrOf)
13033       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13034   }
13035 
13036   if (SrcAlign >= DestAlign) return;
13037 
13038   Diag(TRange.getBegin(), diag::warn_cast_align)
13039     << Op->getType() << T
13040     << static_cast<unsigned>(SrcAlign.getQuantity())
13041     << static_cast<unsigned>(DestAlign.getQuantity())
13042     << TRange << Op->getSourceRange();
13043 }
13044 
13045 /// Check whether this array fits the idiom of a size-one tail padded
13046 /// array member of a struct.
13047 ///
13048 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13049 /// commonly used to emulate flexible arrays in C89 code.
13050 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13051                                     const NamedDecl *ND) {
13052   if (Size != 1 || !ND) return false;
13053 
13054   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13055   if (!FD) return false;
13056 
13057   // Don't consider sizes resulting from macro expansions or template argument
13058   // substitution to form C89 tail-padded arrays.
13059 
13060   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13061   while (TInfo) {
13062     TypeLoc TL = TInfo->getTypeLoc();
13063     // Look through typedefs.
13064     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13065       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13066       TInfo = TDL->getTypeSourceInfo();
13067       continue;
13068     }
13069     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13070       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13071       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13072         return false;
13073     }
13074     break;
13075   }
13076 
13077   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13078   if (!RD) return false;
13079   if (RD->isUnion()) return false;
13080   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13081     if (!CRD->isStandardLayout()) return false;
13082   }
13083 
13084   // See if this is the last field decl in the record.
13085   const Decl *D = FD;
13086   while ((D = D->getNextDeclInContext()))
13087     if (isa<FieldDecl>(D))
13088       return false;
13089   return true;
13090 }
13091 
13092 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13093                             const ArraySubscriptExpr *ASE,
13094                             bool AllowOnePastEnd, bool IndexNegated) {
13095   // Already diagnosed by the constant evaluator.
13096   if (isConstantEvaluated())
13097     return;
13098 
13099   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13100   if (IndexExpr->isValueDependent())
13101     return;
13102 
13103   const Type *EffectiveType =
13104       BaseExpr->getType()->getPointeeOrArrayElementType();
13105   BaseExpr = BaseExpr->IgnoreParenCasts();
13106   const ConstantArrayType *ArrayTy =
13107       Context.getAsConstantArrayType(BaseExpr->getType());
13108 
13109   if (!ArrayTy)
13110     return;
13111 
13112   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13113   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13114     return;
13115 
13116   Expr::EvalResult Result;
13117   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13118     return;
13119 
13120   llvm::APSInt index = Result.Val.getInt();
13121   if (IndexNegated)
13122     index = -index;
13123 
13124   const NamedDecl *ND = nullptr;
13125   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13126     ND = DRE->getDecl();
13127   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13128     ND = ME->getMemberDecl();
13129 
13130   if (index.isUnsigned() || !index.isNegative()) {
13131     // It is possible that the type of the base expression after
13132     // IgnoreParenCasts is incomplete, even though the type of the base
13133     // expression before IgnoreParenCasts is complete (see PR39746 for an
13134     // example). In this case we have no information about whether the array
13135     // access exceeds the array bounds. However we can still diagnose an array
13136     // access which precedes the array bounds.
13137     if (BaseType->isIncompleteType())
13138       return;
13139 
13140     llvm::APInt size = ArrayTy->getSize();
13141     if (!size.isStrictlyPositive())
13142       return;
13143 
13144     if (BaseType != EffectiveType) {
13145       // Make sure we're comparing apples to apples when comparing index to size
13146       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13147       uint64_t array_typesize = Context.getTypeSize(BaseType);
13148       // Handle ptrarith_typesize being zero, such as when casting to void*
13149       if (!ptrarith_typesize) ptrarith_typesize = 1;
13150       if (ptrarith_typesize != array_typesize) {
13151         // There's a cast to a different size type involved
13152         uint64_t ratio = array_typesize / ptrarith_typesize;
13153         // TODO: Be smarter about handling cases where array_typesize is not a
13154         // multiple of ptrarith_typesize
13155         if (ptrarith_typesize * ratio == array_typesize)
13156           size *= llvm::APInt(size.getBitWidth(), ratio);
13157       }
13158     }
13159 
13160     if (size.getBitWidth() > index.getBitWidth())
13161       index = index.zext(size.getBitWidth());
13162     else if (size.getBitWidth() < index.getBitWidth())
13163       size = size.zext(index.getBitWidth());
13164 
13165     // For array subscripting the index must be less than size, but for pointer
13166     // arithmetic also allow the index (offset) to be equal to size since
13167     // computing the next address after the end of the array is legal and
13168     // commonly done e.g. in C++ iterators and range-based for loops.
13169     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13170       return;
13171 
13172     // Also don't warn for arrays of size 1 which are members of some
13173     // structure. These are often used to approximate flexible arrays in C89
13174     // code.
13175     if (IsTailPaddedMemberArray(*this, size, ND))
13176       return;
13177 
13178     // Suppress the warning if the subscript expression (as identified by the
13179     // ']' location) and the index expression are both from macro expansions
13180     // within a system header.
13181     if (ASE) {
13182       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13183           ASE->getRBracketLoc());
13184       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13185         SourceLocation IndexLoc =
13186             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13187         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13188           return;
13189       }
13190     }
13191 
13192     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13193     if (ASE)
13194       DiagID = diag::warn_array_index_exceeds_bounds;
13195 
13196     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13197                         PDiag(DiagID) << index.toString(10, true)
13198                                       << size.toString(10, true)
13199                                       << (unsigned)size.getLimitedValue(~0U)
13200                                       << IndexExpr->getSourceRange());
13201   } else {
13202     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13203     if (!ASE) {
13204       DiagID = diag::warn_ptr_arith_precedes_bounds;
13205       if (index.isNegative()) index = -index;
13206     }
13207 
13208     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13209                         PDiag(DiagID) << index.toString(10, true)
13210                                       << IndexExpr->getSourceRange());
13211   }
13212 
13213   if (!ND) {
13214     // Try harder to find a NamedDecl to point at in the note.
13215     while (const ArraySubscriptExpr *ASE =
13216            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13217       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13218     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13219       ND = DRE->getDecl();
13220     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13221       ND = ME->getMemberDecl();
13222   }
13223 
13224   if (ND)
13225     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13226                         PDiag(diag::note_array_declared_here)
13227                             << ND->getDeclName());
13228 }
13229 
13230 void Sema::CheckArrayAccess(const Expr *expr) {
13231   int AllowOnePastEnd = 0;
13232   while (expr) {
13233     expr = expr->IgnoreParenImpCasts();
13234     switch (expr->getStmtClass()) {
13235       case Stmt::ArraySubscriptExprClass: {
13236         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13237         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13238                          AllowOnePastEnd > 0);
13239         expr = ASE->getBase();
13240         break;
13241       }
13242       case Stmt::MemberExprClass: {
13243         expr = cast<MemberExpr>(expr)->getBase();
13244         break;
13245       }
13246       case Stmt::OMPArraySectionExprClass: {
13247         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13248         if (ASE->getLowerBound())
13249           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13250                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13251         return;
13252       }
13253       case Stmt::UnaryOperatorClass: {
13254         // Only unwrap the * and & unary operators
13255         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13256         expr = UO->getSubExpr();
13257         switch (UO->getOpcode()) {
13258           case UO_AddrOf:
13259             AllowOnePastEnd++;
13260             break;
13261           case UO_Deref:
13262             AllowOnePastEnd--;
13263             break;
13264           default:
13265             return;
13266         }
13267         break;
13268       }
13269       case Stmt::ConditionalOperatorClass: {
13270         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13271         if (const Expr *lhs = cond->getLHS())
13272           CheckArrayAccess(lhs);
13273         if (const Expr *rhs = cond->getRHS())
13274           CheckArrayAccess(rhs);
13275         return;
13276       }
13277       case Stmt::CXXOperatorCallExprClass: {
13278         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13279         for (const auto *Arg : OCE->arguments())
13280           CheckArrayAccess(Arg);
13281         return;
13282       }
13283       default:
13284         return;
13285     }
13286   }
13287 }
13288 
13289 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13290 
13291 namespace {
13292 
13293 struct RetainCycleOwner {
13294   VarDecl *Variable = nullptr;
13295   SourceRange Range;
13296   SourceLocation Loc;
13297   bool Indirect = false;
13298 
13299   RetainCycleOwner() = default;
13300 
13301   void setLocsFrom(Expr *e) {
13302     Loc = e->getExprLoc();
13303     Range = e->getSourceRange();
13304   }
13305 };
13306 
13307 } // namespace
13308 
13309 /// Consider whether capturing the given variable can possibly lead to
13310 /// a retain cycle.
13311 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13312   // In ARC, it's captured strongly iff the variable has __strong
13313   // lifetime.  In MRR, it's captured strongly if the variable is
13314   // __block and has an appropriate type.
13315   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13316     return false;
13317 
13318   owner.Variable = var;
13319   if (ref)
13320     owner.setLocsFrom(ref);
13321   return true;
13322 }
13323 
13324 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13325   while (true) {
13326     e = e->IgnoreParens();
13327     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13328       switch (cast->getCastKind()) {
13329       case CK_BitCast:
13330       case CK_LValueBitCast:
13331       case CK_LValueToRValue:
13332       case CK_ARCReclaimReturnedObject:
13333         e = cast->getSubExpr();
13334         continue;
13335 
13336       default:
13337         return false;
13338       }
13339     }
13340 
13341     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13342       ObjCIvarDecl *ivar = ref->getDecl();
13343       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13344         return false;
13345 
13346       // Try to find a retain cycle in the base.
13347       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13348         return false;
13349 
13350       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13351       owner.Indirect = true;
13352       return true;
13353     }
13354 
13355     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13356       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13357       if (!var) return false;
13358       return considerVariable(var, ref, owner);
13359     }
13360 
13361     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13362       if (member->isArrow()) return false;
13363 
13364       // Don't count this as an indirect ownership.
13365       e = member->getBase();
13366       continue;
13367     }
13368 
13369     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13370       // Only pay attention to pseudo-objects on property references.
13371       ObjCPropertyRefExpr *pre
13372         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13373                                               ->IgnoreParens());
13374       if (!pre) return false;
13375       if (pre->isImplicitProperty()) return false;
13376       ObjCPropertyDecl *property = pre->getExplicitProperty();
13377       if (!property->isRetaining() &&
13378           !(property->getPropertyIvarDecl() &&
13379             property->getPropertyIvarDecl()->getType()
13380               .getObjCLifetime() == Qualifiers::OCL_Strong))
13381           return false;
13382 
13383       owner.Indirect = true;
13384       if (pre->isSuperReceiver()) {
13385         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13386         if (!owner.Variable)
13387           return false;
13388         owner.Loc = pre->getLocation();
13389         owner.Range = pre->getSourceRange();
13390         return true;
13391       }
13392       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13393                               ->getSourceExpr());
13394       continue;
13395     }
13396 
13397     // Array ivars?
13398 
13399     return false;
13400   }
13401 }
13402 
13403 namespace {
13404 
13405   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13406     ASTContext &Context;
13407     VarDecl *Variable;
13408     Expr *Capturer = nullptr;
13409     bool VarWillBeReased = false;
13410 
13411     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13412         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13413           Context(Context), Variable(variable) {}
13414 
13415     void VisitDeclRefExpr(DeclRefExpr *ref) {
13416       if (ref->getDecl() == Variable && !Capturer)
13417         Capturer = ref;
13418     }
13419 
13420     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13421       if (Capturer) return;
13422       Visit(ref->getBase());
13423       if (Capturer && ref->isFreeIvar())
13424         Capturer = ref;
13425     }
13426 
13427     void VisitBlockExpr(BlockExpr *block) {
13428       // Look inside nested blocks
13429       if (block->getBlockDecl()->capturesVariable(Variable))
13430         Visit(block->getBlockDecl()->getBody());
13431     }
13432 
13433     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13434       if (Capturer) return;
13435       if (OVE->getSourceExpr())
13436         Visit(OVE->getSourceExpr());
13437     }
13438 
13439     void VisitBinaryOperator(BinaryOperator *BinOp) {
13440       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13441         return;
13442       Expr *LHS = BinOp->getLHS();
13443       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13444         if (DRE->getDecl() != Variable)
13445           return;
13446         if (Expr *RHS = BinOp->getRHS()) {
13447           RHS = RHS->IgnoreParenCasts();
13448           llvm::APSInt Value;
13449           VarWillBeReased =
13450             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13451         }
13452       }
13453     }
13454   };
13455 
13456 } // namespace
13457 
13458 /// Check whether the given argument is a block which captures a
13459 /// variable.
13460 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13461   assert(owner.Variable && owner.Loc.isValid());
13462 
13463   e = e->IgnoreParenCasts();
13464 
13465   // Look through [^{...} copy] and Block_copy(^{...}).
13466   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13467     Selector Cmd = ME->getSelector();
13468     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13469       e = ME->getInstanceReceiver();
13470       if (!e)
13471         return nullptr;
13472       e = e->IgnoreParenCasts();
13473     }
13474   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13475     if (CE->getNumArgs() == 1) {
13476       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13477       if (Fn) {
13478         const IdentifierInfo *FnI = Fn->getIdentifier();
13479         if (FnI && FnI->isStr("_Block_copy")) {
13480           e = CE->getArg(0)->IgnoreParenCasts();
13481         }
13482       }
13483     }
13484   }
13485 
13486   BlockExpr *block = dyn_cast<BlockExpr>(e);
13487   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13488     return nullptr;
13489 
13490   FindCaptureVisitor visitor(S.Context, owner.Variable);
13491   visitor.Visit(block->getBlockDecl()->getBody());
13492   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13493 }
13494 
13495 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13496                                 RetainCycleOwner &owner) {
13497   assert(capturer);
13498   assert(owner.Variable && owner.Loc.isValid());
13499 
13500   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13501     << owner.Variable << capturer->getSourceRange();
13502   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13503     << owner.Indirect << owner.Range;
13504 }
13505 
13506 /// Check for a keyword selector that starts with the word 'add' or
13507 /// 'set'.
13508 static bool isSetterLikeSelector(Selector sel) {
13509   if (sel.isUnarySelector()) return false;
13510 
13511   StringRef str = sel.getNameForSlot(0);
13512   while (!str.empty() && str.front() == '_') str = str.substr(1);
13513   if (str.startswith("set"))
13514     str = str.substr(3);
13515   else if (str.startswith("add")) {
13516     // Specially whitelist 'addOperationWithBlock:'.
13517     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13518       return false;
13519     str = str.substr(3);
13520   }
13521   else
13522     return false;
13523 
13524   if (str.empty()) return true;
13525   return !isLowercase(str.front());
13526 }
13527 
13528 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13529                                                     ObjCMessageExpr *Message) {
13530   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13531                                                 Message->getReceiverInterface(),
13532                                                 NSAPI::ClassId_NSMutableArray);
13533   if (!IsMutableArray) {
13534     return None;
13535   }
13536 
13537   Selector Sel = Message->getSelector();
13538 
13539   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13540     S.NSAPIObj->getNSArrayMethodKind(Sel);
13541   if (!MKOpt) {
13542     return None;
13543   }
13544 
13545   NSAPI::NSArrayMethodKind MK = *MKOpt;
13546 
13547   switch (MK) {
13548     case NSAPI::NSMutableArr_addObject:
13549     case NSAPI::NSMutableArr_insertObjectAtIndex:
13550     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13551       return 0;
13552     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13553       return 1;
13554 
13555     default:
13556       return None;
13557   }
13558 
13559   return None;
13560 }
13561 
13562 static
13563 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13564                                                   ObjCMessageExpr *Message) {
13565   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13566                                             Message->getReceiverInterface(),
13567                                             NSAPI::ClassId_NSMutableDictionary);
13568   if (!IsMutableDictionary) {
13569     return None;
13570   }
13571 
13572   Selector Sel = Message->getSelector();
13573 
13574   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13575     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13576   if (!MKOpt) {
13577     return None;
13578   }
13579 
13580   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13581 
13582   switch (MK) {
13583     case NSAPI::NSMutableDict_setObjectForKey:
13584     case NSAPI::NSMutableDict_setValueForKey:
13585     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13586       return 0;
13587 
13588     default:
13589       return None;
13590   }
13591 
13592   return None;
13593 }
13594 
13595 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13596   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13597                                                 Message->getReceiverInterface(),
13598                                                 NSAPI::ClassId_NSMutableSet);
13599 
13600   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13601                                             Message->getReceiverInterface(),
13602                                             NSAPI::ClassId_NSMutableOrderedSet);
13603   if (!IsMutableSet && !IsMutableOrderedSet) {
13604     return None;
13605   }
13606 
13607   Selector Sel = Message->getSelector();
13608 
13609   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13610   if (!MKOpt) {
13611     return None;
13612   }
13613 
13614   NSAPI::NSSetMethodKind MK = *MKOpt;
13615 
13616   switch (MK) {
13617     case NSAPI::NSMutableSet_addObject:
13618     case NSAPI::NSOrderedSet_setObjectAtIndex:
13619     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13620     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13621       return 0;
13622     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13623       return 1;
13624   }
13625 
13626   return None;
13627 }
13628 
13629 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13630   if (!Message->isInstanceMessage()) {
13631     return;
13632   }
13633 
13634   Optional<int> ArgOpt;
13635 
13636   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13637       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13638       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13639     return;
13640   }
13641 
13642   int ArgIndex = *ArgOpt;
13643 
13644   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13645   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13646     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13647   }
13648 
13649   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13650     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13651       if (ArgRE->isObjCSelfExpr()) {
13652         Diag(Message->getSourceRange().getBegin(),
13653              diag::warn_objc_circular_container)
13654           << ArgRE->getDecl() << StringRef("'super'");
13655       }
13656     }
13657   } else {
13658     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13659 
13660     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13661       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13662     }
13663 
13664     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13665       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13666         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13667           ValueDecl *Decl = ReceiverRE->getDecl();
13668           Diag(Message->getSourceRange().getBegin(),
13669                diag::warn_objc_circular_container)
13670             << Decl << Decl;
13671           if (!ArgRE->isObjCSelfExpr()) {
13672             Diag(Decl->getLocation(),
13673                  diag::note_objc_circular_container_declared_here)
13674               << Decl;
13675           }
13676         }
13677       }
13678     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13679       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13680         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13681           ObjCIvarDecl *Decl = IvarRE->getDecl();
13682           Diag(Message->getSourceRange().getBegin(),
13683                diag::warn_objc_circular_container)
13684             << Decl << Decl;
13685           Diag(Decl->getLocation(),
13686                diag::note_objc_circular_container_declared_here)
13687             << Decl;
13688         }
13689       }
13690     }
13691   }
13692 }
13693 
13694 /// Check a message send to see if it's likely to cause a retain cycle.
13695 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13696   // Only check instance methods whose selector looks like a setter.
13697   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13698     return;
13699 
13700   // Try to find a variable that the receiver is strongly owned by.
13701   RetainCycleOwner owner;
13702   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13703     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13704       return;
13705   } else {
13706     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13707     owner.Variable = getCurMethodDecl()->getSelfDecl();
13708     owner.Loc = msg->getSuperLoc();
13709     owner.Range = msg->getSuperLoc();
13710   }
13711 
13712   // Check whether the receiver is captured by any of the arguments.
13713   const ObjCMethodDecl *MD = msg->getMethodDecl();
13714   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13715     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13716       // noescape blocks should not be retained by the method.
13717       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13718         continue;
13719       return diagnoseRetainCycle(*this, capturer, owner);
13720     }
13721   }
13722 }
13723 
13724 /// Check a property assign to see if it's likely to cause a retain cycle.
13725 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13726   RetainCycleOwner owner;
13727   if (!findRetainCycleOwner(*this, receiver, owner))
13728     return;
13729 
13730   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13731     diagnoseRetainCycle(*this, capturer, owner);
13732 }
13733 
13734 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13735   RetainCycleOwner Owner;
13736   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13737     return;
13738 
13739   // Because we don't have an expression for the variable, we have to set the
13740   // location explicitly here.
13741   Owner.Loc = Var->getLocation();
13742   Owner.Range = Var->getSourceRange();
13743 
13744   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13745     diagnoseRetainCycle(*this, Capturer, Owner);
13746 }
13747 
13748 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13749                                      Expr *RHS, bool isProperty) {
13750   // Check if RHS is an Objective-C object literal, which also can get
13751   // immediately zapped in a weak reference.  Note that we explicitly
13752   // allow ObjCStringLiterals, since those are designed to never really die.
13753   RHS = RHS->IgnoreParenImpCasts();
13754 
13755   // This enum needs to match with the 'select' in
13756   // warn_objc_arc_literal_assign (off-by-1).
13757   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13758   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13759     return false;
13760 
13761   S.Diag(Loc, diag::warn_arc_literal_assign)
13762     << (unsigned) Kind
13763     << (isProperty ? 0 : 1)
13764     << RHS->getSourceRange();
13765 
13766   return true;
13767 }
13768 
13769 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13770                                     Qualifiers::ObjCLifetime LT,
13771                                     Expr *RHS, bool isProperty) {
13772   // Strip off any implicit cast added to get to the one ARC-specific.
13773   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13774     if (cast->getCastKind() == CK_ARCConsumeObject) {
13775       S.Diag(Loc, diag::warn_arc_retained_assign)
13776         << (LT == Qualifiers::OCL_ExplicitNone)
13777         << (isProperty ? 0 : 1)
13778         << RHS->getSourceRange();
13779       return true;
13780     }
13781     RHS = cast->getSubExpr();
13782   }
13783 
13784   if (LT == Qualifiers::OCL_Weak &&
13785       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13786     return true;
13787 
13788   return false;
13789 }
13790 
13791 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13792                               QualType LHS, Expr *RHS) {
13793   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13794 
13795   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13796     return false;
13797 
13798   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13799     return true;
13800 
13801   return false;
13802 }
13803 
13804 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13805                               Expr *LHS, Expr *RHS) {
13806   QualType LHSType;
13807   // PropertyRef on LHS type need be directly obtained from
13808   // its declaration as it has a PseudoType.
13809   ObjCPropertyRefExpr *PRE
13810     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13811   if (PRE && !PRE->isImplicitProperty()) {
13812     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13813     if (PD)
13814       LHSType = PD->getType();
13815   }
13816 
13817   if (LHSType.isNull())
13818     LHSType = LHS->getType();
13819 
13820   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13821 
13822   if (LT == Qualifiers::OCL_Weak) {
13823     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13824       getCurFunction()->markSafeWeakUse(LHS);
13825   }
13826 
13827   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13828     return;
13829 
13830   // FIXME. Check for other life times.
13831   if (LT != Qualifiers::OCL_None)
13832     return;
13833 
13834   if (PRE) {
13835     if (PRE->isImplicitProperty())
13836       return;
13837     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13838     if (!PD)
13839       return;
13840 
13841     unsigned Attributes = PD->getPropertyAttributes();
13842     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13843       // when 'assign' attribute was not explicitly specified
13844       // by user, ignore it and rely on property type itself
13845       // for lifetime info.
13846       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13847       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13848           LHSType->isObjCRetainableType())
13849         return;
13850 
13851       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13852         if (cast->getCastKind() == CK_ARCConsumeObject) {
13853           Diag(Loc, diag::warn_arc_retained_property_assign)
13854           << RHS->getSourceRange();
13855           return;
13856         }
13857         RHS = cast->getSubExpr();
13858       }
13859     }
13860     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13861       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13862         return;
13863     }
13864   }
13865 }
13866 
13867 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13868 
13869 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13870                                         SourceLocation StmtLoc,
13871                                         const NullStmt *Body) {
13872   // Do not warn if the body is a macro that expands to nothing, e.g:
13873   //
13874   // #define CALL(x)
13875   // if (condition)
13876   //   CALL(0);
13877   if (Body->hasLeadingEmptyMacro())
13878     return false;
13879 
13880   // Get line numbers of statement and body.
13881   bool StmtLineInvalid;
13882   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13883                                                       &StmtLineInvalid);
13884   if (StmtLineInvalid)
13885     return false;
13886 
13887   bool BodyLineInvalid;
13888   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13889                                                       &BodyLineInvalid);
13890   if (BodyLineInvalid)
13891     return false;
13892 
13893   // Warn if null statement and body are on the same line.
13894   if (StmtLine != BodyLine)
13895     return false;
13896 
13897   return true;
13898 }
13899 
13900 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13901                                  const Stmt *Body,
13902                                  unsigned DiagID) {
13903   // Since this is a syntactic check, don't emit diagnostic for template
13904   // instantiations, this just adds noise.
13905   if (CurrentInstantiationScope)
13906     return;
13907 
13908   // The body should be a null statement.
13909   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13910   if (!NBody)
13911     return;
13912 
13913   // Do the usual checks.
13914   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13915     return;
13916 
13917   Diag(NBody->getSemiLoc(), DiagID);
13918   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13919 }
13920 
13921 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13922                                  const Stmt *PossibleBody) {
13923   assert(!CurrentInstantiationScope); // Ensured by caller
13924 
13925   SourceLocation StmtLoc;
13926   const Stmt *Body;
13927   unsigned DiagID;
13928   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13929     StmtLoc = FS->getRParenLoc();
13930     Body = FS->getBody();
13931     DiagID = diag::warn_empty_for_body;
13932   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13933     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13934     Body = WS->getBody();
13935     DiagID = diag::warn_empty_while_body;
13936   } else
13937     return; // Neither `for' nor `while'.
13938 
13939   // The body should be a null statement.
13940   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13941   if (!NBody)
13942     return;
13943 
13944   // Skip expensive checks if diagnostic is disabled.
13945   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13946     return;
13947 
13948   // Do the usual checks.
13949   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13950     return;
13951 
13952   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13953   // noise level low, emit diagnostics only if for/while is followed by a
13954   // CompoundStmt, e.g.:
13955   //    for (int i = 0; i < n; i++);
13956   //    {
13957   //      a(i);
13958   //    }
13959   // or if for/while is followed by a statement with more indentation
13960   // than for/while itself:
13961   //    for (int i = 0; i < n; i++);
13962   //      a(i);
13963   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13964   if (!ProbableTypo) {
13965     bool BodyColInvalid;
13966     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13967         PossibleBody->getBeginLoc(), &BodyColInvalid);
13968     if (BodyColInvalid)
13969       return;
13970 
13971     bool StmtColInvalid;
13972     unsigned StmtCol =
13973         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13974     if (StmtColInvalid)
13975       return;
13976 
13977     if (BodyCol > StmtCol)
13978       ProbableTypo = true;
13979   }
13980 
13981   if (ProbableTypo) {
13982     Diag(NBody->getSemiLoc(), DiagID);
13983     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13984   }
13985 }
13986 
13987 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13988 
13989 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13990 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13991                              SourceLocation OpLoc) {
13992   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13993     return;
13994 
13995   if (inTemplateInstantiation())
13996     return;
13997 
13998   // Strip parens and casts away.
13999   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14000   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14001 
14002   // Check for a call expression
14003   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14004   if (!CE || CE->getNumArgs() != 1)
14005     return;
14006 
14007   // Check for a call to std::move
14008   if (!CE->isCallToStdMove())
14009     return;
14010 
14011   // Get argument from std::move
14012   RHSExpr = CE->getArg(0);
14013 
14014   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14015   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14016 
14017   // Two DeclRefExpr's, check that the decls are the same.
14018   if (LHSDeclRef && RHSDeclRef) {
14019     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14020       return;
14021     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14022         RHSDeclRef->getDecl()->getCanonicalDecl())
14023       return;
14024 
14025     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14026                                         << LHSExpr->getSourceRange()
14027                                         << RHSExpr->getSourceRange();
14028     return;
14029   }
14030 
14031   // Member variables require a different approach to check for self moves.
14032   // MemberExpr's are the same if every nested MemberExpr refers to the same
14033   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14034   // the base Expr's are CXXThisExpr's.
14035   const Expr *LHSBase = LHSExpr;
14036   const Expr *RHSBase = RHSExpr;
14037   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14038   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14039   if (!LHSME || !RHSME)
14040     return;
14041 
14042   while (LHSME && RHSME) {
14043     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14044         RHSME->getMemberDecl()->getCanonicalDecl())
14045       return;
14046 
14047     LHSBase = LHSME->getBase();
14048     RHSBase = RHSME->getBase();
14049     LHSME = dyn_cast<MemberExpr>(LHSBase);
14050     RHSME = dyn_cast<MemberExpr>(RHSBase);
14051   }
14052 
14053   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14054   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14055   if (LHSDeclRef && RHSDeclRef) {
14056     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14057       return;
14058     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14059         RHSDeclRef->getDecl()->getCanonicalDecl())
14060       return;
14061 
14062     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14063                                         << LHSExpr->getSourceRange()
14064                                         << RHSExpr->getSourceRange();
14065     return;
14066   }
14067 
14068   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14069     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14070                                         << LHSExpr->getSourceRange()
14071                                         << RHSExpr->getSourceRange();
14072 }
14073 
14074 //===--- Layout compatibility ----------------------------------------------//
14075 
14076 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14077 
14078 /// Check if two enumeration types are layout-compatible.
14079 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14080   // C++11 [dcl.enum] p8:
14081   // Two enumeration types are layout-compatible if they have the same
14082   // underlying type.
14083   return ED1->isComplete() && ED2->isComplete() &&
14084          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14085 }
14086 
14087 /// Check if two fields are layout-compatible.
14088 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14089                                FieldDecl *Field2) {
14090   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14091     return false;
14092 
14093   if (Field1->isBitField() != Field2->isBitField())
14094     return false;
14095 
14096   if (Field1->isBitField()) {
14097     // Make sure that the bit-fields are the same length.
14098     unsigned Bits1 = Field1->getBitWidthValue(C);
14099     unsigned Bits2 = Field2->getBitWidthValue(C);
14100 
14101     if (Bits1 != Bits2)
14102       return false;
14103   }
14104 
14105   return true;
14106 }
14107 
14108 /// Check if two standard-layout structs are layout-compatible.
14109 /// (C++11 [class.mem] p17)
14110 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14111                                      RecordDecl *RD2) {
14112   // If both records are C++ classes, check that base classes match.
14113   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14114     // If one of records is a CXXRecordDecl we are in C++ mode,
14115     // thus the other one is a CXXRecordDecl, too.
14116     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14117     // Check number of base classes.
14118     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14119       return false;
14120 
14121     // Check the base classes.
14122     for (CXXRecordDecl::base_class_const_iterator
14123                Base1 = D1CXX->bases_begin(),
14124            BaseEnd1 = D1CXX->bases_end(),
14125               Base2 = D2CXX->bases_begin();
14126          Base1 != BaseEnd1;
14127          ++Base1, ++Base2) {
14128       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14129         return false;
14130     }
14131   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14132     // If only RD2 is a C++ class, it should have zero base classes.
14133     if (D2CXX->getNumBases() > 0)
14134       return false;
14135   }
14136 
14137   // Check the fields.
14138   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14139                              Field2End = RD2->field_end(),
14140                              Field1 = RD1->field_begin(),
14141                              Field1End = RD1->field_end();
14142   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14143     if (!isLayoutCompatible(C, *Field1, *Field2))
14144       return false;
14145   }
14146   if (Field1 != Field1End || Field2 != Field2End)
14147     return false;
14148 
14149   return true;
14150 }
14151 
14152 /// Check if two standard-layout unions are layout-compatible.
14153 /// (C++11 [class.mem] p18)
14154 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14155                                     RecordDecl *RD2) {
14156   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14157   for (auto *Field2 : RD2->fields())
14158     UnmatchedFields.insert(Field2);
14159 
14160   for (auto *Field1 : RD1->fields()) {
14161     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14162         I = UnmatchedFields.begin(),
14163         E = UnmatchedFields.end();
14164 
14165     for ( ; I != E; ++I) {
14166       if (isLayoutCompatible(C, Field1, *I)) {
14167         bool Result = UnmatchedFields.erase(*I);
14168         (void) Result;
14169         assert(Result);
14170         break;
14171       }
14172     }
14173     if (I == E)
14174       return false;
14175   }
14176 
14177   return UnmatchedFields.empty();
14178 }
14179 
14180 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14181                                RecordDecl *RD2) {
14182   if (RD1->isUnion() != RD2->isUnion())
14183     return false;
14184 
14185   if (RD1->isUnion())
14186     return isLayoutCompatibleUnion(C, RD1, RD2);
14187   else
14188     return isLayoutCompatibleStruct(C, RD1, RD2);
14189 }
14190 
14191 /// Check if two types are layout-compatible in C++11 sense.
14192 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14193   if (T1.isNull() || T2.isNull())
14194     return false;
14195 
14196   // C++11 [basic.types] p11:
14197   // If two types T1 and T2 are the same type, then T1 and T2 are
14198   // layout-compatible types.
14199   if (C.hasSameType(T1, T2))
14200     return true;
14201 
14202   T1 = T1.getCanonicalType().getUnqualifiedType();
14203   T2 = T2.getCanonicalType().getUnqualifiedType();
14204 
14205   const Type::TypeClass TC1 = T1->getTypeClass();
14206   const Type::TypeClass TC2 = T2->getTypeClass();
14207 
14208   if (TC1 != TC2)
14209     return false;
14210 
14211   if (TC1 == Type::Enum) {
14212     return isLayoutCompatible(C,
14213                               cast<EnumType>(T1)->getDecl(),
14214                               cast<EnumType>(T2)->getDecl());
14215   } else if (TC1 == Type::Record) {
14216     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14217       return false;
14218 
14219     return isLayoutCompatible(C,
14220                               cast<RecordType>(T1)->getDecl(),
14221                               cast<RecordType>(T2)->getDecl());
14222   }
14223 
14224   return false;
14225 }
14226 
14227 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14228 
14229 /// Given a type tag expression find the type tag itself.
14230 ///
14231 /// \param TypeExpr Type tag expression, as it appears in user's code.
14232 ///
14233 /// \param VD Declaration of an identifier that appears in a type tag.
14234 ///
14235 /// \param MagicValue Type tag magic value.
14236 ///
14237 /// \param isConstantEvaluated wether the evalaution should be performed in
14238 
14239 /// constant context.
14240 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14241                             const ValueDecl **VD, uint64_t *MagicValue,
14242                             bool isConstantEvaluated) {
14243   while(true) {
14244     if (!TypeExpr)
14245       return false;
14246 
14247     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14248 
14249     switch (TypeExpr->getStmtClass()) {
14250     case Stmt::UnaryOperatorClass: {
14251       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14252       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14253         TypeExpr = UO->getSubExpr();
14254         continue;
14255       }
14256       return false;
14257     }
14258 
14259     case Stmt::DeclRefExprClass: {
14260       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14261       *VD = DRE->getDecl();
14262       return true;
14263     }
14264 
14265     case Stmt::IntegerLiteralClass: {
14266       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14267       llvm::APInt MagicValueAPInt = IL->getValue();
14268       if (MagicValueAPInt.getActiveBits() <= 64) {
14269         *MagicValue = MagicValueAPInt.getZExtValue();
14270         return true;
14271       } else
14272         return false;
14273     }
14274 
14275     case Stmt::BinaryConditionalOperatorClass:
14276     case Stmt::ConditionalOperatorClass: {
14277       const AbstractConditionalOperator *ACO =
14278           cast<AbstractConditionalOperator>(TypeExpr);
14279       bool Result;
14280       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14281                                                      isConstantEvaluated)) {
14282         if (Result)
14283           TypeExpr = ACO->getTrueExpr();
14284         else
14285           TypeExpr = ACO->getFalseExpr();
14286         continue;
14287       }
14288       return false;
14289     }
14290 
14291     case Stmt::BinaryOperatorClass: {
14292       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14293       if (BO->getOpcode() == BO_Comma) {
14294         TypeExpr = BO->getRHS();
14295         continue;
14296       }
14297       return false;
14298     }
14299 
14300     default:
14301       return false;
14302     }
14303   }
14304 }
14305 
14306 /// Retrieve the C type corresponding to type tag TypeExpr.
14307 ///
14308 /// \param TypeExpr Expression that specifies a type tag.
14309 ///
14310 /// \param MagicValues Registered magic values.
14311 ///
14312 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14313 ///        kind.
14314 ///
14315 /// \param TypeInfo Information about the corresponding C type.
14316 ///
14317 /// \param isConstantEvaluated wether the evalaution should be performed in
14318 /// constant context.
14319 ///
14320 /// \returns true if the corresponding C type was found.
14321 static bool GetMatchingCType(
14322     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14323     const ASTContext &Ctx,
14324     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14325         *MagicValues,
14326     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14327     bool isConstantEvaluated) {
14328   FoundWrongKind = false;
14329 
14330   // Variable declaration that has type_tag_for_datatype attribute.
14331   const ValueDecl *VD = nullptr;
14332 
14333   uint64_t MagicValue;
14334 
14335   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14336     return false;
14337 
14338   if (VD) {
14339     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14340       if (I->getArgumentKind() != ArgumentKind) {
14341         FoundWrongKind = true;
14342         return false;
14343       }
14344       TypeInfo.Type = I->getMatchingCType();
14345       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14346       TypeInfo.MustBeNull = I->getMustBeNull();
14347       return true;
14348     }
14349     return false;
14350   }
14351 
14352   if (!MagicValues)
14353     return false;
14354 
14355   llvm::DenseMap<Sema::TypeTagMagicValue,
14356                  Sema::TypeTagData>::const_iterator I =
14357       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14358   if (I == MagicValues->end())
14359     return false;
14360 
14361   TypeInfo = I->second;
14362   return true;
14363 }
14364 
14365 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14366                                       uint64_t MagicValue, QualType Type,
14367                                       bool LayoutCompatible,
14368                                       bool MustBeNull) {
14369   if (!TypeTagForDatatypeMagicValues)
14370     TypeTagForDatatypeMagicValues.reset(
14371         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14372 
14373   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14374   (*TypeTagForDatatypeMagicValues)[Magic] =
14375       TypeTagData(Type, LayoutCompatible, MustBeNull);
14376 }
14377 
14378 static bool IsSameCharType(QualType T1, QualType T2) {
14379   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14380   if (!BT1)
14381     return false;
14382 
14383   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14384   if (!BT2)
14385     return false;
14386 
14387   BuiltinType::Kind T1Kind = BT1->getKind();
14388   BuiltinType::Kind T2Kind = BT2->getKind();
14389 
14390   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14391          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14392          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14393          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14394 }
14395 
14396 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14397                                     const ArrayRef<const Expr *> ExprArgs,
14398                                     SourceLocation CallSiteLoc) {
14399   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14400   bool IsPointerAttr = Attr->getIsPointer();
14401 
14402   // Retrieve the argument representing the 'type_tag'.
14403   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14404   if (TypeTagIdxAST >= ExprArgs.size()) {
14405     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14406         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14407     return;
14408   }
14409   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14410   bool FoundWrongKind;
14411   TypeTagData TypeInfo;
14412   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14413                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14414                         TypeInfo, isConstantEvaluated())) {
14415     if (FoundWrongKind)
14416       Diag(TypeTagExpr->getExprLoc(),
14417            diag::warn_type_tag_for_datatype_wrong_kind)
14418         << TypeTagExpr->getSourceRange();
14419     return;
14420   }
14421 
14422   // Retrieve the argument representing the 'arg_idx'.
14423   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14424   if (ArgumentIdxAST >= ExprArgs.size()) {
14425     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14426         << 1 << Attr->getArgumentIdx().getSourceIndex();
14427     return;
14428   }
14429   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14430   if (IsPointerAttr) {
14431     // Skip implicit cast of pointer to `void *' (as a function argument).
14432     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14433       if (ICE->getType()->isVoidPointerType() &&
14434           ICE->getCastKind() == CK_BitCast)
14435         ArgumentExpr = ICE->getSubExpr();
14436   }
14437   QualType ArgumentType = ArgumentExpr->getType();
14438 
14439   // Passing a `void*' pointer shouldn't trigger a warning.
14440   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14441     return;
14442 
14443   if (TypeInfo.MustBeNull) {
14444     // Type tag with matching void type requires a null pointer.
14445     if (!ArgumentExpr->isNullPointerConstant(Context,
14446                                              Expr::NPC_ValueDependentIsNotNull)) {
14447       Diag(ArgumentExpr->getExprLoc(),
14448            diag::warn_type_safety_null_pointer_required)
14449           << ArgumentKind->getName()
14450           << ArgumentExpr->getSourceRange()
14451           << TypeTagExpr->getSourceRange();
14452     }
14453     return;
14454   }
14455 
14456   QualType RequiredType = TypeInfo.Type;
14457   if (IsPointerAttr)
14458     RequiredType = Context.getPointerType(RequiredType);
14459 
14460   bool mismatch = false;
14461   if (!TypeInfo.LayoutCompatible) {
14462     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14463 
14464     // C++11 [basic.fundamental] p1:
14465     // Plain char, signed char, and unsigned char are three distinct types.
14466     //
14467     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14468     // char' depending on the current char signedness mode.
14469     if (mismatch)
14470       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14471                                            RequiredType->getPointeeType())) ||
14472           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14473         mismatch = false;
14474   } else
14475     if (IsPointerAttr)
14476       mismatch = !isLayoutCompatible(Context,
14477                                      ArgumentType->getPointeeType(),
14478                                      RequiredType->getPointeeType());
14479     else
14480       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14481 
14482   if (mismatch)
14483     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14484         << ArgumentType << ArgumentKind
14485         << TypeInfo.LayoutCompatible << RequiredType
14486         << ArgumentExpr->getSourceRange()
14487         << TypeTagExpr->getSourceRange();
14488 }
14489 
14490 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14491                                          CharUnits Alignment) {
14492   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14493 }
14494 
14495 void Sema::DiagnoseMisalignedMembers() {
14496   for (MisalignedMember &m : MisalignedMembers) {
14497     const NamedDecl *ND = m.RD;
14498     if (ND->getName().empty()) {
14499       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14500         ND = TD;
14501     }
14502     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14503         << m.MD << ND << m.E->getSourceRange();
14504   }
14505   MisalignedMembers.clear();
14506 }
14507 
14508 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14509   E = E->IgnoreParens();
14510   if (!T->isPointerType() && !T->isIntegerType())
14511     return;
14512   if (isa<UnaryOperator>(E) &&
14513       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14514     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14515     if (isa<MemberExpr>(Op)) {
14516       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14517       if (MA != MisalignedMembers.end() &&
14518           (T->isIntegerType() ||
14519            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14520                                    Context.getTypeAlignInChars(
14521                                        T->getPointeeType()) <= MA->Alignment))))
14522         MisalignedMembers.erase(MA);
14523     }
14524   }
14525 }
14526 
14527 void Sema::RefersToMemberWithReducedAlignment(
14528     Expr *E,
14529     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14530         Action) {
14531   const auto *ME = dyn_cast<MemberExpr>(E);
14532   if (!ME)
14533     return;
14534 
14535   // No need to check expressions with an __unaligned-qualified type.
14536   if (E->getType().getQualifiers().hasUnaligned())
14537     return;
14538 
14539   // For a chain of MemberExpr like "a.b.c.d" this list
14540   // will keep FieldDecl's like [d, c, b].
14541   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14542   const MemberExpr *TopME = nullptr;
14543   bool AnyIsPacked = false;
14544   do {
14545     QualType BaseType = ME->getBase()->getType();
14546     if (BaseType->isDependentType())
14547       return;
14548     if (ME->isArrow())
14549       BaseType = BaseType->getPointeeType();
14550     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14551     if (RD->isInvalidDecl())
14552       return;
14553 
14554     ValueDecl *MD = ME->getMemberDecl();
14555     auto *FD = dyn_cast<FieldDecl>(MD);
14556     // We do not care about non-data members.
14557     if (!FD || FD->isInvalidDecl())
14558       return;
14559 
14560     AnyIsPacked =
14561         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14562     ReverseMemberChain.push_back(FD);
14563 
14564     TopME = ME;
14565     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14566   } while (ME);
14567   assert(TopME && "We did not compute a topmost MemberExpr!");
14568 
14569   // Not the scope of this diagnostic.
14570   if (!AnyIsPacked)
14571     return;
14572 
14573   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14574   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14575   // TODO: The innermost base of the member expression may be too complicated.
14576   // For now, just disregard these cases. This is left for future
14577   // improvement.
14578   if (!DRE && !isa<CXXThisExpr>(TopBase))
14579       return;
14580 
14581   // Alignment expected by the whole expression.
14582   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14583 
14584   // No need to do anything else with this case.
14585   if (ExpectedAlignment.isOne())
14586     return;
14587 
14588   // Synthesize offset of the whole access.
14589   CharUnits Offset;
14590   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14591        I++) {
14592     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14593   }
14594 
14595   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14596   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14597       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14598 
14599   // The base expression of the innermost MemberExpr may give
14600   // stronger guarantees than the class containing the member.
14601   if (DRE && !TopME->isArrow()) {
14602     const ValueDecl *VD = DRE->getDecl();
14603     if (!VD->getType()->isReferenceType())
14604       CompleteObjectAlignment =
14605           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14606   }
14607 
14608   // Check if the synthesized offset fulfills the alignment.
14609   if (Offset % ExpectedAlignment != 0 ||
14610       // It may fulfill the offset it but the effective alignment may still be
14611       // lower than the expected expression alignment.
14612       CompleteObjectAlignment < ExpectedAlignment) {
14613     // If this happens, we want to determine a sensible culprit of this.
14614     // Intuitively, watching the chain of member expressions from right to
14615     // left, we start with the required alignment (as required by the field
14616     // type) but some packed attribute in that chain has reduced the alignment.
14617     // It may happen that another packed structure increases it again. But if
14618     // we are here such increase has not been enough. So pointing the first
14619     // FieldDecl that either is packed or else its RecordDecl is,
14620     // seems reasonable.
14621     FieldDecl *FD = nullptr;
14622     CharUnits Alignment;
14623     for (FieldDecl *FDI : ReverseMemberChain) {
14624       if (FDI->hasAttr<PackedAttr>() ||
14625           FDI->getParent()->hasAttr<PackedAttr>()) {
14626         FD = FDI;
14627         Alignment = std::min(
14628             Context.getTypeAlignInChars(FD->getType()),
14629             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14630         break;
14631       }
14632     }
14633     assert(FD && "We did not find a packed FieldDecl!");
14634     Action(E, FD->getParent(), FD, Alignment);
14635   }
14636 }
14637 
14638 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14639   using namespace std::placeholders;
14640 
14641   RefersToMemberWithReducedAlignment(
14642       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14643                      _2, _3, _4));
14644 }
14645