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/raw_ostream.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstddef>
91 #include <cstdint>
92 #include <functional>
93 #include <limits>
94 #include <string>
95 #include <tuple>
96 #include <utility>
97 
98 using namespace clang;
99 using namespace sema;
100 
101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102                                                     unsigned ByteNo) const {
103   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104                                Context.getTargetInfo());
105 }
106 
107 /// Checks that a call expression's argument count is the desired number.
108 /// This is useful when doing custom type-checking.  Returns true on error.
109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110   unsigned argCount = call->getNumArgs();
111   if (argCount == desiredArgCount) return false;
112 
113   if (argCount < desiredArgCount)
114     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
115            << 0 /*function call*/ << desiredArgCount << argCount
116            << call->getSourceRange();
117 
118   // Highlight all the excess arguments.
119   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
120                     call->getArg(argCount - 1)->getEndLoc());
121 
122   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123     << 0 /*function call*/ << desiredArgCount << argCount
124     << call->getArg(1)->getSourceRange();
125 }
126 
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130   if (checkArgCount(S, TheCall, 2))
131     return true;
132 
133   // First argument should be an integer.
134   Expr *ValArg = TheCall->getArg(0);
135   QualType Ty = ValArg->getType();
136   if (!Ty->isIntegerType()) {
137     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
138         << ValArg->getSourceRange();
139     return true;
140   }
141 
142   // Second argument should be a constant string.
143   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145   if (!Literal || !Literal->isAscii()) {
146     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
147         << StrArg->getSourceRange();
148     return true;
149   }
150 
151   TheCall->setType(Ty);
152   return false;
153 }
154 
155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156   // We need at least one argument.
157   if (TheCall->getNumArgs() < 1) {
158     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
159         << 0 << 1 << TheCall->getNumArgs()
160         << TheCall->getCallee()->getSourceRange();
161     return true;
162   }
163 
164   // All arguments should be wide string literals.
165   for (Expr *Arg : TheCall->arguments()) {
166     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167     if (!Literal || !Literal->isWide()) {
168       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
169           << Arg->getSourceRange();
170       return true;
171     }
172   }
173 
174   return false;
175 }
176 
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180   if (checkArgCount(S, TheCall, 1))
181     return true;
182 
183   ExprResult Arg(TheCall->getArg(0));
184   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
185   if (ResultType.isNull())
186     return true;
187 
188   TheCall->setArg(0, Arg.get());
189   TheCall->setType(ResultType);
190   return false;
191 }
192 
193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194   if (checkArgCount(S, TheCall, 3))
195     return true;
196 
197   // First two arguments should be integers.
198   for (unsigned I = 0; I < 2; ++I) {
199     ExprResult Arg = TheCall->getArg(I);
200     QualType Ty = Arg.get()->getType();
201     if (!Ty->isIntegerType()) {
202       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
203           << Ty << Arg.get()->getSourceRange();
204       return true;
205     }
206     InitializedEntity Entity = InitializedEntity::InitializeParameter(
207         S.getASTContext(), Ty, /*consume*/ false);
208     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
209     if (Arg.isInvalid())
210       return true;
211     TheCall->setArg(I, Arg.get());
212   }
213 
214   // Third argument should be a pointer to a non-const integer.
215   // IRGen correctly handles volatile, restrict, and address spaces, and
216   // the other qualifiers aren't possible.
217   {
218     ExprResult Arg = TheCall->getArg(2);
219     QualType Ty = Arg.get()->getType();
220     const auto *PtrTy = Ty->getAs<PointerType>();
221     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
222           !PtrTy->getPointeeType().isConstQualified())) {
223       S.Diag(Arg.get()->getBeginLoc(),
224              diag::err_overflow_builtin_must_be_ptr_int)
225           << Ty << Arg.get()->getSourceRange();
226       return true;
227     }
228     InitializedEntity Entity = InitializedEntity::InitializeParameter(
229         S.getASTContext(), Ty, /*consume*/ false);
230     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
231     if (Arg.isInvalid())
232       return true;
233     TheCall->setArg(2, Arg.get());
234   }
235   return false;
236 }
237 
238 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
239   if (checkArgCount(S, BuiltinCall, 2))
240     return true;
241 
242   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
243   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
244   Expr *Call = BuiltinCall->getArg(0);
245   Expr *Chain = BuiltinCall->getArg(1);
246 
247   if (Call->getStmtClass() != Stmt::CallExprClass) {
248     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
249         << Call->getSourceRange();
250     return true;
251   }
252 
253   auto CE = cast<CallExpr>(Call);
254   if (CE->getCallee()->getType()->isBlockPointerType()) {
255     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
256         << Call->getSourceRange();
257     return true;
258   }
259 
260   const Decl *TargetDecl = CE->getCalleeDecl();
261   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
262     if (FD->getBuiltinID()) {
263       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
264           << Call->getSourceRange();
265       return true;
266     }
267 
268   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
269     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
270         << Call->getSourceRange();
271     return true;
272   }
273 
274   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
275   if (ChainResult.isInvalid())
276     return true;
277   if (!ChainResult.get()->getType()->isPointerType()) {
278     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
279         << Chain->getSourceRange();
280     return true;
281   }
282 
283   QualType ReturnTy = CE->getCallReturnType(S.Context);
284   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
285   QualType BuiltinTy = S.Context.getFunctionType(
286       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
287   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
288 
289   Builtin =
290       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
291 
292   BuiltinCall->setType(CE->getType());
293   BuiltinCall->setValueKind(CE->getValueKind());
294   BuiltinCall->setObjectKind(CE->getObjectKind());
295   BuiltinCall->setCallee(Builtin);
296   BuiltinCall->setArg(1, ChainResult.get());
297 
298   return false;
299 }
300 
301 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
302 /// __builtin_*_chk function, then use the object size argument specified in the
303 /// source. Otherwise, infer the object size using __builtin_object_size.
304 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
305                                                CallExpr *TheCall) {
306   // FIXME: There are some more useful checks we could be doing here:
307   //  - Analyze the format string of sprintf to see how much of buffer is used.
308   //  - Evaluate strlen of strcpy arguments, use as object size.
309 
310   if (TheCall->isValueDependent() || TheCall->isTypeDependent())
311     return;
312 
313   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
314   if (!BuiltinID)
315     return;
316 
317   unsigned DiagID = 0;
318   bool IsChkVariant = false;
319   unsigned SizeIndex, ObjectIndex;
320   switch (BuiltinID) {
321   default:
322     return;
323   case Builtin::BI__builtin___memcpy_chk:
324   case Builtin::BI__builtin___memmove_chk:
325   case Builtin::BI__builtin___memset_chk:
326   case Builtin::BI__builtin___strlcat_chk:
327   case Builtin::BI__builtin___strlcpy_chk:
328   case Builtin::BI__builtin___strncat_chk:
329   case Builtin::BI__builtin___strncpy_chk:
330   case Builtin::BI__builtin___stpncpy_chk:
331   case Builtin::BI__builtin___memccpy_chk: {
332     DiagID = diag::warn_builtin_chk_overflow;
333     IsChkVariant = true;
334     SizeIndex = TheCall->getNumArgs() - 2;
335     ObjectIndex = TheCall->getNumArgs() - 1;
336     break;
337   }
338 
339   case Builtin::BI__builtin___snprintf_chk:
340   case Builtin::BI__builtin___vsnprintf_chk: {
341     DiagID = diag::warn_builtin_chk_overflow;
342     IsChkVariant = true;
343     SizeIndex = 1;
344     ObjectIndex = 3;
345     break;
346   }
347 
348   case Builtin::BIstrncat:
349   case Builtin::BI__builtin_strncat:
350   case Builtin::BIstrncpy:
351   case Builtin::BI__builtin_strncpy:
352   case Builtin::BIstpncpy:
353   case Builtin::BI__builtin_stpncpy: {
354     // Whether these functions overflow depends on the runtime strlen of the
355     // string, not just the buffer size, so emitting the "always overflow"
356     // diagnostic isn't quite right. We should still diagnose passing a buffer
357     // size larger than the destination buffer though; this is a runtime abort
358     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
359     DiagID = diag::warn_fortify_source_size_mismatch;
360     SizeIndex = TheCall->getNumArgs() - 1;
361     ObjectIndex = 0;
362     break;
363   }
364 
365   case Builtin::BImemcpy:
366   case Builtin::BI__builtin_memcpy:
367   case Builtin::BImemmove:
368   case Builtin::BI__builtin_memmove:
369   case Builtin::BImemset:
370   case Builtin::BI__builtin_memset: {
371     DiagID = diag::warn_fortify_source_overflow;
372     SizeIndex = TheCall->getNumArgs() - 1;
373     ObjectIndex = 0;
374     break;
375   }
376   case Builtin::BIsnprintf:
377   case Builtin::BI__builtin_snprintf:
378   case Builtin::BIvsnprintf:
379   case Builtin::BI__builtin_vsnprintf: {
380     DiagID = diag::warn_fortify_source_size_mismatch;
381     SizeIndex = 1;
382     ObjectIndex = 0;
383     break;
384   }
385   }
386 
387   llvm::APSInt ObjectSize;
388   // For __builtin___*_chk, the object size is explicitly provided by the caller
389   // (usually using __builtin_object_size). Use that value to check this call.
390   if (IsChkVariant) {
391     Expr::EvalResult Result;
392     Expr *SizeArg = TheCall->getArg(ObjectIndex);
393     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
394       return;
395     ObjectSize = Result.Val.getInt();
396 
397   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
398   } else {
399     // If the parameter has a pass_object_size attribute, then we should use its
400     // (potentially) more strict checking mode. Otherwise, conservatively assume
401     // type 0.
402     int BOSType = 0;
403     if (const auto *POS =
404             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
405       BOSType = POS->getType();
406 
407     Expr *ObjArg = TheCall->getArg(ObjectIndex);
408     uint64_t Result;
409     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
410       return;
411     // Get the object size in the target's size_t width.
412     const TargetInfo &TI = getASTContext().getTargetInfo();
413     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
414     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
415   }
416 
417   // Evaluate the number of bytes of the object that this call will use.
418   Expr::EvalResult Result;
419   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
420   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
421     return;
422   llvm::APSInt UsedSize = Result.Val.getInt();
423 
424   if (UsedSize.ule(ObjectSize))
425     return;
426 
427   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
428   // Skim off the details of whichever builtin was called to produce a better
429   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
430   if (IsChkVariant) {
431     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
432     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
433   } else if (FunctionName.startswith("__builtin_")) {
434     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
435   }
436 
437   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
438                       PDiag(DiagID)
439                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
440                           << UsedSize.toString(/*Radix=*/10));
441 }
442 
443 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
444                                      Scope::ScopeFlags NeededScopeFlags,
445                                      unsigned DiagID) {
446   // Scopes aren't available during instantiation. Fortunately, builtin
447   // functions cannot be template args so they cannot be formed through template
448   // instantiation. Therefore checking once during the parse is sufficient.
449   if (SemaRef.inTemplateInstantiation())
450     return false;
451 
452   Scope *S = SemaRef.getCurScope();
453   while (S && !S->isSEHExceptScope())
454     S = S->getParent();
455   if (!S || !(S->getFlags() & NeededScopeFlags)) {
456     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
457     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
458         << DRE->getDecl()->getIdentifier();
459     return true;
460   }
461 
462   return false;
463 }
464 
465 static inline bool isBlockPointer(Expr *Arg) {
466   return Arg->getType()->isBlockPointerType();
467 }
468 
469 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
470 /// void*, which is a requirement of device side enqueue.
471 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
472   const BlockPointerType *BPT =
473       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
474   ArrayRef<QualType> Params =
475       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
476   unsigned ArgCounter = 0;
477   bool IllegalParams = false;
478   // Iterate through the block parameters until either one is found that is not
479   // a local void*, or the block is valid.
480   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
481        I != E; ++I, ++ArgCounter) {
482     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
483         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
484             LangAS::opencl_local) {
485       // Get the location of the error. If a block literal has been passed
486       // (BlockExpr) then we can point straight to the offending argument,
487       // else we just point to the variable reference.
488       SourceLocation ErrorLoc;
489       if (isa<BlockExpr>(BlockArg)) {
490         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
491         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
492       } else if (isa<DeclRefExpr>(BlockArg)) {
493         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
494       }
495       S.Diag(ErrorLoc,
496              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
497       IllegalParams = true;
498     }
499   }
500 
501   return IllegalParams;
502 }
503 
504 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
505   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
506     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
507         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
508     return true;
509   }
510   return false;
511 }
512 
513 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
514   if (checkArgCount(S, TheCall, 2))
515     return true;
516 
517   if (checkOpenCLSubgroupExt(S, TheCall))
518     return true;
519 
520   // First argument is an ndrange_t type.
521   Expr *NDRangeArg = TheCall->getArg(0);
522   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
523     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
524         << TheCall->getDirectCallee() << "'ndrange_t'";
525     return true;
526   }
527 
528   Expr *BlockArg = TheCall->getArg(1);
529   if (!isBlockPointer(BlockArg)) {
530     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
531         << TheCall->getDirectCallee() << "block";
532     return true;
533   }
534   return checkOpenCLBlockArgs(S, BlockArg);
535 }
536 
537 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
538 /// get_kernel_work_group_size
539 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
540 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
541   if (checkArgCount(S, TheCall, 1))
542     return true;
543 
544   Expr *BlockArg = TheCall->getArg(0);
545   if (!isBlockPointer(BlockArg)) {
546     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
547         << TheCall->getDirectCallee() << "block";
548     return true;
549   }
550   return checkOpenCLBlockArgs(S, BlockArg);
551 }
552 
553 /// Diagnose integer type and any valid implicit conversion to it.
554 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
555                                       const QualType &IntType);
556 
557 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
558                                             unsigned Start, unsigned End) {
559   bool IllegalParams = false;
560   for (unsigned I = Start; I <= End; ++I)
561     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
562                                               S.Context.getSizeType());
563   return IllegalParams;
564 }
565 
566 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
567 /// 'local void*' parameter of passed block.
568 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
569                                            Expr *BlockArg,
570                                            unsigned NumNonVarArgs) {
571   const BlockPointerType *BPT =
572       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
573   unsigned NumBlockParams =
574       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
575   unsigned TotalNumArgs = TheCall->getNumArgs();
576 
577   // For each argument passed to the block, a corresponding uint needs to
578   // be passed to describe the size of the local memory.
579   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
580     S.Diag(TheCall->getBeginLoc(),
581            diag::err_opencl_enqueue_kernel_local_size_args);
582     return true;
583   }
584 
585   // Check that the sizes of the local memory are specified by integers.
586   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
587                                          TotalNumArgs - 1);
588 }
589 
590 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
591 /// overload formats specified in Table 6.13.17.1.
592 /// int enqueue_kernel(queue_t queue,
593 ///                    kernel_enqueue_flags_t flags,
594 ///                    const ndrange_t ndrange,
595 ///                    void (^block)(void))
596 /// int enqueue_kernel(queue_t queue,
597 ///                    kernel_enqueue_flags_t flags,
598 ///                    const ndrange_t ndrange,
599 ///                    uint num_events_in_wait_list,
600 ///                    clk_event_t *event_wait_list,
601 ///                    clk_event_t *event_ret,
602 ///                    void (^block)(void))
603 /// int enqueue_kernel(queue_t queue,
604 ///                    kernel_enqueue_flags_t flags,
605 ///                    const ndrange_t ndrange,
606 ///                    void (^block)(local void*, ...),
607 ///                    uint size0, ...)
608 /// int enqueue_kernel(queue_t queue,
609 ///                    kernel_enqueue_flags_t flags,
610 ///                    const ndrange_t ndrange,
611 ///                    uint num_events_in_wait_list,
612 ///                    clk_event_t *event_wait_list,
613 ///                    clk_event_t *event_ret,
614 ///                    void (^block)(local void*, ...),
615 ///                    uint size0, ...)
616 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
617   unsigned NumArgs = TheCall->getNumArgs();
618 
619   if (NumArgs < 4) {
620     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
621     return true;
622   }
623 
624   Expr *Arg0 = TheCall->getArg(0);
625   Expr *Arg1 = TheCall->getArg(1);
626   Expr *Arg2 = TheCall->getArg(2);
627   Expr *Arg3 = TheCall->getArg(3);
628 
629   // First argument always needs to be a queue_t type.
630   if (!Arg0->getType()->isQueueT()) {
631     S.Diag(TheCall->getArg(0)->getBeginLoc(),
632            diag::err_opencl_builtin_expected_type)
633         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
634     return true;
635   }
636 
637   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
638   if (!Arg1->getType()->isIntegerType()) {
639     S.Diag(TheCall->getArg(1)->getBeginLoc(),
640            diag::err_opencl_builtin_expected_type)
641         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
642     return true;
643   }
644 
645   // Third argument is always an ndrange_t type.
646   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
647     S.Diag(TheCall->getArg(2)->getBeginLoc(),
648            diag::err_opencl_builtin_expected_type)
649         << TheCall->getDirectCallee() << "'ndrange_t'";
650     return true;
651   }
652 
653   // With four arguments, there is only one form that the function could be
654   // called in: no events and no variable arguments.
655   if (NumArgs == 4) {
656     // check that the last argument is the right block type.
657     if (!isBlockPointer(Arg3)) {
658       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
659           << TheCall->getDirectCallee() << "block";
660       return true;
661     }
662     // we have a block type, check the prototype
663     const BlockPointerType *BPT =
664         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
665     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
666       S.Diag(Arg3->getBeginLoc(),
667              diag::err_opencl_enqueue_kernel_blocks_no_args);
668       return true;
669     }
670     return false;
671   }
672   // we can have block + varargs.
673   if (isBlockPointer(Arg3))
674     return (checkOpenCLBlockArgs(S, Arg3) ||
675             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
676   // last two cases with either exactly 7 args or 7 args and varargs.
677   if (NumArgs >= 7) {
678     // check common block argument.
679     Expr *Arg6 = TheCall->getArg(6);
680     if (!isBlockPointer(Arg6)) {
681       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
682           << TheCall->getDirectCallee() << "block";
683       return true;
684     }
685     if (checkOpenCLBlockArgs(S, Arg6))
686       return true;
687 
688     // Forth argument has to be any integer type.
689     if (!Arg3->getType()->isIntegerType()) {
690       S.Diag(TheCall->getArg(3)->getBeginLoc(),
691              diag::err_opencl_builtin_expected_type)
692           << TheCall->getDirectCallee() << "integer";
693       return true;
694     }
695     // check remaining common arguments.
696     Expr *Arg4 = TheCall->getArg(4);
697     Expr *Arg5 = TheCall->getArg(5);
698 
699     // Fifth argument is always passed as a pointer to clk_event_t.
700     if (!Arg4->isNullPointerConstant(S.Context,
701                                      Expr::NPC_ValueDependentIsNotNull) &&
702         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
703       S.Diag(TheCall->getArg(4)->getBeginLoc(),
704              diag::err_opencl_builtin_expected_type)
705           << TheCall->getDirectCallee()
706           << S.Context.getPointerType(S.Context.OCLClkEventTy);
707       return true;
708     }
709 
710     // Sixth argument is always passed as a pointer to clk_event_t.
711     if (!Arg5->isNullPointerConstant(S.Context,
712                                      Expr::NPC_ValueDependentIsNotNull) &&
713         !(Arg5->getType()->isPointerType() &&
714           Arg5->getType()->getPointeeType()->isClkEventT())) {
715       S.Diag(TheCall->getArg(5)->getBeginLoc(),
716              diag::err_opencl_builtin_expected_type)
717           << TheCall->getDirectCallee()
718           << S.Context.getPointerType(S.Context.OCLClkEventTy);
719       return true;
720     }
721 
722     if (NumArgs == 7)
723       return false;
724 
725     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
726   }
727 
728   // None of the specific case has been detected, give generic error
729   S.Diag(TheCall->getBeginLoc(),
730          diag::err_opencl_enqueue_kernel_incorrect_args);
731   return true;
732 }
733 
734 /// Returns OpenCL access qual.
735 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
736     return D->getAttr<OpenCLAccessAttr>();
737 }
738 
739 /// Returns true if pipe element type is different from the pointer.
740 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
741   const Expr *Arg0 = Call->getArg(0);
742   // First argument type should always be pipe.
743   if (!Arg0->getType()->isPipeType()) {
744     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
745         << Call->getDirectCallee() << Arg0->getSourceRange();
746     return true;
747   }
748   OpenCLAccessAttr *AccessQual =
749       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
750   // Validates the access qualifier is compatible with the call.
751   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
752   // read_only and write_only, and assumed to be read_only if no qualifier is
753   // specified.
754   switch (Call->getDirectCallee()->getBuiltinID()) {
755   case Builtin::BIread_pipe:
756   case Builtin::BIreserve_read_pipe:
757   case Builtin::BIcommit_read_pipe:
758   case Builtin::BIwork_group_reserve_read_pipe:
759   case Builtin::BIsub_group_reserve_read_pipe:
760   case Builtin::BIwork_group_commit_read_pipe:
761   case Builtin::BIsub_group_commit_read_pipe:
762     if (!(!AccessQual || AccessQual->isReadOnly())) {
763       S.Diag(Arg0->getBeginLoc(),
764              diag::err_opencl_builtin_pipe_invalid_access_modifier)
765           << "read_only" << Arg0->getSourceRange();
766       return true;
767     }
768     break;
769   case Builtin::BIwrite_pipe:
770   case Builtin::BIreserve_write_pipe:
771   case Builtin::BIcommit_write_pipe:
772   case Builtin::BIwork_group_reserve_write_pipe:
773   case Builtin::BIsub_group_reserve_write_pipe:
774   case Builtin::BIwork_group_commit_write_pipe:
775   case Builtin::BIsub_group_commit_write_pipe:
776     if (!(AccessQual && AccessQual->isWriteOnly())) {
777       S.Diag(Arg0->getBeginLoc(),
778              diag::err_opencl_builtin_pipe_invalid_access_modifier)
779           << "write_only" << Arg0->getSourceRange();
780       return true;
781     }
782     break;
783   default:
784     break;
785   }
786   return false;
787 }
788 
789 /// Returns true if pipe element type is different from the pointer.
790 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
791   const Expr *Arg0 = Call->getArg(0);
792   const Expr *ArgIdx = Call->getArg(Idx);
793   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
794   const QualType EltTy = PipeTy->getElementType();
795   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
796   // The Idx argument should be a pointer and the type of the pointer and
797   // the type of pipe element should also be the same.
798   if (!ArgTy ||
799       !S.Context.hasSameType(
800           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
801     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
802         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
803         << ArgIdx->getType() << ArgIdx->getSourceRange();
804     return true;
805   }
806   return false;
807 }
808 
809 // Performs semantic analysis for the read/write_pipe call.
810 // \param S Reference to the semantic analyzer.
811 // \param Call A pointer to the builtin call.
812 // \return True if a semantic error has been found, false otherwise.
813 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
814   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
815   // functions have two forms.
816   switch (Call->getNumArgs()) {
817   case 2:
818     if (checkOpenCLPipeArg(S, Call))
819       return true;
820     // The call with 2 arguments should be
821     // read/write_pipe(pipe T, T*).
822     // Check packet type T.
823     if (checkOpenCLPipePacketType(S, Call, 1))
824       return true;
825     break;
826 
827   case 4: {
828     if (checkOpenCLPipeArg(S, Call))
829       return true;
830     // The call with 4 arguments should be
831     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
832     // Check reserve_id_t.
833     if (!Call->getArg(1)->getType()->isReserveIDT()) {
834       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
835           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
836           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
837       return true;
838     }
839 
840     // Check the index.
841     const Expr *Arg2 = Call->getArg(2);
842     if (!Arg2->getType()->isIntegerType() &&
843         !Arg2->getType()->isUnsignedIntegerType()) {
844       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
845           << Call->getDirectCallee() << S.Context.UnsignedIntTy
846           << Arg2->getType() << Arg2->getSourceRange();
847       return true;
848     }
849 
850     // Check packet type T.
851     if (checkOpenCLPipePacketType(S, Call, 3))
852       return true;
853   } break;
854   default:
855     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
856         << Call->getDirectCallee() << Call->getSourceRange();
857     return true;
858   }
859 
860   return false;
861 }
862 
863 // Performs a semantic analysis on the {work_group_/sub_group_
864 //        /_}reserve_{read/write}_pipe
865 // \param S Reference to the semantic analyzer.
866 // \param Call The call to the builtin function to be analyzed.
867 // \return True if a semantic error was found, false otherwise.
868 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
869   if (checkArgCount(S, Call, 2))
870     return true;
871 
872   if (checkOpenCLPipeArg(S, Call))
873     return true;
874 
875   // Check the reserve size.
876   if (!Call->getArg(1)->getType()->isIntegerType() &&
877       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
878     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
879         << Call->getDirectCallee() << S.Context.UnsignedIntTy
880         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
881     return true;
882   }
883 
884   // Since return type of reserve_read/write_pipe built-in function is
885   // reserve_id_t, which is not defined in the builtin def file , we used int
886   // as return type and need to override the return type of these functions.
887   Call->setType(S.Context.OCLReserveIDTy);
888 
889   return false;
890 }
891 
892 // Performs a semantic analysis on {work_group_/sub_group_
893 //        /_}commit_{read/write}_pipe
894 // \param S Reference to the semantic analyzer.
895 // \param Call The call to the builtin function to be analyzed.
896 // \return True if a semantic error was found, false otherwise.
897 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
898   if (checkArgCount(S, Call, 2))
899     return true;
900 
901   if (checkOpenCLPipeArg(S, Call))
902     return true;
903 
904   // Check reserve_id_t.
905   if (!Call->getArg(1)->getType()->isReserveIDT()) {
906     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
907         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
908         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
909     return true;
910   }
911 
912   return false;
913 }
914 
915 // Performs a semantic analysis on the call to built-in Pipe
916 //        Query Functions.
917 // \param S Reference to the semantic analyzer.
918 // \param Call The call to the builtin function to be analyzed.
919 // \return True if a semantic error was found, false otherwise.
920 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
921   if (checkArgCount(S, Call, 1))
922     return true;
923 
924   if (!Call->getArg(0)->getType()->isPipeType()) {
925     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
926         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
927     return true;
928   }
929 
930   return false;
931 }
932 
933 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
934 // Performs semantic analysis for the to_global/local/private call.
935 // \param S Reference to the semantic analyzer.
936 // \param BuiltinID ID of the builtin function.
937 // \param Call A pointer to the builtin call.
938 // \return True if a semantic error has been found, false otherwise.
939 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
940                                     CallExpr *Call) {
941   if (Call->getNumArgs() != 1) {
942     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
943         << Call->getDirectCallee() << Call->getSourceRange();
944     return true;
945   }
946 
947   auto RT = Call->getArg(0)->getType();
948   if (!RT->isPointerType() || RT->getPointeeType()
949       .getAddressSpace() == LangAS::opencl_constant) {
950     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
951         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
952     return true;
953   }
954 
955   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
956     S.Diag(Call->getArg(0)->getBeginLoc(),
957            diag::warn_opencl_generic_address_space_arg)
958         << Call->getDirectCallee()->getNameInfo().getAsString()
959         << Call->getArg(0)->getSourceRange();
960   }
961 
962   RT = RT->getPointeeType();
963   auto Qual = RT.getQualifiers();
964   switch (BuiltinID) {
965   case Builtin::BIto_global:
966     Qual.setAddressSpace(LangAS::opencl_global);
967     break;
968   case Builtin::BIto_local:
969     Qual.setAddressSpace(LangAS::opencl_local);
970     break;
971   case Builtin::BIto_private:
972     Qual.setAddressSpace(LangAS::opencl_private);
973     break;
974   default:
975     llvm_unreachable("Invalid builtin function");
976   }
977   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
978       RT.getUnqualifiedType(), Qual)));
979 
980   return false;
981 }
982 
983 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
984   if (checkArgCount(S, TheCall, 1))
985     return ExprError();
986 
987   // Compute __builtin_launder's parameter type from the argument.
988   // The parameter type is:
989   //  * The type of the argument if it's not an array or function type,
990   //  Otherwise,
991   //  * The decayed argument type.
992   QualType ParamTy = [&]() {
993     QualType ArgTy = TheCall->getArg(0)->getType();
994     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
995       return S.Context.getPointerType(Ty->getElementType());
996     if (ArgTy->isFunctionType()) {
997       return S.Context.getPointerType(ArgTy);
998     }
999     return ArgTy;
1000   }();
1001 
1002   TheCall->setType(ParamTy);
1003 
1004   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1005     if (!ParamTy->isPointerType())
1006       return 0;
1007     if (ParamTy->isFunctionPointerType())
1008       return 1;
1009     if (ParamTy->isVoidPointerType())
1010       return 2;
1011     return llvm::Optional<unsigned>{};
1012   }();
1013   if (DiagSelect.hasValue()) {
1014     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1015         << DiagSelect.getValue() << TheCall->getSourceRange();
1016     return ExprError();
1017   }
1018 
1019   // We either have an incomplete class type, or we have a class template
1020   // whose instantiation has not been forced. Example:
1021   //
1022   //   template <class T> struct Foo { T value; };
1023   //   Foo<int> *p = nullptr;
1024   //   auto *d = __builtin_launder(p);
1025   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1026                             diag::err_incomplete_type))
1027     return ExprError();
1028 
1029   assert(ParamTy->getPointeeType()->isObjectType() &&
1030          "Unhandled non-object pointer case");
1031 
1032   InitializedEntity Entity =
1033       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1034   ExprResult Arg =
1035       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1036   if (Arg.isInvalid())
1037     return ExprError();
1038   TheCall->setArg(0, Arg.get());
1039 
1040   return TheCall;
1041 }
1042 
1043 // Emit an error and return true if the current architecture is not in the list
1044 // of supported architectures.
1045 static bool
1046 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1047                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1048   llvm::Triple::ArchType CurArch =
1049       S.getASTContext().getTargetInfo().getTriple().getArch();
1050   if (llvm::is_contained(SupportedArchs, CurArch))
1051     return false;
1052   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1053       << TheCall->getSourceRange();
1054   return true;
1055 }
1056 
1057 ExprResult
1058 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1059                                CallExpr *TheCall) {
1060   ExprResult TheCallResult(TheCall);
1061 
1062   // Find out if any arguments are required to be integer constant expressions.
1063   unsigned ICEArguments = 0;
1064   ASTContext::GetBuiltinTypeError Error;
1065   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1066   if (Error != ASTContext::GE_None)
1067     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1068 
1069   // If any arguments are required to be ICE's, check and diagnose.
1070   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1071     // Skip arguments not required to be ICE's.
1072     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1073 
1074     llvm::APSInt Result;
1075     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1076       return true;
1077     ICEArguments &= ~(1 << ArgNo);
1078   }
1079 
1080   switch (BuiltinID) {
1081   case Builtin::BI__builtin___CFStringMakeConstantString:
1082     assert(TheCall->getNumArgs() == 1 &&
1083            "Wrong # arguments to builtin CFStringMakeConstantString");
1084     if (CheckObjCString(TheCall->getArg(0)))
1085       return ExprError();
1086     break;
1087   case Builtin::BI__builtin_ms_va_start:
1088   case Builtin::BI__builtin_stdarg_start:
1089   case Builtin::BI__builtin_va_start:
1090     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1091       return ExprError();
1092     break;
1093   case Builtin::BI__va_start: {
1094     switch (Context.getTargetInfo().getTriple().getArch()) {
1095     case llvm::Triple::aarch64:
1096     case llvm::Triple::arm:
1097     case llvm::Triple::thumb:
1098       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1099         return ExprError();
1100       break;
1101     default:
1102       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1103         return ExprError();
1104       break;
1105     }
1106     break;
1107   }
1108 
1109   // The acquire, release, and no fence variants are ARM and AArch64 only.
1110   case Builtin::BI_interlockedbittestandset_acq:
1111   case Builtin::BI_interlockedbittestandset_rel:
1112   case Builtin::BI_interlockedbittestandset_nf:
1113   case Builtin::BI_interlockedbittestandreset_acq:
1114   case Builtin::BI_interlockedbittestandreset_rel:
1115   case Builtin::BI_interlockedbittestandreset_nf:
1116     if (CheckBuiltinTargetSupport(
1117             *this, BuiltinID, TheCall,
1118             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1119       return ExprError();
1120     break;
1121 
1122   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1123   case Builtin::BI_bittest64:
1124   case Builtin::BI_bittestandcomplement64:
1125   case Builtin::BI_bittestandreset64:
1126   case Builtin::BI_bittestandset64:
1127   case Builtin::BI_interlockedbittestandreset64:
1128   case Builtin::BI_interlockedbittestandset64:
1129     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1130                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1131                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1132       return ExprError();
1133     break;
1134 
1135   case Builtin::BI__builtin_isgreater:
1136   case Builtin::BI__builtin_isgreaterequal:
1137   case Builtin::BI__builtin_isless:
1138   case Builtin::BI__builtin_islessequal:
1139   case Builtin::BI__builtin_islessgreater:
1140   case Builtin::BI__builtin_isunordered:
1141     if (SemaBuiltinUnorderedCompare(TheCall))
1142       return ExprError();
1143     break;
1144   case Builtin::BI__builtin_fpclassify:
1145     if (SemaBuiltinFPClassification(TheCall, 6))
1146       return ExprError();
1147     break;
1148   case Builtin::BI__builtin_isfinite:
1149   case Builtin::BI__builtin_isinf:
1150   case Builtin::BI__builtin_isinf_sign:
1151   case Builtin::BI__builtin_isnan:
1152   case Builtin::BI__builtin_isnormal:
1153   case Builtin::BI__builtin_signbit:
1154   case Builtin::BI__builtin_signbitf:
1155   case Builtin::BI__builtin_signbitl:
1156     if (SemaBuiltinFPClassification(TheCall, 1))
1157       return ExprError();
1158     break;
1159   case Builtin::BI__builtin_shufflevector:
1160     return SemaBuiltinShuffleVector(TheCall);
1161     // TheCall will be freed by the smart pointer here, but that's fine, since
1162     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1163   case Builtin::BI__builtin_prefetch:
1164     if (SemaBuiltinPrefetch(TheCall))
1165       return ExprError();
1166     break;
1167   case Builtin::BI__builtin_alloca_with_align:
1168     if (SemaBuiltinAllocaWithAlign(TheCall))
1169       return ExprError();
1170     break;
1171   case Builtin::BI__assume:
1172   case Builtin::BI__builtin_assume:
1173     if (SemaBuiltinAssume(TheCall))
1174       return ExprError();
1175     break;
1176   case Builtin::BI__builtin_assume_aligned:
1177     if (SemaBuiltinAssumeAligned(TheCall))
1178       return ExprError();
1179     break;
1180   case Builtin::BI__builtin_dynamic_object_size:
1181   case Builtin::BI__builtin_object_size:
1182     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1183       return ExprError();
1184     break;
1185   case Builtin::BI__builtin_longjmp:
1186     if (SemaBuiltinLongjmp(TheCall))
1187       return ExprError();
1188     break;
1189   case Builtin::BI__builtin_setjmp:
1190     if (SemaBuiltinSetjmp(TheCall))
1191       return ExprError();
1192     break;
1193   case Builtin::BI_setjmp:
1194   case Builtin::BI_setjmpex:
1195     if (checkArgCount(*this, TheCall, 1))
1196       return true;
1197     break;
1198   case Builtin::BI__builtin_classify_type:
1199     if (checkArgCount(*this, TheCall, 1)) return true;
1200     TheCall->setType(Context.IntTy);
1201     break;
1202   case Builtin::BI__builtin_constant_p:
1203     if (checkArgCount(*this, TheCall, 1)) return true;
1204     TheCall->setType(Context.IntTy);
1205     break;
1206   case Builtin::BI__builtin_launder:
1207     return SemaBuiltinLaunder(*this, TheCall);
1208   case Builtin::BI__sync_fetch_and_add:
1209   case Builtin::BI__sync_fetch_and_add_1:
1210   case Builtin::BI__sync_fetch_and_add_2:
1211   case Builtin::BI__sync_fetch_and_add_4:
1212   case Builtin::BI__sync_fetch_and_add_8:
1213   case Builtin::BI__sync_fetch_and_add_16:
1214   case Builtin::BI__sync_fetch_and_sub:
1215   case Builtin::BI__sync_fetch_and_sub_1:
1216   case Builtin::BI__sync_fetch_and_sub_2:
1217   case Builtin::BI__sync_fetch_and_sub_4:
1218   case Builtin::BI__sync_fetch_and_sub_8:
1219   case Builtin::BI__sync_fetch_and_sub_16:
1220   case Builtin::BI__sync_fetch_and_or:
1221   case Builtin::BI__sync_fetch_and_or_1:
1222   case Builtin::BI__sync_fetch_and_or_2:
1223   case Builtin::BI__sync_fetch_and_or_4:
1224   case Builtin::BI__sync_fetch_and_or_8:
1225   case Builtin::BI__sync_fetch_and_or_16:
1226   case Builtin::BI__sync_fetch_and_and:
1227   case Builtin::BI__sync_fetch_and_and_1:
1228   case Builtin::BI__sync_fetch_and_and_2:
1229   case Builtin::BI__sync_fetch_and_and_4:
1230   case Builtin::BI__sync_fetch_and_and_8:
1231   case Builtin::BI__sync_fetch_and_and_16:
1232   case Builtin::BI__sync_fetch_and_xor:
1233   case Builtin::BI__sync_fetch_and_xor_1:
1234   case Builtin::BI__sync_fetch_and_xor_2:
1235   case Builtin::BI__sync_fetch_and_xor_4:
1236   case Builtin::BI__sync_fetch_and_xor_8:
1237   case Builtin::BI__sync_fetch_and_xor_16:
1238   case Builtin::BI__sync_fetch_and_nand:
1239   case Builtin::BI__sync_fetch_and_nand_1:
1240   case Builtin::BI__sync_fetch_and_nand_2:
1241   case Builtin::BI__sync_fetch_and_nand_4:
1242   case Builtin::BI__sync_fetch_and_nand_8:
1243   case Builtin::BI__sync_fetch_and_nand_16:
1244   case Builtin::BI__sync_add_and_fetch:
1245   case Builtin::BI__sync_add_and_fetch_1:
1246   case Builtin::BI__sync_add_and_fetch_2:
1247   case Builtin::BI__sync_add_and_fetch_4:
1248   case Builtin::BI__sync_add_and_fetch_8:
1249   case Builtin::BI__sync_add_and_fetch_16:
1250   case Builtin::BI__sync_sub_and_fetch:
1251   case Builtin::BI__sync_sub_and_fetch_1:
1252   case Builtin::BI__sync_sub_and_fetch_2:
1253   case Builtin::BI__sync_sub_and_fetch_4:
1254   case Builtin::BI__sync_sub_and_fetch_8:
1255   case Builtin::BI__sync_sub_and_fetch_16:
1256   case Builtin::BI__sync_and_and_fetch:
1257   case Builtin::BI__sync_and_and_fetch_1:
1258   case Builtin::BI__sync_and_and_fetch_2:
1259   case Builtin::BI__sync_and_and_fetch_4:
1260   case Builtin::BI__sync_and_and_fetch_8:
1261   case Builtin::BI__sync_and_and_fetch_16:
1262   case Builtin::BI__sync_or_and_fetch:
1263   case Builtin::BI__sync_or_and_fetch_1:
1264   case Builtin::BI__sync_or_and_fetch_2:
1265   case Builtin::BI__sync_or_and_fetch_4:
1266   case Builtin::BI__sync_or_and_fetch_8:
1267   case Builtin::BI__sync_or_and_fetch_16:
1268   case Builtin::BI__sync_xor_and_fetch:
1269   case Builtin::BI__sync_xor_and_fetch_1:
1270   case Builtin::BI__sync_xor_and_fetch_2:
1271   case Builtin::BI__sync_xor_and_fetch_4:
1272   case Builtin::BI__sync_xor_and_fetch_8:
1273   case Builtin::BI__sync_xor_and_fetch_16:
1274   case Builtin::BI__sync_nand_and_fetch:
1275   case Builtin::BI__sync_nand_and_fetch_1:
1276   case Builtin::BI__sync_nand_and_fetch_2:
1277   case Builtin::BI__sync_nand_and_fetch_4:
1278   case Builtin::BI__sync_nand_and_fetch_8:
1279   case Builtin::BI__sync_nand_and_fetch_16:
1280   case Builtin::BI__sync_val_compare_and_swap:
1281   case Builtin::BI__sync_val_compare_and_swap_1:
1282   case Builtin::BI__sync_val_compare_and_swap_2:
1283   case Builtin::BI__sync_val_compare_and_swap_4:
1284   case Builtin::BI__sync_val_compare_and_swap_8:
1285   case Builtin::BI__sync_val_compare_and_swap_16:
1286   case Builtin::BI__sync_bool_compare_and_swap:
1287   case Builtin::BI__sync_bool_compare_and_swap_1:
1288   case Builtin::BI__sync_bool_compare_and_swap_2:
1289   case Builtin::BI__sync_bool_compare_and_swap_4:
1290   case Builtin::BI__sync_bool_compare_and_swap_8:
1291   case Builtin::BI__sync_bool_compare_and_swap_16:
1292   case Builtin::BI__sync_lock_test_and_set:
1293   case Builtin::BI__sync_lock_test_and_set_1:
1294   case Builtin::BI__sync_lock_test_and_set_2:
1295   case Builtin::BI__sync_lock_test_and_set_4:
1296   case Builtin::BI__sync_lock_test_and_set_8:
1297   case Builtin::BI__sync_lock_test_and_set_16:
1298   case Builtin::BI__sync_lock_release:
1299   case Builtin::BI__sync_lock_release_1:
1300   case Builtin::BI__sync_lock_release_2:
1301   case Builtin::BI__sync_lock_release_4:
1302   case Builtin::BI__sync_lock_release_8:
1303   case Builtin::BI__sync_lock_release_16:
1304   case Builtin::BI__sync_swap:
1305   case Builtin::BI__sync_swap_1:
1306   case Builtin::BI__sync_swap_2:
1307   case Builtin::BI__sync_swap_4:
1308   case Builtin::BI__sync_swap_8:
1309   case Builtin::BI__sync_swap_16:
1310     return SemaBuiltinAtomicOverloaded(TheCallResult);
1311   case Builtin::BI__sync_synchronize:
1312     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1313         << TheCall->getCallee()->getSourceRange();
1314     break;
1315   case Builtin::BI__builtin_nontemporal_load:
1316   case Builtin::BI__builtin_nontemporal_store:
1317     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1318 #define BUILTIN(ID, TYPE, ATTRS)
1319 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1320   case Builtin::BI##ID: \
1321     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1322 #include "clang/Basic/Builtins.def"
1323   case Builtin::BI__annotation:
1324     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1325       return ExprError();
1326     break;
1327   case Builtin::BI__builtin_annotation:
1328     if (SemaBuiltinAnnotation(*this, TheCall))
1329       return ExprError();
1330     break;
1331   case Builtin::BI__builtin_addressof:
1332     if (SemaBuiltinAddressof(*this, TheCall))
1333       return ExprError();
1334     break;
1335   case Builtin::BI__builtin_add_overflow:
1336   case Builtin::BI__builtin_sub_overflow:
1337   case Builtin::BI__builtin_mul_overflow:
1338     if (SemaBuiltinOverflow(*this, TheCall))
1339       return ExprError();
1340     break;
1341   case Builtin::BI__builtin_operator_new:
1342   case Builtin::BI__builtin_operator_delete: {
1343     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1344     ExprResult Res =
1345         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1346     if (Res.isInvalid())
1347       CorrectDelayedTyposInExpr(TheCallResult.get());
1348     return Res;
1349   }
1350   case Builtin::BI__builtin_dump_struct: {
1351     // We first want to ensure we are called with 2 arguments
1352     if (checkArgCount(*this, TheCall, 2))
1353       return ExprError();
1354     // Ensure that the first argument is of type 'struct XX *'
1355     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1356     const QualType PtrArgType = PtrArg->getType();
1357     if (!PtrArgType->isPointerType() ||
1358         !PtrArgType->getPointeeType()->isRecordType()) {
1359       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1360           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1361           << "structure pointer";
1362       return ExprError();
1363     }
1364 
1365     // Ensure that the second argument is of type 'FunctionType'
1366     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1367     const QualType FnPtrArgType = FnPtrArg->getType();
1368     if (!FnPtrArgType->isPointerType()) {
1369       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1370           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1371           << FnPtrArgType << "'int (*)(const char *, ...)'";
1372       return ExprError();
1373     }
1374 
1375     const auto *FuncType =
1376         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1377 
1378     if (!FuncType) {
1379       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1380           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1381           << FnPtrArgType << "'int (*)(const char *, ...)'";
1382       return ExprError();
1383     }
1384 
1385     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1386       if (!FT->getNumParams()) {
1387         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1388             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1389             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1390         return ExprError();
1391       }
1392       QualType PT = FT->getParamType(0);
1393       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1394           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1395           !PT->getPointeeType().isConstQualified()) {
1396         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1397             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1398             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1399         return ExprError();
1400       }
1401     }
1402 
1403     TheCall->setType(Context.IntTy);
1404     break;
1405   }
1406   case Builtin::BI__builtin_call_with_static_chain:
1407     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1408       return ExprError();
1409     break;
1410   case Builtin::BI__exception_code:
1411   case Builtin::BI_exception_code:
1412     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1413                                  diag::err_seh___except_block))
1414       return ExprError();
1415     break;
1416   case Builtin::BI__exception_info:
1417   case Builtin::BI_exception_info:
1418     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1419                                  diag::err_seh___except_filter))
1420       return ExprError();
1421     break;
1422   case Builtin::BI__GetExceptionInfo:
1423     if (checkArgCount(*this, TheCall, 1))
1424       return ExprError();
1425 
1426     if (CheckCXXThrowOperand(
1427             TheCall->getBeginLoc(),
1428             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1429             TheCall))
1430       return ExprError();
1431 
1432     TheCall->setType(Context.VoidPtrTy);
1433     break;
1434   // OpenCL v2.0, s6.13.16 - Pipe functions
1435   case Builtin::BIread_pipe:
1436   case Builtin::BIwrite_pipe:
1437     // Since those two functions are declared with var args, we need a semantic
1438     // check for the argument.
1439     if (SemaBuiltinRWPipe(*this, TheCall))
1440       return ExprError();
1441     break;
1442   case Builtin::BIreserve_read_pipe:
1443   case Builtin::BIreserve_write_pipe:
1444   case Builtin::BIwork_group_reserve_read_pipe:
1445   case Builtin::BIwork_group_reserve_write_pipe:
1446     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1447       return ExprError();
1448     break;
1449   case Builtin::BIsub_group_reserve_read_pipe:
1450   case Builtin::BIsub_group_reserve_write_pipe:
1451     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1452         SemaBuiltinReserveRWPipe(*this, TheCall))
1453       return ExprError();
1454     break;
1455   case Builtin::BIcommit_read_pipe:
1456   case Builtin::BIcommit_write_pipe:
1457   case Builtin::BIwork_group_commit_read_pipe:
1458   case Builtin::BIwork_group_commit_write_pipe:
1459     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1460       return ExprError();
1461     break;
1462   case Builtin::BIsub_group_commit_read_pipe:
1463   case Builtin::BIsub_group_commit_write_pipe:
1464     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1465         SemaBuiltinCommitRWPipe(*this, TheCall))
1466       return ExprError();
1467     break;
1468   case Builtin::BIget_pipe_num_packets:
1469   case Builtin::BIget_pipe_max_packets:
1470     if (SemaBuiltinPipePackets(*this, TheCall))
1471       return ExprError();
1472     break;
1473   case Builtin::BIto_global:
1474   case Builtin::BIto_local:
1475   case Builtin::BIto_private:
1476     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1477       return ExprError();
1478     break;
1479   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1480   case Builtin::BIenqueue_kernel:
1481     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1482       return ExprError();
1483     break;
1484   case Builtin::BIget_kernel_work_group_size:
1485   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1486     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1490   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1491     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1492       return ExprError();
1493     break;
1494   case Builtin::BI__builtin_os_log_format:
1495   case Builtin::BI__builtin_os_log_format_buffer_size:
1496     if (SemaBuiltinOSLogFormat(TheCall))
1497       return ExprError();
1498     break;
1499   }
1500 
1501   // Since the target specific builtins for each arch overlap, only check those
1502   // of the arch we are compiling for.
1503   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1504     switch (Context.getTargetInfo().getTriple().getArch()) {
1505       case llvm::Triple::arm:
1506       case llvm::Triple::armeb:
1507       case llvm::Triple::thumb:
1508       case llvm::Triple::thumbeb:
1509         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1510           return ExprError();
1511         break;
1512       case llvm::Triple::aarch64:
1513       case llvm::Triple::aarch64_be:
1514         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1515           return ExprError();
1516         break;
1517       case llvm::Triple::hexagon:
1518         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1519           return ExprError();
1520         break;
1521       case llvm::Triple::mips:
1522       case llvm::Triple::mipsel:
1523       case llvm::Triple::mips64:
1524       case llvm::Triple::mips64el:
1525         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1526           return ExprError();
1527         break;
1528       case llvm::Triple::systemz:
1529         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1530           return ExprError();
1531         break;
1532       case llvm::Triple::x86:
1533       case llvm::Triple::x86_64:
1534         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1535           return ExprError();
1536         break;
1537       case llvm::Triple::ppc:
1538       case llvm::Triple::ppc64:
1539       case llvm::Triple::ppc64le:
1540         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1541           return ExprError();
1542         break;
1543       default:
1544         break;
1545     }
1546   }
1547 
1548   return TheCallResult;
1549 }
1550 
1551 // Get the valid immediate range for the specified NEON type code.
1552 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1553   NeonTypeFlags Type(t);
1554   int IsQuad = ForceQuad ? true : Type.isQuad();
1555   switch (Type.getEltType()) {
1556   case NeonTypeFlags::Int8:
1557   case NeonTypeFlags::Poly8:
1558     return shift ? 7 : (8 << IsQuad) - 1;
1559   case NeonTypeFlags::Int16:
1560   case NeonTypeFlags::Poly16:
1561     return shift ? 15 : (4 << IsQuad) - 1;
1562   case NeonTypeFlags::Int32:
1563     return shift ? 31 : (2 << IsQuad) - 1;
1564   case NeonTypeFlags::Int64:
1565   case NeonTypeFlags::Poly64:
1566     return shift ? 63 : (1 << IsQuad) - 1;
1567   case NeonTypeFlags::Poly128:
1568     return shift ? 127 : (1 << IsQuad) - 1;
1569   case NeonTypeFlags::Float16:
1570     assert(!shift && "cannot shift float types!");
1571     return (4 << IsQuad) - 1;
1572   case NeonTypeFlags::Float32:
1573     assert(!shift && "cannot shift float types!");
1574     return (2 << IsQuad) - 1;
1575   case NeonTypeFlags::Float64:
1576     assert(!shift && "cannot shift float types!");
1577     return (1 << IsQuad) - 1;
1578   }
1579   llvm_unreachable("Invalid NeonTypeFlag!");
1580 }
1581 
1582 /// getNeonEltType - Return the QualType corresponding to the elements of
1583 /// the vector type specified by the NeonTypeFlags.  This is used to check
1584 /// the pointer arguments for Neon load/store intrinsics.
1585 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1586                                bool IsPolyUnsigned, bool IsInt64Long) {
1587   switch (Flags.getEltType()) {
1588   case NeonTypeFlags::Int8:
1589     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1590   case NeonTypeFlags::Int16:
1591     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1592   case NeonTypeFlags::Int32:
1593     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1594   case NeonTypeFlags::Int64:
1595     if (IsInt64Long)
1596       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1597     else
1598       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1599                                 : Context.LongLongTy;
1600   case NeonTypeFlags::Poly8:
1601     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1602   case NeonTypeFlags::Poly16:
1603     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1604   case NeonTypeFlags::Poly64:
1605     if (IsInt64Long)
1606       return Context.UnsignedLongTy;
1607     else
1608       return Context.UnsignedLongLongTy;
1609   case NeonTypeFlags::Poly128:
1610     break;
1611   case NeonTypeFlags::Float16:
1612     return Context.HalfTy;
1613   case NeonTypeFlags::Float32:
1614     return Context.FloatTy;
1615   case NeonTypeFlags::Float64:
1616     return Context.DoubleTy;
1617   }
1618   llvm_unreachable("Invalid NeonTypeFlag!");
1619 }
1620 
1621 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1622   llvm::APSInt Result;
1623   uint64_t mask = 0;
1624   unsigned TV = 0;
1625   int PtrArgNum = -1;
1626   bool HasConstPtr = false;
1627   switch (BuiltinID) {
1628 #define GET_NEON_OVERLOAD_CHECK
1629 #include "clang/Basic/arm_neon.inc"
1630 #include "clang/Basic/arm_fp16.inc"
1631 #undef GET_NEON_OVERLOAD_CHECK
1632   }
1633 
1634   // For NEON intrinsics which are overloaded on vector element type, validate
1635   // the immediate which specifies which variant to emit.
1636   unsigned ImmArg = TheCall->getNumArgs()-1;
1637   if (mask) {
1638     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1639       return true;
1640 
1641     TV = Result.getLimitedValue(64);
1642     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1643       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1644              << TheCall->getArg(ImmArg)->getSourceRange();
1645   }
1646 
1647   if (PtrArgNum >= 0) {
1648     // Check that pointer arguments have the specified type.
1649     Expr *Arg = TheCall->getArg(PtrArgNum);
1650     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1651       Arg = ICE->getSubExpr();
1652     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1653     QualType RHSTy = RHS.get()->getType();
1654 
1655     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1656     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1657                           Arch == llvm::Triple::aarch64_be;
1658     bool IsInt64Long =
1659         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1660     QualType EltTy =
1661         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1662     if (HasConstPtr)
1663       EltTy = EltTy.withConst();
1664     QualType LHSTy = Context.getPointerType(EltTy);
1665     AssignConvertType ConvTy;
1666     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1667     if (RHS.isInvalid())
1668       return true;
1669     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1670                                  RHS.get(), AA_Assigning))
1671       return true;
1672   }
1673 
1674   // For NEON intrinsics which take an immediate value as part of the
1675   // instruction, range check them here.
1676   unsigned i = 0, l = 0, u = 0;
1677   switch (BuiltinID) {
1678   default:
1679     return false;
1680   #define GET_NEON_IMMEDIATE_CHECK
1681   #include "clang/Basic/arm_neon.inc"
1682   #include "clang/Basic/arm_fp16.inc"
1683   #undef GET_NEON_IMMEDIATE_CHECK
1684   }
1685 
1686   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1687 }
1688 
1689 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1690                                         unsigned MaxWidth) {
1691   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1692           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1693           BuiltinID == ARM::BI__builtin_arm_strex ||
1694           BuiltinID == ARM::BI__builtin_arm_stlex ||
1695           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1696           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1697           BuiltinID == AArch64::BI__builtin_arm_strex ||
1698           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1699          "unexpected ARM builtin");
1700   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1701                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1702                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1703                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1704 
1705   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1706 
1707   // Ensure that we have the proper number of arguments.
1708   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1709     return true;
1710 
1711   // Inspect the pointer argument of the atomic builtin.  This should always be
1712   // a pointer type, whose element is an integral scalar or pointer type.
1713   // Because it is a pointer type, we don't have to worry about any implicit
1714   // casts here.
1715   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1716   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1717   if (PointerArgRes.isInvalid())
1718     return true;
1719   PointerArg = PointerArgRes.get();
1720 
1721   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1722   if (!pointerType) {
1723     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1724         << PointerArg->getType() << PointerArg->getSourceRange();
1725     return true;
1726   }
1727 
1728   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1729   // task is to insert the appropriate casts into the AST. First work out just
1730   // what the appropriate type is.
1731   QualType ValType = pointerType->getPointeeType();
1732   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1733   if (IsLdrex)
1734     AddrType.addConst();
1735 
1736   // Issue a warning if the cast is dodgy.
1737   CastKind CastNeeded = CK_NoOp;
1738   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1739     CastNeeded = CK_BitCast;
1740     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1741         << PointerArg->getType() << Context.getPointerType(AddrType)
1742         << AA_Passing << PointerArg->getSourceRange();
1743   }
1744 
1745   // Finally, do the cast and replace the argument with the corrected version.
1746   AddrType = Context.getPointerType(AddrType);
1747   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1748   if (PointerArgRes.isInvalid())
1749     return true;
1750   PointerArg = PointerArgRes.get();
1751 
1752   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1753 
1754   // In general, we allow ints, floats and pointers to be loaded and stored.
1755   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1756       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1757     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1758         << PointerArg->getType() << PointerArg->getSourceRange();
1759     return true;
1760   }
1761 
1762   // But ARM doesn't have instructions to deal with 128-bit versions.
1763   if (Context.getTypeSize(ValType) > MaxWidth) {
1764     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1765     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1766         << PointerArg->getType() << PointerArg->getSourceRange();
1767     return true;
1768   }
1769 
1770   switch (ValType.getObjCLifetime()) {
1771   case Qualifiers::OCL_None:
1772   case Qualifiers::OCL_ExplicitNone:
1773     // okay
1774     break;
1775 
1776   case Qualifiers::OCL_Weak:
1777   case Qualifiers::OCL_Strong:
1778   case Qualifiers::OCL_Autoreleasing:
1779     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1780         << ValType << PointerArg->getSourceRange();
1781     return true;
1782   }
1783 
1784   if (IsLdrex) {
1785     TheCall->setType(ValType);
1786     return false;
1787   }
1788 
1789   // Initialize the argument to be stored.
1790   ExprResult ValArg = TheCall->getArg(0);
1791   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1792       Context, ValType, /*consume*/ false);
1793   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1794   if (ValArg.isInvalid())
1795     return true;
1796   TheCall->setArg(0, ValArg.get());
1797 
1798   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1799   // but the custom checker bypasses all default analysis.
1800   TheCall->setType(Context.IntTy);
1801   return false;
1802 }
1803 
1804 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1805   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1806       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1807       BuiltinID == ARM::BI__builtin_arm_strex ||
1808       BuiltinID == ARM::BI__builtin_arm_stlex) {
1809     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1810   }
1811 
1812   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1813     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1814       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1815   }
1816 
1817   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1818       BuiltinID == ARM::BI__builtin_arm_wsr64)
1819     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1820 
1821   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1822       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1823       BuiltinID == ARM::BI__builtin_arm_wsr ||
1824       BuiltinID == ARM::BI__builtin_arm_wsrp)
1825     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1826 
1827   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1828     return true;
1829 
1830   // For intrinsics which take an immediate value as part of the instruction,
1831   // range check them here.
1832   // FIXME: VFP Intrinsics should error if VFP not present.
1833   switch (BuiltinID) {
1834   default: return false;
1835   case ARM::BI__builtin_arm_ssat:
1836     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1837   case ARM::BI__builtin_arm_usat:
1838     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1839   case ARM::BI__builtin_arm_ssat16:
1840     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1841   case ARM::BI__builtin_arm_usat16:
1842     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1843   case ARM::BI__builtin_arm_vcvtr_f:
1844   case ARM::BI__builtin_arm_vcvtr_d:
1845     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1846   case ARM::BI__builtin_arm_dmb:
1847   case ARM::BI__builtin_arm_dsb:
1848   case ARM::BI__builtin_arm_isb:
1849   case ARM::BI__builtin_arm_dbg:
1850     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1851   }
1852 }
1853 
1854 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1855                                          CallExpr *TheCall) {
1856   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1857       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1858       BuiltinID == AArch64::BI__builtin_arm_strex ||
1859       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1860     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1861   }
1862 
1863   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1864     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1865       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1866       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1867       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1868   }
1869 
1870   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1871       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1872     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1873 
1874   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1875       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1876       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1877       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1878     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1879 
1880   // Only check the valid encoding range. Any constant in this range would be
1881   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1882   // an exception for incorrect registers. This matches MSVC behavior.
1883   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1884       BuiltinID == AArch64::BI_WriteStatusReg)
1885     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1886 
1887   if (BuiltinID == AArch64::BI__getReg)
1888     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1889 
1890   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1891     return true;
1892 
1893   // For intrinsics which take an immediate value as part of the instruction,
1894   // range check them here.
1895   unsigned i = 0, l = 0, u = 0;
1896   switch (BuiltinID) {
1897   default: return false;
1898   case AArch64::BI__builtin_arm_dmb:
1899   case AArch64::BI__builtin_arm_dsb:
1900   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1901   }
1902 
1903   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1904 }
1905 
1906 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1907   struct BuiltinAndString {
1908     unsigned BuiltinID;
1909     const char *Str;
1910   };
1911 
1912   static BuiltinAndString ValidCPU[] = {
1913     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1914     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1915     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1916     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1917     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1918     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1919     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1920     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1926     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1927     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1933     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1934     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1935     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1936   };
1937 
1938   static BuiltinAndString ValidHVX[] = {
1939     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1940     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1941     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1942     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1943     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1944     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1945     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1946     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1947     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1948     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1949     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1950     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1951     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1952     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1953     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1954     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1955     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1956     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1957     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1958     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1959     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1960     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1961     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1962     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1963     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1964     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1965     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1966     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1967     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1968     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1969     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1970     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1971     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1972     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1973     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1974     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1975     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1976     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2671   };
2672 
2673   // Sort the tables on first execution so we can binary search them.
2674   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2675     return LHS.BuiltinID < RHS.BuiltinID;
2676   };
2677   static const bool SortOnce =
2678       (llvm::sort(ValidCPU, SortCmp),
2679        llvm::sort(ValidHVX, SortCmp), true);
2680   (void)SortOnce;
2681   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2682     return BI.BuiltinID < BuiltinID;
2683   };
2684 
2685   const TargetInfo &TI = Context.getTargetInfo();
2686 
2687   const BuiltinAndString *FC =
2688       std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2689                        LowerBoundCmp);
2690   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2691     const TargetOptions &Opts = TI.getTargetOpts();
2692     StringRef CPU = Opts.CPU;
2693     if (!CPU.empty()) {
2694       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2695       CPU.consume_front("hexagon");
2696       SmallVector<StringRef, 3> CPUs;
2697       StringRef(FC->Str).split(CPUs, ',');
2698       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2699         return Diag(TheCall->getBeginLoc(),
2700                     diag::err_hexagon_builtin_unsupported_cpu);
2701     }
2702   }
2703 
2704   const BuiltinAndString *FH =
2705       std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2706                        LowerBoundCmp);
2707   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2708     if (!TI.hasFeature("hvx"))
2709       return Diag(TheCall->getBeginLoc(),
2710                   diag::err_hexagon_builtin_requires_hvx);
2711 
2712     SmallVector<StringRef, 3> HVXs;
2713     StringRef(FH->Str).split(HVXs, ',');
2714     bool IsValid = llvm::any_of(HVXs,
2715                                 [&TI] (StringRef V) {
2716                                   std::string F = "hvx" + V.str();
2717                                   return TI.hasFeature(F);
2718                                 });
2719     if (!IsValid)
2720       return Diag(TheCall->getBeginLoc(),
2721                   diag::err_hexagon_builtin_unsupported_hvx);
2722   }
2723 
2724   return false;
2725 }
2726 
2727 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2728   struct ArgInfo {
2729     uint8_t OpNum;
2730     bool IsSigned;
2731     uint8_t BitWidth;
2732     uint8_t Align;
2733   };
2734   struct BuiltinInfo {
2735     unsigned BuiltinID;
2736     ArgInfo Infos[2];
2737   };
2738 
2739   static BuiltinInfo Infos[] = {
2740     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2741     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2742     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2743     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2744     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2745     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2746     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2747     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2748     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2749     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2750     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2751 
2752     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2755     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2756     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2757     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2761     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2762     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2763 
2764     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2816                                                       {{ 1, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2824                                                       {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2831                                                        { 2, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2833                                                        { 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2835                                                        { 3, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2837                                                        { 3, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2854                                                       {{ 2, false, 4,  0 },
2855                                                        { 3, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2857                                                       {{ 2, false, 4,  0 },
2858                                                        { 3, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2860                                                       {{ 2, false, 4,  0 },
2861                                                        { 3, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2863                                                       {{ 2, false, 4,  0 },
2864                                                        { 3, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2876                                                        { 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2878                                                        { 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2888                                                       {{ 1, false, 4,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2891                                                       {{ 1, false, 4,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2912                                                       {{ 3, false, 1,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2917                                                       {{ 3, false, 1,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2922                                                       {{ 3, false, 1,  0 }} },
2923   };
2924 
2925   // Use a dynamically initialized static to sort the table exactly once on
2926   // first run.
2927   static const bool SortOnce =
2928       (llvm::sort(Infos,
2929                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2930                    return LHS.BuiltinID < RHS.BuiltinID;
2931                  }),
2932        true);
2933   (void)SortOnce;
2934 
2935   const BuiltinInfo *F =
2936       std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2937                        [](const BuiltinInfo &BI, unsigned BuiltinID) {
2938                          return BI.BuiltinID < BuiltinID;
2939                        });
2940   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2941     return false;
2942 
2943   bool Error = false;
2944 
2945   for (const ArgInfo &A : F->Infos) {
2946     // Ignore empty ArgInfo elements.
2947     if (A.BitWidth == 0)
2948       continue;
2949 
2950     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2951     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2952     if (!A.Align) {
2953       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2954     } else {
2955       unsigned M = 1 << A.Align;
2956       Min *= M;
2957       Max *= M;
2958       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2959                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2960     }
2961   }
2962   return Error;
2963 }
2964 
2965 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2966                                            CallExpr *TheCall) {
2967   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2968          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2969 }
2970 
2971 
2972 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2973 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2974 // ordering for DSP is unspecified. MSA is ordered by the data format used
2975 // by the underlying instruction i.e., df/m, df/n and then by size.
2976 //
2977 // FIXME: The size tests here should instead be tablegen'd along with the
2978 //        definitions from include/clang/Basic/BuiltinsMips.def.
2979 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2980 //        be too.
2981 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2982   unsigned i = 0, l = 0, u = 0, m = 0;
2983   switch (BuiltinID) {
2984   default: return false;
2985   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2986   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2987   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2988   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2989   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2990   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2991   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2992   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2993   // df/m field.
2994   // These intrinsics take an unsigned 3 bit immediate.
2995   case Mips::BI__builtin_msa_bclri_b:
2996   case Mips::BI__builtin_msa_bnegi_b:
2997   case Mips::BI__builtin_msa_bseti_b:
2998   case Mips::BI__builtin_msa_sat_s_b:
2999   case Mips::BI__builtin_msa_sat_u_b:
3000   case Mips::BI__builtin_msa_slli_b:
3001   case Mips::BI__builtin_msa_srai_b:
3002   case Mips::BI__builtin_msa_srari_b:
3003   case Mips::BI__builtin_msa_srli_b:
3004   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3005   case Mips::BI__builtin_msa_binsli_b:
3006   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3007   // These intrinsics take an unsigned 4 bit immediate.
3008   case Mips::BI__builtin_msa_bclri_h:
3009   case Mips::BI__builtin_msa_bnegi_h:
3010   case Mips::BI__builtin_msa_bseti_h:
3011   case Mips::BI__builtin_msa_sat_s_h:
3012   case Mips::BI__builtin_msa_sat_u_h:
3013   case Mips::BI__builtin_msa_slli_h:
3014   case Mips::BI__builtin_msa_srai_h:
3015   case Mips::BI__builtin_msa_srari_h:
3016   case Mips::BI__builtin_msa_srli_h:
3017   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3018   case Mips::BI__builtin_msa_binsli_h:
3019   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3020   // These intrinsics take an unsigned 5 bit immediate.
3021   // The first block of intrinsics actually have an unsigned 5 bit field,
3022   // not a df/n field.
3023   case Mips::BI__builtin_msa_clei_u_b:
3024   case Mips::BI__builtin_msa_clei_u_h:
3025   case Mips::BI__builtin_msa_clei_u_w:
3026   case Mips::BI__builtin_msa_clei_u_d:
3027   case Mips::BI__builtin_msa_clti_u_b:
3028   case Mips::BI__builtin_msa_clti_u_h:
3029   case Mips::BI__builtin_msa_clti_u_w:
3030   case Mips::BI__builtin_msa_clti_u_d:
3031   case Mips::BI__builtin_msa_maxi_u_b:
3032   case Mips::BI__builtin_msa_maxi_u_h:
3033   case Mips::BI__builtin_msa_maxi_u_w:
3034   case Mips::BI__builtin_msa_maxi_u_d:
3035   case Mips::BI__builtin_msa_mini_u_b:
3036   case Mips::BI__builtin_msa_mini_u_h:
3037   case Mips::BI__builtin_msa_mini_u_w:
3038   case Mips::BI__builtin_msa_mini_u_d:
3039   case Mips::BI__builtin_msa_addvi_b:
3040   case Mips::BI__builtin_msa_addvi_h:
3041   case Mips::BI__builtin_msa_addvi_w:
3042   case Mips::BI__builtin_msa_addvi_d:
3043   case Mips::BI__builtin_msa_bclri_w:
3044   case Mips::BI__builtin_msa_bnegi_w:
3045   case Mips::BI__builtin_msa_bseti_w:
3046   case Mips::BI__builtin_msa_sat_s_w:
3047   case Mips::BI__builtin_msa_sat_u_w:
3048   case Mips::BI__builtin_msa_slli_w:
3049   case Mips::BI__builtin_msa_srai_w:
3050   case Mips::BI__builtin_msa_srari_w:
3051   case Mips::BI__builtin_msa_srli_w:
3052   case Mips::BI__builtin_msa_srlri_w:
3053   case Mips::BI__builtin_msa_subvi_b:
3054   case Mips::BI__builtin_msa_subvi_h:
3055   case Mips::BI__builtin_msa_subvi_w:
3056   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3057   case Mips::BI__builtin_msa_binsli_w:
3058   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3059   // These intrinsics take an unsigned 6 bit immediate.
3060   case Mips::BI__builtin_msa_bclri_d:
3061   case Mips::BI__builtin_msa_bnegi_d:
3062   case Mips::BI__builtin_msa_bseti_d:
3063   case Mips::BI__builtin_msa_sat_s_d:
3064   case Mips::BI__builtin_msa_sat_u_d:
3065   case Mips::BI__builtin_msa_slli_d:
3066   case Mips::BI__builtin_msa_srai_d:
3067   case Mips::BI__builtin_msa_srari_d:
3068   case Mips::BI__builtin_msa_srli_d:
3069   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3070   case Mips::BI__builtin_msa_binsli_d:
3071   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3072   // These intrinsics take a signed 5 bit immediate.
3073   case Mips::BI__builtin_msa_ceqi_b:
3074   case Mips::BI__builtin_msa_ceqi_h:
3075   case Mips::BI__builtin_msa_ceqi_w:
3076   case Mips::BI__builtin_msa_ceqi_d:
3077   case Mips::BI__builtin_msa_clti_s_b:
3078   case Mips::BI__builtin_msa_clti_s_h:
3079   case Mips::BI__builtin_msa_clti_s_w:
3080   case Mips::BI__builtin_msa_clti_s_d:
3081   case Mips::BI__builtin_msa_clei_s_b:
3082   case Mips::BI__builtin_msa_clei_s_h:
3083   case Mips::BI__builtin_msa_clei_s_w:
3084   case Mips::BI__builtin_msa_clei_s_d:
3085   case Mips::BI__builtin_msa_maxi_s_b:
3086   case Mips::BI__builtin_msa_maxi_s_h:
3087   case Mips::BI__builtin_msa_maxi_s_w:
3088   case Mips::BI__builtin_msa_maxi_s_d:
3089   case Mips::BI__builtin_msa_mini_s_b:
3090   case Mips::BI__builtin_msa_mini_s_h:
3091   case Mips::BI__builtin_msa_mini_s_w:
3092   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3093   // These intrinsics take an unsigned 8 bit immediate.
3094   case Mips::BI__builtin_msa_andi_b:
3095   case Mips::BI__builtin_msa_nori_b:
3096   case Mips::BI__builtin_msa_ori_b:
3097   case Mips::BI__builtin_msa_shf_b:
3098   case Mips::BI__builtin_msa_shf_h:
3099   case Mips::BI__builtin_msa_shf_w:
3100   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3101   case Mips::BI__builtin_msa_bseli_b:
3102   case Mips::BI__builtin_msa_bmnzi_b:
3103   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3104   // df/n format
3105   // These intrinsics take an unsigned 4 bit immediate.
3106   case Mips::BI__builtin_msa_copy_s_b:
3107   case Mips::BI__builtin_msa_copy_u_b:
3108   case Mips::BI__builtin_msa_insve_b:
3109   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3110   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3111   // These intrinsics take an unsigned 3 bit immediate.
3112   case Mips::BI__builtin_msa_copy_s_h:
3113   case Mips::BI__builtin_msa_copy_u_h:
3114   case Mips::BI__builtin_msa_insve_h:
3115   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3116   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3117   // These intrinsics take an unsigned 2 bit immediate.
3118   case Mips::BI__builtin_msa_copy_s_w:
3119   case Mips::BI__builtin_msa_copy_u_w:
3120   case Mips::BI__builtin_msa_insve_w:
3121   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3122   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3123   // These intrinsics take an unsigned 1 bit immediate.
3124   case Mips::BI__builtin_msa_copy_s_d:
3125   case Mips::BI__builtin_msa_copy_u_d:
3126   case Mips::BI__builtin_msa_insve_d:
3127   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3128   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3129   // Memory offsets and immediate loads.
3130   // These intrinsics take a signed 10 bit immediate.
3131   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3132   case Mips::BI__builtin_msa_ldi_h:
3133   case Mips::BI__builtin_msa_ldi_w:
3134   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3135   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3136   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3137   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3138   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3139   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3140   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3141   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3142   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3143   }
3144 
3145   if (!m)
3146     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3147 
3148   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3149          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3150 }
3151 
3152 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3153   unsigned i = 0, l = 0, u = 0;
3154   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3155                       BuiltinID == PPC::BI__builtin_divdeu ||
3156                       BuiltinID == PPC::BI__builtin_bpermd;
3157   bool IsTarget64Bit = Context.getTargetInfo()
3158                               .getTypeWidth(Context
3159                                             .getTargetInfo()
3160                                             .getIntPtrType()) == 64;
3161   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3162                        BuiltinID == PPC::BI__builtin_divweu ||
3163                        BuiltinID == PPC::BI__builtin_divde ||
3164                        BuiltinID == PPC::BI__builtin_divdeu;
3165 
3166   if (Is64BitBltin && !IsTarget64Bit)
3167     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3168            << TheCall->getSourceRange();
3169 
3170   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3171       (BuiltinID == PPC::BI__builtin_bpermd &&
3172        !Context.getTargetInfo().hasFeature("bpermd")))
3173     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3174            << TheCall->getSourceRange();
3175 
3176   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3177     if (!Context.getTargetInfo().hasFeature("vsx"))
3178       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3179              << TheCall->getSourceRange();
3180     return false;
3181   };
3182 
3183   switch (BuiltinID) {
3184   default: return false;
3185   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3186   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3187     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3188            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3189   case PPC::BI__builtin_tbegin:
3190   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3191   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3192   case PPC::BI__builtin_tabortwc:
3193   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3194   case PPC::BI__builtin_tabortwci:
3195   case PPC::BI__builtin_tabortdci:
3196     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3197            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3198   case PPC::BI__builtin_vsx_xxpermdi:
3199   case PPC::BI__builtin_vsx_xxsldwi:
3200     return SemaBuiltinVSX(TheCall);
3201   case PPC::BI__builtin_unpack_vector_int128:
3202     return SemaVSXCheck(TheCall) ||
3203            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3204   case PPC::BI__builtin_pack_vector_int128:
3205     return SemaVSXCheck(TheCall);
3206   }
3207   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3208 }
3209 
3210 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3211                                            CallExpr *TheCall) {
3212   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3213     Expr *Arg = TheCall->getArg(0);
3214     llvm::APSInt AbortCode(32);
3215     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3216         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3217       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3218              << Arg->getSourceRange();
3219   }
3220 
3221   // For intrinsics which take an immediate value as part of the instruction,
3222   // range check them here.
3223   unsigned i = 0, l = 0, u = 0;
3224   switch (BuiltinID) {
3225   default: return false;
3226   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3227   case SystemZ::BI__builtin_s390_verimb:
3228   case SystemZ::BI__builtin_s390_verimh:
3229   case SystemZ::BI__builtin_s390_verimf:
3230   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3231   case SystemZ::BI__builtin_s390_vfaeb:
3232   case SystemZ::BI__builtin_s390_vfaeh:
3233   case SystemZ::BI__builtin_s390_vfaef:
3234   case SystemZ::BI__builtin_s390_vfaebs:
3235   case SystemZ::BI__builtin_s390_vfaehs:
3236   case SystemZ::BI__builtin_s390_vfaefs:
3237   case SystemZ::BI__builtin_s390_vfaezb:
3238   case SystemZ::BI__builtin_s390_vfaezh:
3239   case SystemZ::BI__builtin_s390_vfaezf:
3240   case SystemZ::BI__builtin_s390_vfaezbs:
3241   case SystemZ::BI__builtin_s390_vfaezhs:
3242   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3243   case SystemZ::BI__builtin_s390_vfisb:
3244   case SystemZ::BI__builtin_s390_vfidb:
3245     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3246            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3247   case SystemZ::BI__builtin_s390_vftcisb:
3248   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3249   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3250   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3251   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3252   case SystemZ::BI__builtin_s390_vstrcb:
3253   case SystemZ::BI__builtin_s390_vstrch:
3254   case SystemZ::BI__builtin_s390_vstrcf:
3255   case SystemZ::BI__builtin_s390_vstrczb:
3256   case SystemZ::BI__builtin_s390_vstrczh:
3257   case SystemZ::BI__builtin_s390_vstrczf:
3258   case SystemZ::BI__builtin_s390_vstrcbs:
3259   case SystemZ::BI__builtin_s390_vstrchs:
3260   case SystemZ::BI__builtin_s390_vstrcfs:
3261   case SystemZ::BI__builtin_s390_vstrczbs:
3262   case SystemZ::BI__builtin_s390_vstrczhs:
3263   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3264   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3265   case SystemZ::BI__builtin_s390_vfminsb:
3266   case SystemZ::BI__builtin_s390_vfmaxsb:
3267   case SystemZ::BI__builtin_s390_vfmindb:
3268   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3269   }
3270   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3271 }
3272 
3273 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3274 /// This checks that the target supports __builtin_cpu_supports and
3275 /// that the string argument is constant and valid.
3276 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3277   Expr *Arg = TheCall->getArg(0);
3278 
3279   // Check if the argument is a string literal.
3280   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3281     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3282            << Arg->getSourceRange();
3283 
3284   // Check the contents of the string.
3285   StringRef Feature =
3286       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3287   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3288     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3289            << Arg->getSourceRange();
3290   return false;
3291 }
3292 
3293 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3294 /// This checks that the target supports __builtin_cpu_is and
3295 /// that the string argument is constant and valid.
3296 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3297   Expr *Arg = TheCall->getArg(0);
3298 
3299   // Check if the argument is a string literal.
3300   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3301     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3302            << Arg->getSourceRange();
3303 
3304   // Check the contents of the string.
3305   StringRef Feature =
3306       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3307   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3308     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3309            << Arg->getSourceRange();
3310   return false;
3311 }
3312 
3313 // Check if the rounding mode is legal.
3314 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3315   // Indicates if this instruction has rounding control or just SAE.
3316   bool HasRC = false;
3317 
3318   unsigned ArgNum = 0;
3319   switch (BuiltinID) {
3320   default:
3321     return false;
3322   case X86::BI__builtin_ia32_vcvttsd2si32:
3323   case X86::BI__builtin_ia32_vcvttsd2si64:
3324   case X86::BI__builtin_ia32_vcvttsd2usi32:
3325   case X86::BI__builtin_ia32_vcvttsd2usi64:
3326   case X86::BI__builtin_ia32_vcvttss2si32:
3327   case X86::BI__builtin_ia32_vcvttss2si64:
3328   case X86::BI__builtin_ia32_vcvttss2usi32:
3329   case X86::BI__builtin_ia32_vcvttss2usi64:
3330     ArgNum = 1;
3331     break;
3332   case X86::BI__builtin_ia32_maxpd512:
3333   case X86::BI__builtin_ia32_maxps512:
3334   case X86::BI__builtin_ia32_minpd512:
3335   case X86::BI__builtin_ia32_minps512:
3336     ArgNum = 2;
3337     break;
3338   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3339   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3340   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3341   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3342   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3343   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3344   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3345   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3346   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3347   case X86::BI__builtin_ia32_exp2pd_mask:
3348   case X86::BI__builtin_ia32_exp2ps_mask:
3349   case X86::BI__builtin_ia32_getexppd512_mask:
3350   case X86::BI__builtin_ia32_getexpps512_mask:
3351   case X86::BI__builtin_ia32_rcp28pd_mask:
3352   case X86::BI__builtin_ia32_rcp28ps_mask:
3353   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3354   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3355   case X86::BI__builtin_ia32_vcomisd:
3356   case X86::BI__builtin_ia32_vcomiss:
3357   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3358     ArgNum = 3;
3359     break;
3360   case X86::BI__builtin_ia32_cmppd512_mask:
3361   case X86::BI__builtin_ia32_cmpps512_mask:
3362   case X86::BI__builtin_ia32_cmpsd_mask:
3363   case X86::BI__builtin_ia32_cmpss_mask:
3364   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3365   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3366   case X86::BI__builtin_ia32_getexpss128_round_mask:
3367   case X86::BI__builtin_ia32_maxsd_round_mask:
3368   case X86::BI__builtin_ia32_maxss_round_mask:
3369   case X86::BI__builtin_ia32_minsd_round_mask:
3370   case X86::BI__builtin_ia32_minss_round_mask:
3371   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3372   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3373   case X86::BI__builtin_ia32_reducepd512_mask:
3374   case X86::BI__builtin_ia32_reduceps512_mask:
3375   case X86::BI__builtin_ia32_rndscalepd_mask:
3376   case X86::BI__builtin_ia32_rndscaleps_mask:
3377   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3378   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3379     ArgNum = 4;
3380     break;
3381   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3382   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3383   case X86::BI__builtin_ia32_fixupimmps512_mask:
3384   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3385   case X86::BI__builtin_ia32_fixupimmsd_mask:
3386   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3387   case X86::BI__builtin_ia32_fixupimmss_mask:
3388   case X86::BI__builtin_ia32_fixupimmss_maskz:
3389   case X86::BI__builtin_ia32_rangepd512_mask:
3390   case X86::BI__builtin_ia32_rangeps512_mask:
3391   case X86::BI__builtin_ia32_rangesd128_round_mask:
3392   case X86::BI__builtin_ia32_rangess128_round_mask:
3393   case X86::BI__builtin_ia32_reducesd_mask:
3394   case X86::BI__builtin_ia32_reducess_mask:
3395   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3396   case X86::BI__builtin_ia32_rndscaless_round_mask:
3397     ArgNum = 5;
3398     break;
3399   case X86::BI__builtin_ia32_vcvtsd2si64:
3400   case X86::BI__builtin_ia32_vcvtsd2si32:
3401   case X86::BI__builtin_ia32_vcvtsd2usi32:
3402   case X86::BI__builtin_ia32_vcvtsd2usi64:
3403   case X86::BI__builtin_ia32_vcvtss2si32:
3404   case X86::BI__builtin_ia32_vcvtss2si64:
3405   case X86::BI__builtin_ia32_vcvtss2usi32:
3406   case X86::BI__builtin_ia32_vcvtss2usi64:
3407   case X86::BI__builtin_ia32_sqrtpd512:
3408   case X86::BI__builtin_ia32_sqrtps512:
3409     ArgNum = 1;
3410     HasRC = true;
3411     break;
3412   case X86::BI__builtin_ia32_addpd512:
3413   case X86::BI__builtin_ia32_addps512:
3414   case X86::BI__builtin_ia32_divpd512:
3415   case X86::BI__builtin_ia32_divps512:
3416   case X86::BI__builtin_ia32_mulpd512:
3417   case X86::BI__builtin_ia32_mulps512:
3418   case X86::BI__builtin_ia32_subpd512:
3419   case X86::BI__builtin_ia32_subps512:
3420   case X86::BI__builtin_ia32_cvtsi2sd64:
3421   case X86::BI__builtin_ia32_cvtsi2ss32:
3422   case X86::BI__builtin_ia32_cvtsi2ss64:
3423   case X86::BI__builtin_ia32_cvtusi2sd64:
3424   case X86::BI__builtin_ia32_cvtusi2ss32:
3425   case X86::BI__builtin_ia32_cvtusi2ss64:
3426     ArgNum = 2;
3427     HasRC = true;
3428     break;
3429   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3430   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3431   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3432   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3433   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3434   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3435   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3436   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3437   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3438   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3439   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3440   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3441   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3442   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3443   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3444     ArgNum = 3;
3445     HasRC = true;
3446     break;
3447   case X86::BI__builtin_ia32_addss_round_mask:
3448   case X86::BI__builtin_ia32_addsd_round_mask:
3449   case X86::BI__builtin_ia32_divss_round_mask:
3450   case X86::BI__builtin_ia32_divsd_round_mask:
3451   case X86::BI__builtin_ia32_mulss_round_mask:
3452   case X86::BI__builtin_ia32_mulsd_round_mask:
3453   case X86::BI__builtin_ia32_subss_round_mask:
3454   case X86::BI__builtin_ia32_subsd_round_mask:
3455   case X86::BI__builtin_ia32_scalefpd512_mask:
3456   case X86::BI__builtin_ia32_scalefps512_mask:
3457   case X86::BI__builtin_ia32_scalefsd_round_mask:
3458   case X86::BI__builtin_ia32_scalefss_round_mask:
3459   case X86::BI__builtin_ia32_getmantpd512_mask:
3460   case X86::BI__builtin_ia32_getmantps512_mask:
3461   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3462   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3463   case X86::BI__builtin_ia32_sqrtss_round_mask:
3464   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3465   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3466   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3467   case X86::BI__builtin_ia32_vfmaddss3_mask:
3468   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3469   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3470   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3471   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3472   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3473   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3474   case X86::BI__builtin_ia32_vfmaddps512_mask:
3475   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3476   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3477   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3478   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3479   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3480   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3481   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3482   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3483   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3484   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3485   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3486     ArgNum = 4;
3487     HasRC = true;
3488     break;
3489   case X86::BI__builtin_ia32_getmantsd_round_mask:
3490   case X86::BI__builtin_ia32_getmantss_round_mask:
3491     ArgNum = 5;
3492     HasRC = true;
3493     break;
3494   }
3495 
3496   llvm::APSInt Result;
3497 
3498   // We can't check the value of a dependent argument.
3499   Expr *Arg = TheCall->getArg(ArgNum);
3500   if (Arg->isTypeDependent() || Arg->isValueDependent())
3501     return false;
3502 
3503   // Check constant-ness first.
3504   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3505     return true;
3506 
3507   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3508   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3509   // combined with ROUND_NO_EXC.
3510   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3511       Result == 8/*ROUND_NO_EXC*/ ||
3512       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3513     return false;
3514 
3515   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3516          << Arg->getSourceRange();
3517 }
3518 
3519 // Check if the gather/scatter scale is legal.
3520 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3521                                              CallExpr *TheCall) {
3522   unsigned ArgNum = 0;
3523   switch (BuiltinID) {
3524   default:
3525     return false;
3526   case X86::BI__builtin_ia32_gatherpfdpd:
3527   case X86::BI__builtin_ia32_gatherpfdps:
3528   case X86::BI__builtin_ia32_gatherpfqpd:
3529   case X86::BI__builtin_ia32_gatherpfqps:
3530   case X86::BI__builtin_ia32_scatterpfdpd:
3531   case X86::BI__builtin_ia32_scatterpfdps:
3532   case X86::BI__builtin_ia32_scatterpfqpd:
3533   case X86::BI__builtin_ia32_scatterpfqps:
3534     ArgNum = 3;
3535     break;
3536   case X86::BI__builtin_ia32_gatherd_pd:
3537   case X86::BI__builtin_ia32_gatherd_pd256:
3538   case X86::BI__builtin_ia32_gatherq_pd:
3539   case X86::BI__builtin_ia32_gatherq_pd256:
3540   case X86::BI__builtin_ia32_gatherd_ps:
3541   case X86::BI__builtin_ia32_gatherd_ps256:
3542   case X86::BI__builtin_ia32_gatherq_ps:
3543   case X86::BI__builtin_ia32_gatherq_ps256:
3544   case X86::BI__builtin_ia32_gatherd_q:
3545   case X86::BI__builtin_ia32_gatherd_q256:
3546   case X86::BI__builtin_ia32_gatherq_q:
3547   case X86::BI__builtin_ia32_gatherq_q256:
3548   case X86::BI__builtin_ia32_gatherd_d:
3549   case X86::BI__builtin_ia32_gatherd_d256:
3550   case X86::BI__builtin_ia32_gatherq_d:
3551   case X86::BI__builtin_ia32_gatherq_d256:
3552   case X86::BI__builtin_ia32_gather3div2df:
3553   case X86::BI__builtin_ia32_gather3div2di:
3554   case X86::BI__builtin_ia32_gather3div4df:
3555   case X86::BI__builtin_ia32_gather3div4di:
3556   case X86::BI__builtin_ia32_gather3div4sf:
3557   case X86::BI__builtin_ia32_gather3div4si:
3558   case X86::BI__builtin_ia32_gather3div8sf:
3559   case X86::BI__builtin_ia32_gather3div8si:
3560   case X86::BI__builtin_ia32_gather3siv2df:
3561   case X86::BI__builtin_ia32_gather3siv2di:
3562   case X86::BI__builtin_ia32_gather3siv4df:
3563   case X86::BI__builtin_ia32_gather3siv4di:
3564   case X86::BI__builtin_ia32_gather3siv4sf:
3565   case X86::BI__builtin_ia32_gather3siv4si:
3566   case X86::BI__builtin_ia32_gather3siv8sf:
3567   case X86::BI__builtin_ia32_gather3siv8si:
3568   case X86::BI__builtin_ia32_gathersiv8df:
3569   case X86::BI__builtin_ia32_gathersiv16sf:
3570   case X86::BI__builtin_ia32_gatherdiv8df:
3571   case X86::BI__builtin_ia32_gatherdiv16sf:
3572   case X86::BI__builtin_ia32_gathersiv8di:
3573   case X86::BI__builtin_ia32_gathersiv16si:
3574   case X86::BI__builtin_ia32_gatherdiv8di:
3575   case X86::BI__builtin_ia32_gatherdiv16si:
3576   case X86::BI__builtin_ia32_scatterdiv2df:
3577   case X86::BI__builtin_ia32_scatterdiv2di:
3578   case X86::BI__builtin_ia32_scatterdiv4df:
3579   case X86::BI__builtin_ia32_scatterdiv4di:
3580   case X86::BI__builtin_ia32_scatterdiv4sf:
3581   case X86::BI__builtin_ia32_scatterdiv4si:
3582   case X86::BI__builtin_ia32_scatterdiv8sf:
3583   case X86::BI__builtin_ia32_scatterdiv8si:
3584   case X86::BI__builtin_ia32_scattersiv2df:
3585   case X86::BI__builtin_ia32_scattersiv2di:
3586   case X86::BI__builtin_ia32_scattersiv4df:
3587   case X86::BI__builtin_ia32_scattersiv4di:
3588   case X86::BI__builtin_ia32_scattersiv4sf:
3589   case X86::BI__builtin_ia32_scattersiv4si:
3590   case X86::BI__builtin_ia32_scattersiv8sf:
3591   case X86::BI__builtin_ia32_scattersiv8si:
3592   case X86::BI__builtin_ia32_scattersiv8df:
3593   case X86::BI__builtin_ia32_scattersiv16sf:
3594   case X86::BI__builtin_ia32_scatterdiv8df:
3595   case X86::BI__builtin_ia32_scatterdiv16sf:
3596   case X86::BI__builtin_ia32_scattersiv8di:
3597   case X86::BI__builtin_ia32_scattersiv16si:
3598   case X86::BI__builtin_ia32_scatterdiv8di:
3599   case X86::BI__builtin_ia32_scatterdiv16si:
3600     ArgNum = 4;
3601     break;
3602   }
3603 
3604   llvm::APSInt Result;
3605 
3606   // We can't check the value of a dependent argument.
3607   Expr *Arg = TheCall->getArg(ArgNum);
3608   if (Arg->isTypeDependent() || Arg->isValueDependent())
3609     return false;
3610 
3611   // Check constant-ness first.
3612   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3613     return true;
3614 
3615   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3616     return false;
3617 
3618   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3619          << Arg->getSourceRange();
3620 }
3621 
3622 static bool isX86_32Builtin(unsigned BuiltinID) {
3623   // These builtins only work on x86-32 targets.
3624   switch (BuiltinID) {
3625   case X86::BI__builtin_ia32_readeflags_u32:
3626   case X86::BI__builtin_ia32_writeeflags_u32:
3627     return true;
3628   }
3629 
3630   return false;
3631 }
3632 
3633 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3634   if (BuiltinID == X86::BI__builtin_cpu_supports)
3635     return SemaBuiltinCpuSupports(*this, TheCall);
3636 
3637   if (BuiltinID == X86::BI__builtin_cpu_is)
3638     return SemaBuiltinCpuIs(*this, TheCall);
3639 
3640   // Check for 32-bit only builtins on a 64-bit target.
3641   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3642   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3643     return Diag(TheCall->getCallee()->getBeginLoc(),
3644                 diag::err_32_bit_builtin_64_bit_tgt);
3645 
3646   // If the intrinsic has rounding or SAE make sure its valid.
3647   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3648     return true;
3649 
3650   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3651   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3652     return true;
3653 
3654   // For intrinsics which take an immediate value as part of the instruction,
3655   // range check them here.
3656   int i = 0, l = 0, u = 0;
3657   switch (BuiltinID) {
3658   default:
3659     return false;
3660   case X86::BI__builtin_ia32_vec_ext_v2si:
3661   case X86::BI__builtin_ia32_vec_ext_v2di:
3662   case X86::BI__builtin_ia32_vextractf128_pd256:
3663   case X86::BI__builtin_ia32_vextractf128_ps256:
3664   case X86::BI__builtin_ia32_vextractf128_si256:
3665   case X86::BI__builtin_ia32_extract128i256:
3666   case X86::BI__builtin_ia32_extractf64x4_mask:
3667   case X86::BI__builtin_ia32_extracti64x4_mask:
3668   case X86::BI__builtin_ia32_extractf32x8_mask:
3669   case X86::BI__builtin_ia32_extracti32x8_mask:
3670   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3671   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3672   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3673   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3674     i = 1; l = 0; u = 1;
3675     break;
3676   case X86::BI__builtin_ia32_vec_set_v2di:
3677   case X86::BI__builtin_ia32_vinsertf128_pd256:
3678   case X86::BI__builtin_ia32_vinsertf128_ps256:
3679   case X86::BI__builtin_ia32_vinsertf128_si256:
3680   case X86::BI__builtin_ia32_insert128i256:
3681   case X86::BI__builtin_ia32_insertf32x8:
3682   case X86::BI__builtin_ia32_inserti32x8:
3683   case X86::BI__builtin_ia32_insertf64x4:
3684   case X86::BI__builtin_ia32_inserti64x4:
3685   case X86::BI__builtin_ia32_insertf64x2_256:
3686   case X86::BI__builtin_ia32_inserti64x2_256:
3687   case X86::BI__builtin_ia32_insertf32x4_256:
3688   case X86::BI__builtin_ia32_inserti32x4_256:
3689     i = 2; l = 0; u = 1;
3690     break;
3691   case X86::BI__builtin_ia32_vpermilpd:
3692   case X86::BI__builtin_ia32_vec_ext_v4hi:
3693   case X86::BI__builtin_ia32_vec_ext_v4si:
3694   case X86::BI__builtin_ia32_vec_ext_v4sf:
3695   case X86::BI__builtin_ia32_vec_ext_v4di:
3696   case X86::BI__builtin_ia32_extractf32x4_mask:
3697   case X86::BI__builtin_ia32_extracti32x4_mask:
3698   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3699   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3700     i = 1; l = 0; u = 3;
3701     break;
3702   case X86::BI_mm_prefetch:
3703   case X86::BI__builtin_ia32_vec_ext_v8hi:
3704   case X86::BI__builtin_ia32_vec_ext_v8si:
3705     i = 1; l = 0; u = 7;
3706     break;
3707   case X86::BI__builtin_ia32_sha1rnds4:
3708   case X86::BI__builtin_ia32_blendpd:
3709   case X86::BI__builtin_ia32_shufpd:
3710   case X86::BI__builtin_ia32_vec_set_v4hi:
3711   case X86::BI__builtin_ia32_vec_set_v4si:
3712   case X86::BI__builtin_ia32_vec_set_v4di:
3713   case X86::BI__builtin_ia32_shuf_f32x4_256:
3714   case X86::BI__builtin_ia32_shuf_f64x2_256:
3715   case X86::BI__builtin_ia32_shuf_i32x4_256:
3716   case X86::BI__builtin_ia32_shuf_i64x2_256:
3717   case X86::BI__builtin_ia32_insertf64x2_512:
3718   case X86::BI__builtin_ia32_inserti64x2_512:
3719   case X86::BI__builtin_ia32_insertf32x4:
3720   case X86::BI__builtin_ia32_inserti32x4:
3721     i = 2; l = 0; u = 3;
3722     break;
3723   case X86::BI__builtin_ia32_vpermil2pd:
3724   case X86::BI__builtin_ia32_vpermil2pd256:
3725   case X86::BI__builtin_ia32_vpermil2ps:
3726   case X86::BI__builtin_ia32_vpermil2ps256:
3727     i = 3; l = 0; u = 3;
3728     break;
3729   case X86::BI__builtin_ia32_cmpb128_mask:
3730   case X86::BI__builtin_ia32_cmpw128_mask:
3731   case X86::BI__builtin_ia32_cmpd128_mask:
3732   case X86::BI__builtin_ia32_cmpq128_mask:
3733   case X86::BI__builtin_ia32_cmpb256_mask:
3734   case X86::BI__builtin_ia32_cmpw256_mask:
3735   case X86::BI__builtin_ia32_cmpd256_mask:
3736   case X86::BI__builtin_ia32_cmpq256_mask:
3737   case X86::BI__builtin_ia32_cmpb512_mask:
3738   case X86::BI__builtin_ia32_cmpw512_mask:
3739   case X86::BI__builtin_ia32_cmpd512_mask:
3740   case X86::BI__builtin_ia32_cmpq512_mask:
3741   case X86::BI__builtin_ia32_ucmpb128_mask:
3742   case X86::BI__builtin_ia32_ucmpw128_mask:
3743   case X86::BI__builtin_ia32_ucmpd128_mask:
3744   case X86::BI__builtin_ia32_ucmpq128_mask:
3745   case X86::BI__builtin_ia32_ucmpb256_mask:
3746   case X86::BI__builtin_ia32_ucmpw256_mask:
3747   case X86::BI__builtin_ia32_ucmpd256_mask:
3748   case X86::BI__builtin_ia32_ucmpq256_mask:
3749   case X86::BI__builtin_ia32_ucmpb512_mask:
3750   case X86::BI__builtin_ia32_ucmpw512_mask:
3751   case X86::BI__builtin_ia32_ucmpd512_mask:
3752   case X86::BI__builtin_ia32_ucmpq512_mask:
3753   case X86::BI__builtin_ia32_vpcomub:
3754   case X86::BI__builtin_ia32_vpcomuw:
3755   case X86::BI__builtin_ia32_vpcomud:
3756   case X86::BI__builtin_ia32_vpcomuq:
3757   case X86::BI__builtin_ia32_vpcomb:
3758   case X86::BI__builtin_ia32_vpcomw:
3759   case X86::BI__builtin_ia32_vpcomd:
3760   case X86::BI__builtin_ia32_vpcomq:
3761   case X86::BI__builtin_ia32_vec_set_v8hi:
3762   case X86::BI__builtin_ia32_vec_set_v8si:
3763     i = 2; l = 0; u = 7;
3764     break;
3765   case X86::BI__builtin_ia32_vpermilpd256:
3766   case X86::BI__builtin_ia32_roundps:
3767   case X86::BI__builtin_ia32_roundpd:
3768   case X86::BI__builtin_ia32_roundps256:
3769   case X86::BI__builtin_ia32_roundpd256:
3770   case X86::BI__builtin_ia32_getmantpd128_mask:
3771   case X86::BI__builtin_ia32_getmantpd256_mask:
3772   case X86::BI__builtin_ia32_getmantps128_mask:
3773   case X86::BI__builtin_ia32_getmantps256_mask:
3774   case X86::BI__builtin_ia32_getmantpd512_mask:
3775   case X86::BI__builtin_ia32_getmantps512_mask:
3776   case X86::BI__builtin_ia32_vec_ext_v16qi:
3777   case X86::BI__builtin_ia32_vec_ext_v16hi:
3778     i = 1; l = 0; u = 15;
3779     break;
3780   case X86::BI__builtin_ia32_pblendd128:
3781   case X86::BI__builtin_ia32_blendps:
3782   case X86::BI__builtin_ia32_blendpd256:
3783   case X86::BI__builtin_ia32_shufpd256:
3784   case X86::BI__builtin_ia32_roundss:
3785   case X86::BI__builtin_ia32_roundsd:
3786   case X86::BI__builtin_ia32_rangepd128_mask:
3787   case X86::BI__builtin_ia32_rangepd256_mask:
3788   case X86::BI__builtin_ia32_rangepd512_mask:
3789   case X86::BI__builtin_ia32_rangeps128_mask:
3790   case X86::BI__builtin_ia32_rangeps256_mask:
3791   case X86::BI__builtin_ia32_rangeps512_mask:
3792   case X86::BI__builtin_ia32_getmantsd_round_mask:
3793   case X86::BI__builtin_ia32_getmantss_round_mask:
3794   case X86::BI__builtin_ia32_vec_set_v16qi:
3795   case X86::BI__builtin_ia32_vec_set_v16hi:
3796     i = 2; l = 0; u = 15;
3797     break;
3798   case X86::BI__builtin_ia32_vec_ext_v32qi:
3799     i = 1; l = 0; u = 31;
3800     break;
3801   case X86::BI__builtin_ia32_cmpps:
3802   case X86::BI__builtin_ia32_cmpss:
3803   case X86::BI__builtin_ia32_cmppd:
3804   case X86::BI__builtin_ia32_cmpsd:
3805   case X86::BI__builtin_ia32_cmpps256:
3806   case X86::BI__builtin_ia32_cmppd256:
3807   case X86::BI__builtin_ia32_cmpps128_mask:
3808   case X86::BI__builtin_ia32_cmppd128_mask:
3809   case X86::BI__builtin_ia32_cmpps256_mask:
3810   case X86::BI__builtin_ia32_cmppd256_mask:
3811   case X86::BI__builtin_ia32_cmpps512_mask:
3812   case X86::BI__builtin_ia32_cmppd512_mask:
3813   case X86::BI__builtin_ia32_cmpsd_mask:
3814   case X86::BI__builtin_ia32_cmpss_mask:
3815   case X86::BI__builtin_ia32_vec_set_v32qi:
3816     i = 2; l = 0; u = 31;
3817     break;
3818   case X86::BI__builtin_ia32_permdf256:
3819   case X86::BI__builtin_ia32_permdi256:
3820   case X86::BI__builtin_ia32_permdf512:
3821   case X86::BI__builtin_ia32_permdi512:
3822   case X86::BI__builtin_ia32_vpermilps:
3823   case X86::BI__builtin_ia32_vpermilps256:
3824   case X86::BI__builtin_ia32_vpermilpd512:
3825   case X86::BI__builtin_ia32_vpermilps512:
3826   case X86::BI__builtin_ia32_pshufd:
3827   case X86::BI__builtin_ia32_pshufd256:
3828   case X86::BI__builtin_ia32_pshufd512:
3829   case X86::BI__builtin_ia32_pshufhw:
3830   case X86::BI__builtin_ia32_pshufhw256:
3831   case X86::BI__builtin_ia32_pshufhw512:
3832   case X86::BI__builtin_ia32_pshuflw:
3833   case X86::BI__builtin_ia32_pshuflw256:
3834   case X86::BI__builtin_ia32_pshuflw512:
3835   case X86::BI__builtin_ia32_vcvtps2ph:
3836   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3837   case X86::BI__builtin_ia32_vcvtps2ph256:
3838   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3839   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3840   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3841   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3842   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3843   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3844   case X86::BI__builtin_ia32_rndscaleps_mask:
3845   case X86::BI__builtin_ia32_rndscalepd_mask:
3846   case X86::BI__builtin_ia32_reducepd128_mask:
3847   case X86::BI__builtin_ia32_reducepd256_mask:
3848   case X86::BI__builtin_ia32_reducepd512_mask:
3849   case X86::BI__builtin_ia32_reduceps128_mask:
3850   case X86::BI__builtin_ia32_reduceps256_mask:
3851   case X86::BI__builtin_ia32_reduceps512_mask:
3852   case X86::BI__builtin_ia32_prold512:
3853   case X86::BI__builtin_ia32_prolq512:
3854   case X86::BI__builtin_ia32_prold128:
3855   case X86::BI__builtin_ia32_prold256:
3856   case X86::BI__builtin_ia32_prolq128:
3857   case X86::BI__builtin_ia32_prolq256:
3858   case X86::BI__builtin_ia32_prord512:
3859   case X86::BI__builtin_ia32_prorq512:
3860   case X86::BI__builtin_ia32_prord128:
3861   case X86::BI__builtin_ia32_prord256:
3862   case X86::BI__builtin_ia32_prorq128:
3863   case X86::BI__builtin_ia32_prorq256:
3864   case X86::BI__builtin_ia32_fpclasspd128_mask:
3865   case X86::BI__builtin_ia32_fpclasspd256_mask:
3866   case X86::BI__builtin_ia32_fpclassps128_mask:
3867   case X86::BI__builtin_ia32_fpclassps256_mask:
3868   case X86::BI__builtin_ia32_fpclassps512_mask:
3869   case X86::BI__builtin_ia32_fpclasspd512_mask:
3870   case X86::BI__builtin_ia32_fpclasssd_mask:
3871   case X86::BI__builtin_ia32_fpclassss_mask:
3872   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3873   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3874   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3875   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3876   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3877   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3878   case X86::BI__builtin_ia32_kshiftliqi:
3879   case X86::BI__builtin_ia32_kshiftlihi:
3880   case X86::BI__builtin_ia32_kshiftlisi:
3881   case X86::BI__builtin_ia32_kshiftlidi:
3882   case X86::BI__builtin_ia32_kshiftriqi:
3883   case X86::BI__builtin_ia32_kshiftrihi:
3884   case X86::BI__builtin_ia32_kshiftrisi:
3885   case X86::BI__builtin_ia32_kshiftridi:
3886     i = 1; l = 0; u = 255;
3887     break;
3888   case X86::BI__builtin_ia32_vperm2f128_pd256:
3889   case X86::BI__builtin_ia32_vperm2f128_ps256:
3890   case X86::BI__builtin_ia32_vperm2f128_si256:
3891   case X86::BI__builtin_ia32_permti256:
3892   case X86::BI__builtin_ia32_pblendw128:
3893   case X86::BI__builtin_ia32_pblendw256:
3894   case X86::BI__builtin_ia32_blendps256:
3895   case X86::BI__builtin_ia32_pblendd256:
3896   case X86::BI__builtin_ia32_palignr128:
3897   case X86::BI__builtin_ia32_palignr256:
3898   case X86::BI__builtin_ia32_palignr512:
3899   case X86::BI__builtin_ia32_alignq512:
3900   case X86::BI__builtin_ia32_alignd512:
3901   case X86::BI__builtin_ia32_alignd128:
3902   case X86::BI__builtin_ia32_alignd256:
3903   case X86::BI__builtin_ia32_alignq128:
3904   case X86::BI__builtin_ia32_alignq256:
3905   case X86::BI__builtin_ia32_vcomisd:
3906   case X86::BI__builtin_ia32_vcomiss:
3907   case X86::BI__builtin_ia32_shuf_f32x4:
3908   case X86::BI__builtin_ia32_shuf_f64x2:
3909   case X86::BI__builtin_ia32_shuf_i32x4:
3910   case X86::BI__builtin_ia32_shuf_i64x2:
3911   case X86::BI__builtin_ia32_shufpd512:
3912   case X86::BI__builtin_ia32_shufps:
3913   case X86::BI__builtin_ia32_shufps256:
3914   case X86::BI__builtin_ia32_shufps512:
3915   case X86::BI__builtin_ia32_dbpsadbw128:
3916   case X86::BI__builtin_ia32_dbpsadbw256:
3917   case X86::BI__builtin_ia32_dbpsadbw512:
3918   case X86::BI__builtin_ia32_vpshldd128:
3919   case X86::BI__builtin_ia32_vpshldd256:
3920   case X86::BI__builtin_ia32_vpshldd512:
3921   case X86::BI__builtin_ia32_vpshldq128:
3922   case X86::BI__builtin_ia32_vpshldq256:
3923   case X86::BI__builtin_ia32_vpshldq512:
3924   case X86::BI__builtin_ia32_vpshldw128:
3925   case X86::BI__builtin_ia32_vpshldw256:
3926   case X86::BI__builtin_ia32_vpshldw512:
3927   case X86::BI__builtin_ia32_vpshrdd128:
3928   case X86::BI__builtin_ia32_vpshrdd256:
3929   case X86::BI__builtin_ia32_vpshrdd512:
3930   case X86::BI__builtin_ia32_vpshrdq128:
3931   case X86::BI__builtin_ia32_vpshrdq256:
3932   case X86::BI__builtin_ia32_vpshrdq512:
3933   case X86::BI__builtin_ia32_vpshrdw128:
3934   case X86::BI__builtin_ia32_vpshrdw256:
3935   case X86::BI__builtin_ia32_vpshrdw512:
3936     i = 2; l = 0; u = 255;
3937     break;
3938   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3939   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3940   case X86::BI__builtin_ia32_fixupimmps512_mask:
3941   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3942   case X86::BI__builtin_ia32_fixupimmsd_mask:
3943   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3944   case X86::BI__builtin_ia32_fixupimmss_mask:
3945   case X86::BI__builtin_ia32_fixupimmss_maskz:
3946   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3947   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3948   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3949   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3950   case X86::BI__builtin_ia32_fixupimmps128_mask:
3951   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3952   case X86::BI__builtin_ia32_fixupimmps256_mask:
3953   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3954   case X86::BI__builtin_ia32_pternlogd512_mask:
3955   case X86::BI__builtin_ia32_pternlogd512_maskz:
3956   case X86::BI__builtin_ia32_pternlogq512_mask:
3957   case X86::BI__builtin_ia32_pternlogq512_maskz:
3958   case X86::BI__builtin_ia32_pternlogd128_mask:
3959   case X86::BI__builtin_ia32_pternlogd128_maskz:
3960   case X86::BI__builtin_ia32_pternlogd256_mask:
3961   case X86::BI__builtin_ia32_pternlogd256_maskz:
3962   case X86::BI__builtin_ia32_pternlogq128_mask:
3963   case X86::BI__builtin_ia32_pternlogq128_maskz:
3964   case X86::BI__builtin_ia32_pternlogq256_mask:
3965   case X86::BI__builtin_ia32_pternlogq256_maskz:
3966     i = 3; l = 0; u = 255;
3967     break;
3968   case X86::BI__builtin_ia32_gatherpfdpd:
3969   case X86::BI__builtin_ia32_gatherpfdps:
3970   case X86::BI__builtin_ia32_gatherpfqpd:
3971   case X86::BI__builtin_ia32_gatherpfqps:
3972   case X86::BI__builtin_ia32_scatterpfdpd:
3973   case X86::BI__builtin_ia32_scatterpfdps:
3974   case X86::BI__builtin_ia32_scatterpfqpd:
3975   case X86::BI__builtin_ia32_scatterpfqps:
3976     i = 4; l = 2; u = 3;
3977     break;
3978   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3979   case X86::BI__builtin_ia32_rndscaless_round_mask:
3980     i = 4; l = 0; u = 255;
3981     break;
3982   }
3983 
3984   // Note that we don't force a hard error on the range check here, allowing
3985   // template-generated or macro-generated dead code to potentially have out-of-
3986   // range values. These need to code generate, but don't need to necessarily
3987   // make any sense. We use a warning that defaults to an error.
3988   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3989 }
3990 
3991 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3992 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3993 /// Returns true when the format fits the function and the FormatStringInfo has
3994 /// been populated.
3995 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3996                                FormatStringInfo *FSI) {
3997   FSI->HasVAListArg = Format->getFirstArg() == 0;
3998   FSI->FormatIdx = Format->getFormatIdx() - 1;
3999   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4000 
4001   // The way the format attribute works in GCC, the implicit this argument
4002   // of member functions is counted. However, it doesn't appear in our own
4003   // lists, so decrement format_idx in that case.
4004   if (IsCXXMember) {
4005     if(FSI->FormatIdx == 0)
4006       return false;
4007     --FSI->FormatIdx;
4008     if (FSI->FirstDataArg != 0)
4009       --FSI->FirstDataArg;
4010   }
4011   return true;
4012 }
4013 
4014 /// Checks if a the given expression evaluates to null.
4015 ///
4016 /// Returns true if the value evaluates to null.
4017 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4018   // If the expression has non-null type, it doesn't evaluate to null.
4019   if (auto nullability
4020         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4021     if (*nullability == NullabilityKind::NonNull)
4022       return false;
4023   }
4024 
4025   // As a special case, transparent unions initialized with zero are
4026   // considered null for the purposes of the nonnull attribute.
4027   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4028     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4029       if (const CompoundLiteralExpr *CLE =
4030           dyn_cast<CompoundLiteralExpr>(Expr))
4031         if (const InitListExpr *ILE =
4032             dyn_cast<InitListExpr>(CLE->getInitializer()))
4033           Expr = ILE->getInit(0);
4034   }
4035 
4036   bool Result;
4037   return (!Expr->isValueDependent() &&
4038           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4039           !Result);
4040 }
4041 
4042 static void CheckNonNullArgument(Sema &S,
4043                                  const Expr *ArgExpr,
4044                                  SourceLocation CallSiteLoc) {
4045   if (CheckNonNullExpr(S, ArgExpr))
4046     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4047            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
4048 }
4049 
4050 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4051   FormatStringInfo FSI;
4052   if ((GetFormatStringType(Format) == FST_NSString) &&
4053       getFormatStringInfo(Format, false, &FSI)) {
4054     Idx = FSI.FormatIdx;
4055     return true;
4056   }
4057   return false;
4058 }
4059 
4060 /// Diagnose use of %s directive in an NSString which is being passed
4061 /// as formatting string to formatting method.
4062 static void
4063 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4064                                         const NamedDecl *FDecl,
4065                                         Expr **Args,
4066                                         unsigned NumArgs) {
4067   unsigned Idx = 0;
4068   bool Format = false;
4069   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4070   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4071     Idx = 2;
4072     Format = true;
4073   }
4074   else
4075     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4076       if (S.GetFormatNSStringIdx(I, Idx)) {
4077         Format = true;
4078         break;
4079       }
4080     }
4081   if (!Format || NumArgs <= Idx)
4082     return;
4083   const Expr *FormatExpr = Args[Idx];
4084   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4085     FormatExpr = CSCE->getSubExpr();
4086   const StringLiteral *FormatString;
4087   if (const ObjCStringLiteral *OSL =
4088       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4089     FormatString = OSL->getString();
4090   else
4091     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4092   if (!FormatString)
4093     return;
4094   if (S.FormatStringHasSArg(FormatString)) {
4095     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4096       << "%s" << 1 << 1;
4097     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4098       << FDecl->getDeclName();
4099   }
4100 }
4101 
4102 /// Determine whether the given type has a non-null nullability annotation.
4103 static bool isNonNullType(ASTContext &ctx, QualType type) {
4104   if (auto nullability = type->getNullability(ctx))
4105     return *nullability == NullabilityKind::NonNull;
4106 
4107   return false;
4108 }
4109 
4110 static void CheckNonNullArguments(Sema &S,
4111                                   const NamedDecl *FDecl,
4112                                   const FunctionProtoType *Proto,
4113                                   ArrayRef<const Expr *> Args,
4114                                   SourceLocation CallSiteLoc) {
4115   assert((FDecl || Proto) && "Need a function declaration or prototype");
4116 
4117   // Check the attributes attached to the method/function itself.
4118   llvm::SmallBitVector NonNullArgs;
4119   if (FDecl) {
4120     // Handle the nonnull attribute on the function/method declaration itself.
4121     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4122       if (!NonNull->args_size()) {
4123         // Easy case: all pointer arguments are nonnull.
4124         for (const auto *Arg : Args)
4125           if (S.isValidPointerAttrType(Arg->getType()))
4126             CheckNonNullArgument(S, Arg, CallSiteLoc);
4127         return;
4128       }
4129 
4130       for (const ParamIdx &Idx : NonNull->args()) {
4131         unsigned IdxAST = Idx.getASTIndex();
4132         if (IdxAST >= Args.size())
4133           continue;
4134         if (NonNullArgs.empty())
4135           NonNullArgs.resize(Args.size());
4136         NonNullArgs.set(IdxAST);
4137       }
4138     }
4139   }
4140 
4141   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4142     // Handle the nonnull attribute on the parameters of the
4143     // function/method.
4144     ArrayRef<ParmVarDecl*> parms;
4145     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4146       parms = FD->parameters();
4147     else
4148       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4149 
4150     unsigned ParamIndex = 0;
4151     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4152          I != E; ++I, ++ParamIndex) {
4153       const ParmVarDecl *PVD = *I;
4154       if (PVD->hasAttr<NonNullAttr>() ||
4155           isNonNullType(S.Context, PVD->getType())) {
4156         if (NonNullArgs.empty())
4157           NonNullArgs.resize(Args.size());
4158 
4159         NonNullArgs.set(ParamIndex);
4160       }
4161     }
4162   } else {
4163     // If we have a non-function, non-method declaration but no
4164     // function prototype, try to dig out the function prototype.
4165     if (!Proto) {
4166       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4167         QualType type = VD->getType().getNonReferenceType();
4168         if (auto pointerType = type->getAs<PointerType>())
4169           type = pointerType->getPointeeType();
4170         else if (auto blockType = type->getAs<BlockPointerType>())
4171           type = blockType->getPointeeType();
4172         // FIXME: data member pointers?
4173 
4174         // Dig out the function prototype, if there is one.
4175         Proto = type->getAs<FunctionProtoType>();
4176       }
4177     }
4178 
4179     // Fill in non-null argument information from the nullability
4180     // information on the parameter types (if we have them).
4181     if (Proto) {
4182       unsigned Index = 0;
4183       for (auto paramType : Proto->getParamTypes()) {
4184         if (isNonNullType(S.Context, paramType)) {
4185           if (NonNullArgs.empty())
4186             NonNullArgs.resize(Args.size());
4187 
4188           NonNullArgs.set(Index);
4189         }
4190 
4191         ++Index;
4192       }
4193     }
4194   }
4195 
4196   // Check for non-null arguments.
4197   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4198        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4199     if (NonNullArgs[ArgIndex])
4200       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4201   }
4202 }
4203 
4204 /// Handles the checks for format strings, non-POD arguments to vararg
4205 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4206 /// attributes.
4207 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4208                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4209                      bool IsMemberFunction, SourceLocation Loc,
4210                      SourceRange Range, VariadicCallType CallType) {
4211   // FIXME: We should check as much as we can in the template definition.
4212   if (CurContext->isDependentContext())
4213     return;
4214 
4215   // Printf and scanf checking.
4216   llvm::SmallBitVector CheckedVarArgs;
4217   if (FDecl) {
4218     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4219       // Only create vector if there are format attributes.
4220       CheckedVarArgs.resize(Args.size());
4221 
4222       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4223                            CheckedVarArgs);
4224     }
4225   }
4226 
4227   // Refuse POD arguments that weren't caught by the format string
4228   // checks above.
4229   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4230   if (CallType != VariadicDoesNotApply &&
4231       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4232     unsigned NumParams = Proto ? Proto->getNumParams()
4233                        : FDecl && isa<FunctionDecl>(FDecl)
4234                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4235                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4236                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4237                        : 0;
4238 
4239     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4240       // Args[ArgIdx] can be null in malformed code.
4241       if (const Expr *Arg = Args[ArgIdx]) {
4242         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4243           checkVariadicArgument(Arg, CallType);
4244       }
4245     }
4246   }
4247 
4248   if (FDecl || Proto) {
4249     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4250 
4251     // Type safety checking.
4252     if (FDecl) {
4253       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4254         CheckArgumentWithTypeTag(I, Args, Loc);
4255     }
4256   }
4257 
4258   if (FD)
4259     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4260 }
4261 
4262 /// CheckConstructorCall - Check a constructor call for correctness and safety
4263 /// properties not enforced by the C type system.
4264 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4265                                 ArrayRef<const Expr *> Args,
4266                                 const FunctionProtoType *Proto,
4267                                 SourceLocation Loc) {
4268   VariadicCallType CallType =
4269     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4270   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4271             Loc, SourceRange(), CallType);
4272 }
4273 
4274 /// CheckFunctionCall - Check a direct function call for various correctness
4275 /// and safety properties not strictly enforced by the C type system.
4276 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4277                              const FunctionProtoType *Proto) {
4278   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4279                               isa<CXXMethodDecl>(FDecl);
4280   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4281                           IsMemberOperatorCall;
4282   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4283                                                   TheCall->getCallee());
4284   Expr** Args = TheCall->getArgs();
4285   unsigned NumArgs = TheCall->getNumArgs();
4286 
4287   Expr *ImplicitThis = nullptr;
4288   if (IsMemberOperatorCall) {
4289     // If this is a call to a member operator, hide the first argument
4290     // from checkCall.
4291     // FIXME: Our choice of AST representation here is less than ideal.
4292     ImplicitThis = Args[0];
4293     ++Args;
4294     --NumArgs;
4295   } else if (IsMemberFunction)
4296     ImplicitThis =
4297         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4298 
4299   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4300             IsMemberFunction, TheCall->getRParenLoc(),
4301             TheCall->getCallee()->getSourceRange(), CallType);
4302 
4303   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4304   // None of the checks below are needed for functions that don't have
4305   // simple names (e.g., C++ conversion functions).
4306   if (!FnInfo)
4307     return false;
4308 
4309   CheckAbsoluteValueFunction(TheCall, FDecl);
4310   CheckMaxUnsignedZero(TheCall, FDecl);
4311 
4312   if (getLangOpts().ObjC)
4313     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4314 
4315   unsigned CMId = FDecl->getMemoryFunctionKind();
4316   if (CMId == 0)
4317     return false;
4318 
4319   // Handle memory setting and copying functions.
4320   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4321     CheckStrlcpycatArguments(TheCall, FnInfo);
4322   else if (CMId == Builtin::BIstrncat)
4323     CheckStrncatArguments(TheCall, FnInfo);
4324   else
4325     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4326 
4327   return false;
4328 }
4329 
4330 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4331                                ArrayRef<const Expr *> Args) {
4332   VariadicCallType CallType =
4333       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4334 
4335   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4336             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4337             CallType);
4338 
4339   return false;
4340 }
4341 
4342 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4343                             const FunctionProtoType *Proto) {
4344   QualType Ty;
4345   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4346     Ty = V->getType().getNonReferenceType();
4347   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4348     Ty = F->getType().getNonReferenceType();
4349   else
4350     return false;
4351 
4352   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4353       !Ty->isFunctionProtoType())
4354     return false;
4355 
4356   VariadicCallType CallType;
4357   if (!Proto || !Proto->isVariadic()) {
4358     CallType = VariadicDoesNotApply;
4359   } else if (Ty->isBlockPointerType()) {
4360     CallType = VariadicBlock;
4361   } else { // Ty->isFunctionPointerType()
4362     CallType = VariadicFunction;
4363   }
4364 
4365   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4366             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4367             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4368             TheCall->getCallee()->getSourceRange(), CallType);
4369 
4370   return false;
4371 }
4372 
4373 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4374 /// such as function pointers returned from functions.
4375 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4376   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4377                                                   TheCall->getCallee());
4378   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4379             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4380             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4381             TheCall->getCallee()->getSourceRange(), CallType);
4382 
4383   return false;
4384 }
4385 
4386 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4387   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4388     return false;
4389 
4390   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4391   switch (Op) {
4392   case AtomicExpr::AO__c11_atomic_init:
4393   case AtomicExpr::AO__opencl_atomic_init:
4394     llvm_unreachable("There is no ordering argument for an init");
4395 
4396   case AtomicExpr::AO__c11_atomic_load:
4397   case AtomicExpr::AO__opencl_atomic_load:
4398   case AtomicExpr::AO__atomic_load_n:
4399   case AtomicExpr::AO__atomic_load:
4400     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4401            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4402 
4403   case AtomicExpr::AO__c11_atomic_store:
4404   case AtomicExpr::AO__opencl_atomic_store:
4405   case AtomicExpr::AO__atomic_store:
4406   case AtomicExpr::AO__atomic_store_n:
4407     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4408            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4409            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4410 
4411   default:
4412     return true;
4413   }
4414 }
4415 
4416 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4417                                          AtomicExpr::AtomicOp Op) {
4418   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4419   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4420 
4421   // All the non-OpenCL operations take one of the following forms.
4422   // The OpenCL operations take the __c11 forms with one extra argument for
4423   // synchronization scope.
4424   enum {
4425     // C    __c11_atomic_init(A *, C)
4426     Init,
4427 
4428     // C    __c11_atomic_load(A *, int)
4429     Load,
4430 
4431     // void __atomic_load(A *, CP, int)
4432     LoadCopy,
4433 
4434     // void __atomic_store(A *, CP, int)
4435     Copy,
4436 
4437     // C    __c11_atomic_add(A *, M, int)
4438     Arithmetic,
4439 
4440     // C    __atomic_exchange_n(A *, CP, int)
4441     Xchg,
4442 
4443     // void __atomic_exchange(A *, C *, CP, int)
4444     GNUXchg,
4445 
4446     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4447     C11CmpXchg,
4448 
4449     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4450     GNUCmpXchg
4451   } Form = Init;
4452 
4453   const unsigned NumForm = GNUCmpXchg + 1;
4454   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4455   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4456   // where:
4457   //   C is an appropriate type,
4458   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4459   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4460   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4461   //   the int parameters are for orderings.
4462 
4463   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4464       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4465       "need to update code for modified forms");
4466   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4467                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4468                         AtomicExpr::AO__atomic_load,
4469                 "need to update code for modified C11 atomics");
4470   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4471                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4472   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4473                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4474                IsOpenCL;
4475   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4476              Op == AtomicExpr::AO__atomic_store_n ||
4477              Op == AtomicExpr::AO__atomic_exchange_n ||
4478              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4479   bool IsAddSub = false;
4480   bool IsMinMax = false;
4481 
4482   switch (Op) {
4483   case AtomicExpr::AO__c11_atomic_init:
4484   case AtomicExpr::AO__opencl_atomic_init:
4485     Form = Init;
4486     break;
4487 
4488   case AtomicExpr::AO__c11_atomic_load:
4489   case AtomicExpr::AO__opencl_atomic_load:
4490   case AtomicExpr::AO__atomic_load_n:
4491     Form = Load;
4492     break;
4493 
4494   case AtomicExpr::AO__atomic_load:
4495     Form = LoadCopy;
4496     break;
4497 
4498   case AtomicExpr::AO__c11_atomic_store:
4499   case AtomicExpr::AO__opencl_atomic_store:
4500   case AtomicExpr::AO__atomic_store:
4501   case AtomicExpr::AO__atomic_store_n:
4502     Form = Copy;
4503     break;
4504 
4505   case AtomicExpr::AO__c11_atomic_fetch_add:
4506   case AtomicExpr::AO__c11_atomic_fetch_sub:
4507   case AtomicExpr::AO__opencl_atomic_fetch_add:
4508   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4509   case AtomicExpr::AO__opencl_atomic_fetch_min:
4510   case AtomicExpr::AO__opencl_atomic_fetch_max:
4511   case AtomicExpr::AO__atomic_fetch_add:
4512   case AtomicExpr::AO__atomic_fetch_sub:
4513   case AtomicExpr::AO__atomic_add_fetch:
4514   case AtomicExpr::AO__atomic_sub_fetch:
4515     IsAddSub = true;
4516     LLVM_FALLTHROUGH;
4517   case AtomicExpr::AO__c11_atomic_fetch_and:
4518   case AtomicExpr::AO__c11_atomic_fetch_or:
4519   case AtomicExpr::AO__c11_atomic_fetch_xor:
4520   case AtomicExpr::AO__opencl_atomic_fetch_and:
4521   case AtomicExpr::AO__opencl_atomic_fetch_or:
4522   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4523   case AtomicExpr::AO__atomic_fetch_and:
4524   case AtomicExpr::AO__atomic_fetch_or:
4525   case AtomicExpr::AO__atomic_fetch_xor:
4526   case AtomicExpr::AO__atomic_fetch_nand:
4527   case AtomicExpr::AO__atomic_and_fetch:
4528   case AtomicExpr::AO__atomic_or_fetch:
4529   case AtomicExpr::AO__atomic_xor_fetch:
4530   case AtomicExpr::AO__atomic_nand_fetch:
4531     Form = Arithmetic;
4532     break;
4533 
4534   case AtomicExpr::AO__atomic_fetch_min:
4535   case AtomicExpr::AO__atomic_fetch_max:
4536     IsMinMax = true;
4537     Form = Arithmetic;
4538     break;
4539 
4540   case AtomicExpr::AO__c11_atomic_exchange:
4541   case AtomicExpr::AO__opencl_atomic_exchange:
4542   case AtomicExpr::AO__atomic_exchange_n:
4543     Form = Xchg;
4544     break;
4545 
4546   case AtomicExpr::AO__atomic_exchange:
4547     Form = GNUXchg;
4548     break;
4549 
4550   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4551   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4552   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4553   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4554     Form = C11CmpXchg;
4555     break;
4556 
4557   case AtomicExpr::AO__atomic_compare_exchange:
4558   case AtomicExpr::AO__atomic_compare_exchange_n:
4559     Form = GNUCmpXchg;
4560     break;
4561   }
4562 
4563   unsigned AdjustedNumArgs = NumArgs[Form];
4564   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4565     ++AdjustedNumArgs;
4566   // Check we have the right number of arguments.
4567   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4568     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4569         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4570         << TheCall->getCallee()->getSourceRange();
4571     return ExprError();
4572   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4573     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4574          diag::err_typecheck_call_too_many_args)
4575         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4576         << TheCall->getCallee()->getSourceRange();
4577     return ExprError();
4578   }
4579 
4580   // Inspect the first argument of the atomic operation.
4581   Expr *Ptr = TheCall->getArg(0);
4582   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4583   if (ConvertedPtr.isInvalid())
4584     return ExprError();
4585 
4586   Ptr = ConvertedPtr.get();
4587   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4588   if (!pointerType) {
4589     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4590         << Ptr->getType() << Ptr->getSourceRange();
4591     return ExprError();
4592   }
4593 
4594   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4595   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4596   QualType ValType = AtomTy; // 'C'
4597   if (IsC11) {
4598     if (!AtomTy->isAtomicType()) {
4599       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4600           << Ptr->getType() << Ptr->getSourceRange();
4601       return ExprError();
4602     }
4603     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4604         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4605       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4606           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4607           << Ptr->getSourceRange();
4608       return ExprError();
4609     }
4610     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4611   } else if (Form != Load && Form != LoadCopy) {
4612     if (ValType.isConstQualified()) {
4613       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4614           << Ptr->getType() << Ptr->getSourceRange();
4615       return ExprError();
4616     }
4617   }
4618 
4619   // For an arithmetic operation, the implied arithmetic must be well-formed.
4620   if (Form == Arithmetic) {
4621     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4622     if (IsAddSub && !ValType->isIntegerType()
4623         && !ValType->isPointerType()) {
4624       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4625           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4626       return ExprError();
4627     }
4628     if (IsMinMax) {
4629       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4630       if (!BT || (BT->getKind() != BuiltinType::Int &&
4631                   BT->getKind() != BuiltinType::UInt)) {
4632         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4633         return ExprError();
4634       }
4635     }
4636     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4637       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4638           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4639       return ExprError();
4640     }
4641     if (IsC11 && ValType->isPointerType() &&
4642         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4643                             diag::err_incomplete_type)) {
4644       return ExprError();
4645     }
4646   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4647     // For __atomic_*_n operations, the value type must be a scalar integral or
4648     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4649     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4650         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4651     return ExprError();
4652   }
4653 
4654   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4655       !AtomTy->isScalarType()) {
4656     // For GNU atomics, require a trivially-copyable type. This is not part of
4657     // the GNU atomics specification, but we enforce it for sanity.
4658     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4659         << Ptr->getType() << Ptr->getSourceRange();
4660     return ExprError();
4661   }
4662 
4663   switch (ValType.getObjCLifetime()) {
4664   case Qualifiers::OCL_None:
4665   case Qualifiers::OCL_ExplicitNone:
4666     // okay
4667     break;
4668 
4669   case Qualifiers::OCL_Weak:
4670   case Qualifiers::OCL_Strong:
4671   case Qualifiers::OCL_Autoreleasing:
4672     // FIXME: Can this happen? By this point, ValType should be known
4673     // to be trivially copyable.
4674     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4675         << ValType << Ptr->getSourceRange();
4676     return ExprError();
4677   }
4678 
4679   // All atomic operations have an overload which takes a pointer to a volatile
4680   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4681   // into the result or the other operands. Similarly atomic_load takes a
4682   // pointer to a const 'A'.
4683   ValType.removeLocalVolatile();
4684   ValType.removeLocalConst();
4685   QualType ResultType = ValType;
4686   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4687       Form == Init)
4688     ResultType = Context.VoidTy;
4689   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4690     ResultType = Context.BoolTy;
4691 
4692   // The type of a parameter passed 'by value'. In the GNU atomics, such
4693   // arguments are actually passed as pointers.
4694   QualType ByValType = ValType; // 'CP'
4695   bool IsPassedByAddress = false;
4696   if (!IsC11 && !IsN) {
4697     ByValType = Ptr->getType();
4698     IsPassedByAddress = true;
4699   }
4700 
4701   // The first argument's non-CV pointer type is used to deduce the type of
4702   // subsequent arguments, except for:
4703   //  - weak flag (always converted to bool)
4704   //  - memory order (always converted to int)
4705   //  - scope  (always converted to int)
4706   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4707     QualType Ty;
4708     if (i < NumVals[Form] + 1) {
4709       switch (i) {
4710       case 0:
4711         // The first argument is always a pointer. It has a fixed type.
4712         // It is always dereferenced, a nullptr is undefined.
4713         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4714         // Nothing else to do: we already know all we want about this pointer.
4715         continue;
4716       case 1:
4717         // The second argument is the non-atomic operand. For arithmetic, this
4718         // is always passed by value, and for a compare_exchange it is always
4719         // passed by address. For the rest, GNU uses by-address and C11 uses
4720         // by-value.
4721         assert(Form != Load);
4722         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4723           Ty = ValType;
4724         else if (Form == Copy || Form == Xchg) {
4725           if (IsPassedByAddress)
4726             // The value pointer is always dereferenced, a nullptr is undefined.
4727             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4728           Ty = ByValType;
4729         } else if (Form == Arithmetic)
4730           Ty = Context.getPointerDiffType();
4731         else {
4732           Expr *ValArg = TheCall->getArg(i);
4733           // The value pointer is always dereferenced, a nullptr is undefined.
4734           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4735           LangAS AS = LangAS::Default;
4736           // Keep address space of non-atomic pointer type.
4737           if (const PointerType *PtrTy =
4738                   ValArg->getType()->getAs<PointerType>()) {
4739             AS = PtrTy->getPointeeType().getAddressSpace();
4740           }
4741           Ty = Context.getPointerType(
4742               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4743         }
4744         break;
4745       case 2:
4746         // The third argument to compare_exchange / GNU exchange is the desired
4747         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4748         if (IsPassedByAddress)
4749           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4750         Ty = ByValType;
4751         break;
4752       case 3:
4753         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4754         Ty = Context.BoolTy;
4755         break;
4756       }
4757     } else {
4758       // The order(s) and scope are always converted to int.
4759       Ty = Context.IntTy;
4760     }
4761 
4762     InitializedEntity Entity =
4763         InitializedEntity::InitializeParameter(Context, Ty, false);
4764     ExprResult Arg = TheCall->getArg(i);
4765     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4766     if (Arg.isInvalid())
4767       return true;
4768     TheCall->setArg(i, Arg.get());
4769   }
4770 
4771   // Permute the arguments into a 'consistent' order.
4772   SmallVector<Expr*, 5> SubExprs;
4773   SubExprs.push_back(Ptr);
4774   switch (Form) {
4775   case Init:
4776     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4777     SubExprs.push_back(TheCall->getArg(1)); // Val1
4778     break;
4779   case Load:
4780     SubExprs.push_back(TheCall->getArg(1)); // Order
4781     break;
4782   case LoadCopy:
4783   case Copy:
4784   case Arithmetic:
4785   case Xchg:
4786     SubExprs.push_back(TheCall->getArg(2)); // Order
4787     SubExprs.push_back(TheCall->getArg(1)); // Val1
4788     break;
4789   case GNUXchg:
4790     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4791     SubExprs.push_back(TheCall->getArg(3)); // Order
4792     SubExprs.push_back(TheCall->getArg(1)); // Val1
4793     SubExprs.push_back(TheCall->getArg(2)); // Val2
4794     break;
4795   case C11CmpXchg:
4796     SubExprs.push_back(TheCall->getArg(3)); // Order
4797     SubExprs.push_back(TheCall->getArg(1)); // Val1
4798     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4799     SubExprs.push_back(TheCall->getArg(2)); // Val2
4800     break;
4801   case GNUCmpXchg:
4802     SubExprs.push_back(TheCall->getArg(4)); // Order
4803     SubExprs.push_back(TheCall->getArg(1)); // Val1
4804     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4805     SubExprs.push_back(TheCall->getArg(2)); // Val2
4806     SubExprs.push_back(TheCall->getArg(3)); // Weak
4807     break;
4808   }
4809 
4810   if (SubExprs.size() >= 2 && Form != Init) {
4811     llvm::APSInt Result(32);
4812     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4813         !isValidOrderingForOp(Result.getSExtValue(), Op))
4814       Diag(SubExprs[1]->getBeginLoc(),
4815            diag::warn_atomic_op_has_invalid_memory_order)
4816           << SubExprs[1]->getSourceRange();
4817   }
4818 
4819   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4820     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4821     llvm::APSInt Result(32);
4822     if (Scope->isIntegerConstantExpr(Result, Context) &&
4823         !ScopeModel->isValid(Result.getZExtValue())) {
4824       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4825           << Scope->getSourceRange();
4826     }
4827     SubExprs.push_back(Scope);
4828   }
4829 
4830   AtomicExpr *AE =
4831       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4832                                ResultType, Op, TheCall->getRParenLoc());
4833 
4834   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4835        Op == AtomicExpr::AO__c11_atomic_store ||
4836        Op == AtomicExpr::AO__opencl_atomic_load ||
4837        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4838       Context.AtomicUsesUnsupportedLibcall(AE))
4839     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4840         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4841              Op == AtomicExpr::AO__opencl_atomic_load)
4842                 ? 0
4843                 : 1);
4844 
4845   return AE;
4846 }
4847 
4848 /// checkBuiltinArgument - Given a call to a builtin function, perform
4849 /// normal type-checking on the given argument, updating the call in
4850 /// place.  This is useful when a builtin function requires custom
4851 /// type-checking for some of its arguments but not necessarily all of
4852 /// them.
4853 ///
4854 /// Returns true on error.
4855 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4856   FunctionDecl *Fn = E->getDirectCallee();
4857   assert(Fn && "builtin call without direct callee!");
4858 
4859   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4860   InitializedEntity Entity =
4861     InitializedEntity::InitializeParameter(S.Context, Param);
4862 
4863   ExprResult Arg = E->getArg(0);
4864   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4865   if (Arg.isInvalid())
4866     return true;
4867 
4868   E->setArg(ArgIndex, Arg.get());
4869   return false;
4870 }
4871 
4872 /// We have a call to a function like __sync_fetch_and_add, which is an
4873 /// overloaded function based on the pointer type of its first argument.
4874 /// The main ActOnCallExpr routines have already promoted the types of
4875 /// arguments because all of these calls are prototyped as void(...).
4876 ///
4877 /// This function goes through and does final semantic checking for these
4878 /// builtins, as well as generating any warnings.
4879 ExprResult
4880 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4881   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4882   Expr *Callee = TheCall->getCallee();
4883   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4884   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4885 
4886   // Ensure that we have at least one argument to do type inference from.
4887   if (TheCall->getNumArgs() < 1) {
4888     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4889         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4890     return ExprError();
4891   }
4892 
4893   // Inspect the first argument of the atomic builtin.  This should always be
4894   // a pointer type, whose element is an integral scalar or pointer type.
4895   // Because it is a pointer type, we don't have to worry about any implicit
4896   // casts here.
4897   // FIXME: We don't allow floating point scalars as input.
4898   Expr *FirstArg = TheCall->getArg(0);
4899   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4900   if (FirstArgResult.isInvalid())
4901     return ExprError();
4902   FirstArg = FirstArgResult.get();
4903   TheCall->setArg(0, FirstArg);
4904 
4905   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4906   if (!pointerType) {
4907     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4908         << FirstArg->getType() << FirstArg->getSourceRange();
4909     return ExprError();
4910   }
4911 
4912   QualType ValType = pointerType->getPointeeType();
4913   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4914       !ValType->isBlockPointerType()) {
4915     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4916         << FirstArg->getType() << FirstArg->getSourceRange();
4917     return ExprError();
4918   }
4919 
4920   if (ValType.isConstQualified()) {
4921     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4922         << FirstArg->getType() << FirstArg->getSourceRange();
4923     return ExprError();
4924   }
4925 
4926   switch (ValType.getObjCLifetime()) {
4927   case Qualifiers::OCL_None:
4928   case Qualifiers::OCL_ExplicitNone:
4929     // okay
4930     break;
4931 
4932   case Qualifiers::OCL_Weak:
4933   case Qualifiers::OCL_Strong:
4934   case Qualifiers::OCL_Autoreleasing:
4935     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4936         << ValType << FirstArg->getSourceRange();
4937     return ExprError();
4938   }
4939 
4940   // Strip any qualifiers off ValType.
4941   ValType = ValType.getUnqualifiedType();
4942 
4943   // The majority of builtins return a value, but a few have special return
4944   // types, so allow them to override appropriately below.
4945   QualType ResultType = ValType;
4946 
4947   // We need to figure out which concrete builtin this maps onto.  For example,
4948   // __sync_fetch_and_add with a 2 byte object turns into
4949   // __sync_fetch_and_add_2.
4950 #define BUILTIN_ROW(x) \
4951   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4952     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4953 
4954   static const unsigned BuiltinIndices[][5] = {
4955     BUILTIN_ROW(__sync_fetch_and_add),
4956     BUILTIN_ROW(__sync_fetch_and_sub),
4957     BUILTIN_ROW(__sync_fetch_and_or),
4958     BUILTIN_ROW(__sync_fetch_and_and),
4959     BUILTIN_ROW(__sync_fetch_and_xor),
4960     BUILTIN_ROW(__sync_fetch_and_nand),
4961 
4962     BUILTIN_ROW(__sync_add_and_fetch),
4963     BUILTIN_ROW(__sync_sub_and_fetch),
4964     BUILTIN_ROW(__sync_and_and_fetch),
4965     BUILTIN_ROW(__sync_or_and_fetch),
4966     BUILTIN_ROW(__sync_xor_and_fetch),
4967     BUILTIN_ROW(__sync_nand_and_fetch),
4968 
4969     BUILTIN_ROW(__sync_val_compare_and_swap),
4970     BUILTIN_ROW(__sync_bool_compare_and_swap),
4971     BUILTIN_ROW(__sync_lock_test_and_set),
4972     BUILTIN_ROW(__sync_lock_release),
4973     BUILTIN_ROW(__sync_swap)
4974   };
4975 #undef BUILTIN_ROW
4976 
4977   // Determine the index of the size.
4978   unsigned SizeIndex;
4979   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4980   case 1: SizeIndex = 0; break;
4981   case 2: SizeIndex = 1; break;
4982   case 4: SizeIndex = 2; break;
4983   case 8: SizeIndex = 3; break;
4984   case 16: SizeIndex = 4; break;
4985   default:
4986     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4987         << FirstArg->getType() << FirstArg->getSourceRange();
4988     return ExprError();
4989   }
4990 
4991   // Each of these builtins has one pointer argument, followed by some number of
4992   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4993   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4994   // as the number of fixed args.
4995   unsigned BuiltinID = FDecl->getBuiltinID();
4996   unsigned BuiltinIndex, NumFixed = 1;
4997   bool WarnAboutSemanticsChange = false;
4998   switch (BuiltinID) {
4999   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5000   case Builtin::BI__sync_fetch_and_add:
5001   case Builtin::BI__sync_fetch_and_add_1:
5002   case Builtin::BI__sync_fetch_and_add_2:
5003   case Builtin::BI__sync_fetch_and_add_4:
5004   case Builtin::BI__sync_fetch_and_add_8:
5005   case Builtin::BI__sync_fetch_and_add_16:
5006     BuiltinIndex = 0;
5007     break;
5008 
5009   case Builtin::BI__sync_fetch_and_sub:
5010   case Builtin::BI__sync_fetch_and_sub_1:
5011   case Builtin::BI__sync_fetch_and_sub_2:
5012   case Builtin::BI__sync_fetch_and_sub_4:
5013   case Builtin::BI__sync_fetch_and_sub_8:
5014   case Builtin::BI__sync_fetch_and_sub_16:
5015     BuiltinIndex = 1;
5016     break;
5017 
5018   case Builtin::BI__sync_fetch_and_or:
5019   case Builtin::BI__sync_fetch_and_or_1:
5020   case Builtin::BI__sync_fetch_and_or_2:
5021   case Builtin::BI__sync_fetch_and_or_4:
5022   case Builtin::BI__sync_fetch_and_or_8:
5023   case Builtin::BI__sync_fetch_and_or_16:
5024     BuiltinIndex = 2;
5025     break;
5026 
5027   case Builtin::BI__sync_fetch_and_and:
5028   case Builtin::BI__sync_fetch_and_and_1:
5029   case Builtin::BI__sync_fetch_and_and_2:
5030   case Builtin::BI__sync_fetch_and_and_4:
5031   case Builtin::BI__sync_fetch_and_and_8:
5032   case Builtin::BI__sync_fetch_and_and_16:
5033     BuiltinIndex = 3;
5034     break;
5035 
5036   case Builtin::BI__sync_fetch_and_xor:
5037   case Builtin::BI__sync_fetch_and_xor_1:
5038   case Builtin::BI__sync_fetch_and_xor_2:
5039   case Builtin::BI__sync_fetch_and_xor_4:
5040   case Builtin::BI__sync_fetch_and_xor_8:
5041   case Builtin::BI__sync_fetch_and_xor_16:
5042     BuiltinIndex = 4;
5043     break;
5044 
5045   case Builtin::BI__sync_fetch_and_nand:
5046   case Builtin::BI__sync_fetch_and_nand_1:
5047   case Builtin::BI__sync_fetch_and_nand_2:
5048   case Builtin::BI__sync_fetch_and_nand_4:
5049   case Builtin::BI__sync_fetch_and_nand_8:
5050   case Builtin::BI__sync_fetch_and_nand_16:
5051     BuiltinIndex = 5;
5052     WarnAboutSemanticsChange = true;
5053     break;
5054 
5055   case Builtin::BI__sync_add_and_fetch:
5056   case Builtin::BI__sync_add_and_fetch_1:
5057   case Builtin::BI__sync_add_and_fetch_2:
5058   case Builtin::BI__sync_add_and_fetch_4:
5059   case Builtin::BI__sync_add_and_fetch_8:
5060   case Builtin::BI__sync_add_and_fetch_16:
5061     BuiltinIndex = 6;
5062     break;
5063 
5064   case Builtin::BI__sync_sub_and_fetch:
5065   case Builtin::BI__sync_sub_and_fetch_1:
5066   case Builtin::BI__sync_sub_and_fetch_2:
5067   case Builtin::BI__sync_sub_and_fetch_4:
5068   case Builtin::BI__sync_sub_and_fetch_8:
5069   case Builtin::BI__sync_sub_and_fetch_16:
5070     BuiltinIndex = 7;
5071     break;
5072 
5073   case Builtin::BI__sync_and_and_fetch:
5074   case Builtin::BI__sync_and_and_fetch_1:
5075   case Builtin::BI__sync_and_and_fetch_2:
5076   case Builtin::BI__sync_and_and_fetch_4:
5077   case Builtin::BI__sync_and_and_fetch_8:
5078   case Builtin::BI__sync_and_and_fetch_16:
5079     BuiltinIndex = 8;
5080     break;
5081 
5082   case Builtin::BI__sync_or_and_fetch:
5083   case Builtin::BI__sync_or_and_fetch_1:
5084   case Builtin::BI__sync_or_and_fetch_2:
5085   case Builtin::BI__sync_or_and_fetch_4:
5086   case Builtin::BI__sync_or_and_fetch_8:
5087   case Builtin::BI__sync_or_and_fetch_16:
5088     BuiltinIndex = 9;
5089     break;
5090 
5091   case Builtin::BI__sync_xor_and_fetch:
5092   case Builtin::BI__sync_xor_and_fetch_1:
5093   case Builtin::BI__sync_xor_and_fetch_2:
5094   case Builtin::BI__sync_xor_and_fetch_4:
5095   case Builtin::BI__sync_xor_and_fetch_8:
5096   case Builtin::BI__sync_xor_and_fetch_16:
5097     BuiltinIndex = 10;
5098     break;
5099 
5100   case Builtin::BI__sync_nand_and_fetch:
5101   case Builtin::BI__sync_nand_and_fetch_1:
5102   case Builtin::BI__sync_nand_and_fetch_2:
5103   case Builtin::BI__sync_nand_and_fetch_4:
5104   case Builtin::BI__sync_nand_and_fetch_8:
5105   case Builtin::BI__sync_nand_and_fetch_16:
5106     BuiltinIndex = 11;
5107     WarnAboutSemanticsChange = true;
5108     break;
5109 
5110   case Builtin::BI__sync_val_compare_and_swap:
5111   case Builtin::BI__sync_val_compare_and_swap_1:
5112   case Builtin::BI__sync_val_compare_and_swap_2:
5113   case Builtin::BI__sync_val_compare_and_swap_4:
5114   case Builtin::BI__sync_val_compare_and_swap_8:
5115   case Builtin::BI__sync_val_compare_and_swap_16:
5116     BuiltinIndex = 12;
5117     NumFixed = 2;
5118     break;
5119 
5120   case Builtin::BI__sync_bool_compare_and_swap:
5121   case Builtin::BI__sync_bool_compare_and_swap_1:
5122   case Builtin::BI__sync_bool_compare_and_swap_2:
5123   case Builtin::BI__sync_bool_compare_and_swap_4:
5124   case Builtin::BI__sync_bool_compare_and_swap_8:
5125   case Builtin::BI__sync_bool_compare_and_swap_16:
5126     BuiltinIndex = 13;
5127     NumFixed = 2;
5128     ResultType = Context.BoolTy;
5129     break;
5130 
5131   case Builtin::BI__sync_lock_test_and_set:
5132   case Builtin::BI__sync_lock_test_and_set_1:
5133   case Builtin::BI__sync_lock_test_and_set_2:
5134   case Builtin::BI__sync_lock_test_and_set_4:
5135   case Builtin::BI__sync_lock_test_and_set_8:
5136   case Builtin::BI__sync_lock_test_and_set_16:
5137     BuiltinIndex = 14;
5138     break;
5139 
5140   case Builtin::BI__sync_lock_release:
5141   case Builtin::BI__sync_lock_release_1:
5142   case Builtin::BI__sync_lock_release_2:
5143   case Builtin::BI__sync_lock_release_4:
5144   case Builtin::BI__sync_lock_release_8:
5145   case Builtin::BI__sync_lock_release_16:
5146     BuiltinIndex = 15;
5147     NumFixed = 0;
5148     ResultType = Context.VoidTy;
5149     break;
5150 
5151   case Builtin::BI__sync_swap:
5152   case Builtin::BI__sync_swap_1:
5153   case Builtin::BI__sync_swap_2:
5154   case Builtin::BI__sync_swap_4:
5155   case Builtin::BI__sync_swap_8:
5156   case Builtin::BI__sync_swap_16:
5157     BuiltinIndex = 16;
5158     break;
5159   }
5160 
5161   // Now that we know how many fixed arguments we expect, first check that we
5162   // have at least that many.
5163   if (TheCall->getNumArgs() < 1+NumFixed) {
5164     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5165         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5166         << Callee->getSourceRange();
5167     return ExprError();
5168   }
5169 
5170   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5171       << Callee->getSourceRange();
5172 
5173   if (WarnAboutSemanticsChange) {
5174     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5175         << Callee->getSourceRange();
5176   }
5177 
5178   // Get the decl for the concrete builtin from this, we can tell what the
5179   // concrete integer type we should convert to is.
5180   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5181   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5182   FunctionDecl *NewBuiltinDecl;
5183   if (NewBuiltinID == BuiltinID)
5184     NewBuiltinDecl = FDecl;
5185   else {
5186     // Perform builtin lookup to avoid redeclaring it.
5187     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5188     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5189     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5190     assert(Res.getFoundDecl());
5191     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5192     if (!NewBuiltinDecl)
5193       return ExprError();
5194   }
5195 
5196   // The first argument --- the pointer --- has a fixed type; we
5197   // deduce the types of the rest of the arguments accordingly.  Walk
5198   // the remaining arguments, converting them to the deduced value type.
5199   for (unsigned i = 0; i != NumFixed; ++i) {
5200     ExprResult Arg = TheCall->getArg(i+1);
5201 
5202     // GCC does an implicit conversion to the pointer or integer ValType.  This
5203     // can fail in some cases (1i -> int**), check for this error case now.
5204     // Initialize the argument.
5205     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5206                                                    ValType, /*consume*/ false);
5207     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5208     if (Arg.isInvalid())
5209       return ExprError();
5210 
5211     // Okay, we have something that *can* be converted to the right type.  Check
5212     // to see if there is a potentially weird extension going on here.  This can
5213     // happen when you do an atomic operation on something like an char* and
5214     // pass in 42.  The 42 gets converted to char.  This is even more strange
5215     // for things like 45.123 -> char, etc.
5216     // FIXME: Do this check.
5217     TheCall->setArg(i+1, Arg.get());
5218   }
5219 
5220   // Create a new DeclRefExpr to refer to the new decl.
5221   DeclRefExpr* NewDRE = DeclRefExpr::Create(
5222       Context,
5223       DRE->getQualifierLoc(),
5224       SourceLocation(),
5225       NewBuiltinDecl,
5226       /*enclosing*/ false,
5227       DRE->getLocation(),
5228       Context.BuiltinFnTy,
5229       DRE->getValueKind());
5230 
5231   // Set the callee in the CallExpr.
5232   // FIXME: This loses syntactic information.
5233   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5234   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5235                                               CK_BuiltinFnToFnPtr);
5236   TheCall->setCallee(PromotedCall.get());
5237 
5238   // Change the result type of the call to match the original value type. This
5239   // is arbitrary, but the codegen for these builtins ins design to handle it
5240   // gracefully.
5241   TheCall->setType(ResultType);
5242 
5243   return TheCallResult;
5244 }
5245 
5246 /// SemaBuiltinNontemporalOverloaded - We have a call to
5247 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5248 /// overloaded function based on the pointer type of its last argument.
5249 ///
5250 /// This function goes through and does final semantic checking for these
5251 /// builtins.
5252 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5253   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5254   DeclRefExpr *DRE =
5255       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5256   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5257   unsigned BuiltinID = FDecl->getBuiltinID();
5258   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5259           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5260          "Unexpected nontemporal load/store builtin!");
5261   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5262   unsigned numArgs = isStore ? 2 : 1;
5263 
5264   // Ensure that we have the proper number of arguments.
5265   if (checkArgCount(*this, TheCall, numArgs))
5266     return ExprError();
5267 
5268   // Inspect the last argument of the nontemporal builtin.  This should always
5269   // be a pointer type, from which we imply the type of the memory access.
5270   // Because it is a pointer type, we don't have to worry about any implicit
5271   // casts here.
5272   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5273   ExprResult PointerArgResult =
5274       DefaultFunctionArrayLvalueConversion(PointerArg);
5275 
5276   if (PointerArgResult.isInvalid())
5277     return ExprError();
5278   PointerArg = PointerArgResult.get();
5279   TheCall->setArg(numArgs - 1, PointerArg);
5280 
5281   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5282   if (!pointerType) {
5283     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5284         << PointerArg->getType() << PointerArg->getSourceRange();
5285     return ExprError();
5286   }
5287 
5288   QualType ValType = pointerType->getPointeeType();
5289 
5290   // Strip any qualifiers off ValType.
5291   ValType = ValType.getUnqualifiedType();
5292   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5293       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5294       !ValType->isVectorType()) {
5295     Diag(DRE->getBeginLoc(),
5296          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5297         << PointerArg->getType() << PointerArg->getSourceRange();
5298     return ExprError();
5299   }
5300 
5301   if (!isStore) {
5302     TheCall->setType(ValType);
5303     return TheCallResult;
5304   }
5305 
5306   ExprResult ValArg = TheCall->getArg(0);
5307   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5308       Context, ValType, /*consume*/ false);
5309   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5310   if (ValArg.isInvalid())
5311     return ExprError();
5312 
5313   TheCall->setArg(0, ValArg.get());
5314   TheCall->setType(Context.VoidTy);
5315   return TheCallResult;
5316 }
5317 
5318 /// CheckObjCString - Checks that the argument to the builtin
5319 /// CFString constructor is correct
5320 /// Note: It might also make sense to do the UTF-16 conversion here (would
5321 /// simplify the backend).
5322 bool Sema::CheckObjCString(Expr *Arg) {
5323   Arg = Arg->IgnoreParenCasts();
5324   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5325 
5326   if (!Literal || !Literal->isAscii()) {
5327     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5328         << Arg->getSourceRange();
5329     return true;
5330   }
5331 
5332   if (Literal->containsNonAsciiOrNull()) {
5333     StringRef String = Literal->getString();
5334     unsigned NumBytes = String.size();
5335     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5336     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5337     llvm::UTF16 *ToPtr = &ToBuf[0];
5338 
5339     llvm::ConversionResult Result =
5340         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5341                                  ToPtr + NumBytes, llvm::strictConversion);
5342     // Check for conversion failure.
5343     if (Result != llvm::conversionOK)
5344       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5345           << Arg->getSourceRange();
5346   }
5347   return false;
5348 }
5349 
5350 /// CheckObjCString - Checks that the format string argument to the os_log()
5351 /// and os_trace() functions is correct, and converts it to const char *.
5352 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5353   Arg = Arg->IgnoreParenCasts();
5354   auto *Literal = dyn_cast<StringLiteral>(Arg);
5355   if (!Literal) {
5356     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5357       Literal = ObjcLiteral->getString();
5358     }
5359   }
5360 
5361   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5362     return ExprError(
5363         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5364         << Arg->getSourceRange());
5365   }
5366 
5367   ExprResult Result(Literal);
5368   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5369   InitializedEntity Entity =
5370       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5371   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5372   return Result;
5373 }
5374 
5375 /// Check that the user is calling the appropriate va_start builtin for the
5376 /// target and calling convention.
5377 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5378   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5379   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5380   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5381   bool IsWindows = TT.isOSWindows();
5382   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5383   if (IsX64 || IsAArch64) {
5384     CallingConv CC = CC_C;
5385     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5386       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5387     if (IsMSVAStart) {
5388       // Don't allow this in System V ABI functions.
5389       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5390         return S.Diag(Fn->getBeginLoc(),
5391                       diag::err_ms_va_start_used_in_sysv_function);
5392     } else {
5393       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5394       // On x64 Windows, don't allow this in System V ABI functions.
5395       // (Yes, that means there's no corresponding way to support variadic
5396       // System V ABI functions on Windows.)
5397       if ((IsWindows && CC == CC_X86_64SysV) ||
5398           (!IsWindows && CC == CC_Win64))
5399         return S.Diag(Fn->getBeginLoc(),
5400                       diag::err_va_start_used_in_wrong_abi_function)
5401                << !IsWindows;
5402     }
5403     return false;
5404   }
5405 
5406   if (IsMSVAStart)
5407     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5408   return false;
5409 }
5410 
5411 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5412                                              ParmVarDecl **LastParam = nullptr) {
5413   // Determine whether the current function, block, or obj-c method is variadic
5414   // and get its parameter list.
5415   bool IsVariadic = false;
5416   ArrayRef<ParmVarDecl *> Params;
5417   DeclContext *Caller = S.CurContext;
5418   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5419     IsVariadic = Block->isVariadic();
5420     Params = Block->parameters();
5421   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5422     IsVariadic = FD->isVariadic();
5423     Params = FD->parameters();
5424   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5425     IsVariadic = MD->isVariadic();
5426     // FIXME: This isn't correct for methods (results in bogus warning).
5427     Params = MD->parameters();
5428   } else if (isa<CapturedDecl>(Caller)) {
5429     // We don't support va_start in a CapturedDecl.
5430     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5431     return true;
5432   } else {
5433     // This must be some other declcontext that parses exprs.
5434     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5435     return true;
5436   }
5437 
5438   if (!IsVariadic) {
5439     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5440     return true;
5441   }
5442 
5443   if (LastParam)
5444     *LastParam = Params.empty() ? nullptr : Params.back();
5445 
5446   return false;
5447 }
5448 
5449 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5450 /// for validity.  Emit an error and return true on failure; return false
5451 /// on success.
5452 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5453   Expr *Fn = TheCall->getCallee();
5454 
5455   if (checkVAStartABI(*this, BuiltinID, Fn))
5456     return true;
5457 
5458   if (TheCall->getNumArgs() > 2) {
5459     Diag(TheCall->getArg(2)->getBeginLoc(),
5460          diag::err_typecheck_call_too_many_args)
5461         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5462         << Fn->getSourceRange()
5463         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5464                        (*(TheCall->arg_end() - 1))->getEndLoc());
5465     return true;
5466   }
5467 
5468   if (TheCall->getNumArgs() < 2) {
5469     return Diag(TheCall->getEndLoc(),
5470                 diag::err_typecheck_call_too_few_args_at_least)
5471            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5472   }
5473 
5474   // Type-check the first argument normally.
5475   if (checkBuiltinArgument(*this, TheCall, 0))
5476     return true;
5477 
5478   // Check that the current function is variadic, and get its last parameter.
5479   ParmVarDecl *LastParam;
5480   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5481     return true;
5482 
5483   // Verify that the second argument to the builtin is the last argument of the
5484   // current function or method.
5485   bool SecondArgIsLastNamedArgument = false;
5486   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5487 
5488   // These are valid if SecondArgIsLastNamedArgument is false after the next
5489   // block.
5490   QualType Type;
5491   SourceLocation ParamLoc;
5492   bool IsCRegister = false;
5493 
5494   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5495     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5496       SecondArgIsLastNamedArgument = PV == LastParam;
5497 
5498       Type = PV->getType();
5499       ParamLoc = PV->getLocation();
5500       IsCRegister =
5501           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5502     }
5503   }
5504 
5505   if (!SecondArgIsLastNamedArgument)
5506     Diag(TheCall->getArg(1)->getBeginLoc(),
5507          diag::warn_second_arg_of_va_start_not_last_named_param);
5508   else if (IsCRegister || Type->isReferenceType() ||
5509            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5510              // Promotable integers are UB, but enumerations need a bit of
5511              // extra checking to see what their promotable type actually is.
5512              if (!Type->isPromotableIntegerType())
5513                return false;
5514              if (!Type->isEnumeralType())
5515                return true;
5516              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5517              return !(ED &&
5518                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5519            }()) {
5520     unsigned Reason = 0;
5521     if (Type->isReferenceType())  Reason = 1;
5522     else if (IsCRegister)         Reason = 2;
5523     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5524     Diag(ParamLoc, diag::note_parameter_type) << Type;
5525   }
5526 
5527   TheCall->setType(Context.VoidTy);
5528   return false;
5529 }
5530 
5531 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5532   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5533   //                 const char *named_addr);
5534 
5535   Expr *Func = Call->getCallee();
5536 
5537   if (Call->getNumArgs() < 3)
5538     return Diag(Call->getEndLoc(),
5539                 diag::err_typecheck_call_too_few_args_at_least)
5540            << 0 /*function call*/ << 3 << Call->getNumArgs();
5541 
5542   // Type-check the first argument normally.
5543   if (checkBuiltinArgument(*this, Call, 0))
5544     return true;
5545 
5546   // Check that the current function is variadic.
5547   if (checkVAStartIsInVariadicFunction(*this, Func))
5548     return true;
5549 
5550   // __va_start on Windows does not validate the parameter qualifiers
5551 
5552   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5553   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5554 
5555   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5556   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5557 
5558   const QualType &ConstCharPtrTy =
5559       Context.getPointerType(Context.CharTy.withConst());
5560   if (!Arg1Ty->isPointerType() ||
5561       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5562     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5563         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5564         << 0                                      /* qualifier difference */
5565         << 3                                      /* parameter mismatch */
5566         << 2 << Arg1->getType() << ConstCharPtrTy;
5567 
5568   const QualType SizeTy = Context.getSizeType();
5569   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5570     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5571         << Arg2->getType() << SizeTy << 1 /* different class */
5572         << 0                              /* qualifier difference */
5573         << 3                              /* parameter mismatch */
5574         << 3 << Arg2->getType() << SizeTy;
5575 
5576   return false;
5577 }
5578 
5579 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5580 /// friends.  This is declared to take (...), so we have to check everything.
5581 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5582   if (TheCall->getNumArgs() < 2)
5583     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5584            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5585   if (TheCall->getNumArgs() > 2)
5586     return Diag(TheCall->getArg(2)->getBeginLoc(),
5587                 diag::err_typecheck_call_too_many_args)
5588            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5589            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5590                           (*(TheCall->arg_end() - 1))->getEndLoc());
5591 
5592   ExprResult OrigArg0 = TheCall->getArg(0);
5593   ExprResult OrigArg1 = TheCall->getArg(1);
5594 
5595   // Do standard promotions between the two arguments, returning their common
5596   // type.
5597   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5598   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5599     return true;
5600 
5601   // Make sure any conversions are pushed back into the call; this is
5602   // type safe since unordered compare builtins are declared as "_Bool
5603   // foo(...)".
5604   TheCall->setArg(0, OrigArg0.get());
5605   TheCall->setArg(1, OrigArg1.get());
5606 
5607   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5608     return false;
5609 
5610   // If the common type isn't a real floating type, then the arguments were
5611   // invalid for this operation.
5612   if (Res.isNull() || !Res->isRealFloatingType())
5613     return Diag(OrigArg0.get()->getBeginLoc(),
5614                 diag::err_typecheck_call_invalid_ordered_compare)
5615            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5616            << SourceRange(OrigArg0.get()->getBeginLoc(),
5617                           OrigArg1.get()->getEndLoc());
5618 
5619   return false;
5620 }
5621 
5622 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5623 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5624 /// to check everything. We expect the last argument to be a floating point
5625 /// value.
5626 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5627   if (TheCall->getNumArgs() < NumArgs)
5628     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5629            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5630   if (TheCall->getNumArgs() > NumArgs)
5631     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5632                 diag::err_typecheck_call_too_many_args)
5633            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5634            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5635                           (*(TheCall->arg_end() - 1))->getEndLoc());
5636 
5637   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5638 
5639   if (OrigArg->isTypeDependent())
5640     return false;
5641 
5642   // This operation requires a non-_Complex floating-point number.
5643   if (!OrigArg->getType()->isRealFloatingType())
5644     return Diag(OrigArg->getBeginLoc(),
5645                 diag::err_typecheck_call_invalid_unary_fp)
5646            << OrigArg->getType() << OrigArg->getSourceRange();
5647 
5648   // If this is an implicit conversion from float -> float, double, or
5649   // long double, remove it.
5650   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5651     // Only remove standard FloatCasts, leaving other casts inplace
5652     if (Cast->getCastKind() == CK_FloatingCast) {
5653       Expr *CastArg = Cast->getSubExpr();
5654       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5655         assert(
5656             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5657              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5658              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5659             "promotion from float to either float, double, or long double is "
5660             "the only expected cast here");
5661         Cast->setSubExpr(nullptr);
5662         TheCall->setArg(NumArgs-1, CastArg);
5663       }
5664     }
5665   }
5666 
5667   return false;
5668 }
5669 
5670 // Customized Sema Checking for VSX builtins that have the following signature:
5671 // vector [...] builtinName(vector [...], vector [...], const int);
5672 // Which takes the same type of vectors (any legal vector type) for the first
5673 // two arguments and takes compile time constant for the third argument.
5674 // Example builtins are :
5675 // vector double vec_xxpermdi(vector double, vector double, int);
5676 // vector short vec_xxsldwi(vector short, vector short, int);
5677 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5678   unsigned ExpectedNumArgs = 3;
5679   if (TheCall->getNumArgs() < ExpectedNumArgs)
5680     return Diag(TheCall->getEndLoc(),
5681                 diag::err_typecheck_call_too_few_args_at_least)
5682            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5683            << TheCall->getSourceRange();
5684 
5685   if (TheCall->getNumArgs() > ExpectedNumArgs)
5686     return Diag(TheCall->getEndLoc(),
5687                 diag::err_typecheck_call_too_many_args_at_most)
5688            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5689            << TheCall->getSourceRange();
5690 
5691   // Check the third argument is a compile time constant
5692   llvm::APSInt Value;
5693   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5694     return Diag(TheCall->getBeginLoc(),
5695                 diag::err_vsx_builtin_nonconstant_argument)
5696            << 3 /* argument index */ << TheCall->getDirectCallee()
5697            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5698                           TheCall->getArg(2)->getEndLoc());
5699 
5700   QualType Arg1Ty = TheCall->getArg(0)->getType();
5701   QualType Arg2Ty = TheCall->getArg(1)->getType();
5702 
5703   // Check the type of argument 1 and argument 2 are vectors.
5704   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5705   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5706       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5707     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5708            << TheCall->getDirectCallee()
5709            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5710                           TheCall->getArg(1)->getEndLoc());
5711   }
5712 
5713   // Check the first two arguments are the same type.
5714   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5715     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5716            << TheCall->getDirectCallee()
5717            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5718                           TheCall->getArg(1)->getEndLoc());
5719   }
5720 
5721   // When default clang type checking is turned off and the customized type
5722   // checking is used, the returning type of the function must be explicitly
5723   // set. Otherwise it is _Bool by default.
5724   TheCall->setType(Arg1Ty);
5725 
5726   return false;
5727 }
5728 
5729 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5730 // This is declared to take (...), so we have to check everything.
5731 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5732   if (TheCall->getNumArgs() < 2)
5733     return ExprError(Diag(TheCall->getEndLoc(),
5734                           diag::err_typecheck_call_too_few_args_at_least)
5735                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5736                      << TheCall->getSourceRange());
5737 
5738   // Determine which of the following types of shufflevector we're checking:
5739   // 1) unary, vector mask: (lhs, mask)
5740   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5741   QualType resType = TheCall->getArg(0)->getType();
5742   unsigned numElements = 0;
5743 
5744   if (!TheCall->getArg(0)->isTypeDependent() &&
5745       !TheCall->getArg(1)->isTypeDependent()) {
5746     QualType LHSType = TheCall->getArg(0)->getType();
5747     QualType RHSType = TheCall->getArg(1)->getType();
5748 
5749     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5750       return ExprError(
5751           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5752           << TheCall->getDirectCallee()
5753           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5754                          TheCall->getArg(1)->getEndLoc()));
5755 
5756     numElements = LHSType->getAs<VectorType>()->getNumElements();
5757     unsigned numResElements = TheCall->getNumArgs() - 2;
5758 
5759     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5760     // with mask.  If so, verify that RHS is an integer vector type with the
5761     // same number of elts as lhs.
5762     if (TheCall->getNumArgs() == 2) {
5763       if (!RHSType->hasIntegerRepresentation() ||
5764           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5765         return ExprError(Diag(TheCall->getBeginLoc(),
5766                               diag::err_vec_builtin_incompatible_vector)
5767                          << TheCall->getDirectCallee()
5768                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5769                                         TheCall->getArg(1)->getEndLoc()));
5770     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5771       return ExprError(Diag(TheCall->getBeginLoc(),
5772                             diag::err_vec_builtin_incompatible_vector)
5773                        << TheCall->getDirectCallee()
5774                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5775                                       TheCall->getArg(1)->getEndLoc()));
5776     } else if (numElements != numResElements) {
5777       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5778       resType = Context.getVectorType(eltType, numResElements,
5779                                       VectorType::GenericVector);
5780     }
5781   }
5782 
5783   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5784     if (TheCall->getArg(i)->isTypeDependent() ||
5785         TheCall->getArg(i)->isValueDependent())
5786       continue;
5787 
5788     llvm::APSInt Result(32);
5789     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5790       return ExprError(Diag(TheCall->getBeginLoc(),
5791                             diag::err_shufflevector_nonconstant_argument)
5792                        << TheCall->getArg(i)->getSourceRange());
5793 
5794     // Allow -1 which will be translated to undef in the IR.
5795     if (Result.isSigned() && Result.isAllOnesValue())
5796       continue;
5797 
5798     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5799       return ExprError(Diag(TheCall->getBeginLoc(),
5800                             diag::err_shufflevector_argument_too_large)
5801                        << TheCall->getArg(i)->getSourceRange());
5802   }
5803 
5804   SmallVector<Expr*, 32> exprs;
5805 
5806   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5807     exprs.push_back(TheCall->getArg(i));
5808     TheCall->setArg(i, nullptr);
5809   }
5810 
5811   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5812                                          TheCall->getCallee()->getBeginLoc(),
5813                                          TheCall->getRParenLoc());
5814 }
5815 
5816 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5817 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5818                                        SourceLocation BuiltinLoc,
5819                                        SourceLocation RParenLoc) {
5820   ExprValueKind VK = VK_RValue;
5821   ExprObjectKind OK = OK_Ordinary;
5822   QualType DstTy = TInfo->getType();
5823   QualType SrcTy = E->getType();
5824 
5825   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5826     return ExprError(Diag(BuiltinLoc,
5827                           diag::err_convertvector_non_vector)
5828                      << E->getSourceRange());
5829   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5830     return ExprError(Diag(BuiltinLoc,
5831                           diag::err_convertvector_non_vector_type));
5832 
5833   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5834     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5835     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5836     if (SrcElts != DstElts)
5837       return ExprError(Diag(BuiltinLoc,
5838                             diag::err_convertvector_incompatible_vector)
5839                        << E->getSourceRange());
5840   }
5841 
5842   return new (Context)
5843       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5844 }
5845 
5846 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5847 // This is declared to take (const void*, ...) and can take two
5848 // optional constant int args.
5849 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5850   unsigned NumArgs = TheCall->getNumArgs();
5851 
5852   if (NumArgs > 3)
5853     return Diag(TheCall->getEndLoc(),
5854                 diag::err_typecheck_call_too_many_args_at_most)
5855            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5856 
5857   // Argument 0 is checked for us and the remaining arguments must be
5858   // constant integers.
5859   for (unsigned i = 1; i != NumArgs; ++i)
5860     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5861       return true;
5862 
5863   return false;
5864 }
5865 
5866 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5867 // __assume does not evaluate its arguments, and should warn if its argument
5868 // has side effects.
5869 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5870   Expr *Arg = TheCall->getArg(0);
5871   if (Arg->isInstantiationDependent()) return false;
5872 
5873   if (Arg->HasSideEffects(Context))
5874     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5875         << Arg->getSourceRange()
5876         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5877 
5878   return false;
5879 }
5880 
5881 /// Handle __builtin_alloca_with_align. This is declared
5882 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5883 /// than 8.
5884 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5885   // The alignment must be a constant integer.
5886   Expr *Arg = TheCall->getArg(1);
5887 
5888   // We can't check the value of a dependent argument.
5889   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5890     if (const auto *UE =
5891             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5892       if (UE->getKind() == UETT_AlignOf ||
5893           UE->getKind() == UETT_PreferredAlignOf)
5894         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5895             << Arg->getSourceRange();
5896 
5897     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5898 
5899     if (!Result.isPowerOf2())
5900       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5901              << Arg->getSourceRange();
5902 
5903     if (Result < Context.getCharWidth())
5904       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5905              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5906 
5907     if (Result > std::numeric_limits<int32_t>::max())
5908       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5909              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5910   }
5911 
5912   return false;
5913 }
5914 
5915 /// Handle __builtin_assume_aligned. This is declared
5916 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5917 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5918   unsigned NumArgs = TheCall->getNumArgs();
5919 
5920   if (NumArgs > 3)
5921     return Diag(TheCall->getEndLoc(),
5922                 diag::err_typecheck_call_too_many_args_at_most)
5923            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5924 
5925   // The alignment must be a constant integer.
5926   Expr *Arg = TheCall->getArg(1);
5927 
5928   // We can't check the value of a dependent argument.
5929   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5930     llvm::APSInt Result;
5931     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5932       return true;
5933 
5934     if (!Result.isPowerOf2())
5935       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5936              << Arg->getSourceRange();
5937   }
5938 
5939   if (NumArgs > 2) {
5940     ExprResult Arg(TheCall->getArg(2));
5941     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5942       Context.getSizeType(), false);
5943     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5944     if (Arg.isInvalid()) return true;
5945     TheCall->setArg(2, Arg.get());
5946   }
5947 
5948   return false;
5949 }
5950 
5951 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5952   unsigned BuiltinID =
5953       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5954   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5955 
5956   unsigned NumArgs = TheCall->getNumArgs();
5957   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5958   if (NumArgs < NumRequiredArgs) {
5959     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5960            << 0 /* function call */ << NumRequiredArgs << NumArgs
5961            << TheCall->getSourceRange();
5962   }
5963   if (NumArgs >= NumRequiredArgs + 0x100) {
5964     return Diag(TheCall->getEndLoc(),
5965                 diag::err_typecheck_call_too_many_args_at_most)
5966            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5967            << TheCall->getSourceRange();
5968   }
5969   unsigned i = 0;
5970 
5971   // For formatting call, check buffer arg.
5972   if (!IsSizeCall) {
5973     ExprResult Arg(TheCall->getArg(i));
5974     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5975         Context, Context.VoidPtrTy, false);
5976     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5977     if (Arg.isInvalid())
5978       return true;
5979     TheCall->setArg(i, Arg.get());
5980     i++;
5981   }
5982 
5983   // Check string literal arg.
5984   unsigned FormatIdx = i;
5985   {
5986     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5987     if (Arg.isInvalid())
5988       return true;
5989     TheCall->setArg(i, Arg.get());
5990     i++;
5991   }
5992 
5993   // Make sure variadic args are scalar.
5994   unsigned FirstDataArg = i;
5995   while (i < NumArgs) {
5996     ExprResult Arg = DefaultVariadicArgumentPromotion(
5997         TheCall->getArg(i), VariadicFunction, nullptr);
5998     if (Arg.isInvalid())
5999       return true;
6000     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6001     if (ArgSize.getQuantity() >= 0x100) {
6002       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6003              << i << (int)ArgSize.getQuantity() << 0xff
6004              << TheCall->getSourceRange();
6005     }
6006     TheCall->setArg(i, Arg.get());
6007     i++;
6008   }
6009 
6010   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6011   // call to avoid duplicate diagnostics.
6012   if (!IsSizeCall) {
6013     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6014     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6015     bool Success = CheckFormatArguments(
6016         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6017         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6018         CheckedVarArgs);
6019     if (!Success)
6020       return true;
6021   }
6022 
6023   if (IsSizeCall) {
6024     TheCall->setType(Context.getSizeType());
6025   } else {
6026     TheCall->setType(Context.VoidPtrTy);
6027   }
6028   return false;
6029 }
6030 
6031 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6032 /// TheCall is a constant expression.
6033 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6034                                   llvm::APSInt &Result) {
6035   Expr *Arg = TheCall->getArg(ArgNum);
6036   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6037   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6038 
6039   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6040 
6041   if (!Arg->isIntegerConstantExpr(Result, Context))
6042     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6043            << FDecl->getDeclName() << Arg->getSourceRange();
6044 
6045   return false;
6046 }
6047 
6048 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6049 /// TheCall is a constant expression in the range [Low, High].
6050 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6051                                        int Low, int High, bool RangeIsError) {
6052   llvm::APSInt Result;
6053 
6054   // We can't check the value of a dependent argument.
6055   Expr *Arg = TheCall->getArg(ArgNum);
6056   if (Arg->isTypeDependent() || Arg->isValueDependent())
6057     return false;
6058 
6059   // Check constant-ness first.
6060   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6061     return true;
6062 
6063   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6064     if (RangeIsError)
6065       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6066              << Result.toString(10) << Low << High << Arg->getSourceRange();
6067     else
6068       // Defer the warning until we know if the code will be emitted so that
6069       // dead code can ignore this.
6070       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6071                           PDiag(diag::warn_argument_invalid_range)
6072                               << Result.toString(10) << Low << High
6073                               << Arg->getSourceRange());
6074   }
6075 
6076   return false;
6077 }
6078 
6079 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6080 /// TheCall is a constant expression is a multiple of Num..
6081 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6082                                           unsigned Num) {
6083   llvm::APSInt Result;
6084 
6085   // We can't check the value of a dependent argument.
6086   Expr *Arg = TheCall->getArg(ArgNum);
6087   if (Arg->isTypeDependent() || Arg->isValueDependent())
6088     return false;
6089 
6090   // Check constant-ness first.
6091   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6092     return true;
6093 
6094   if (Result.getSExtValue() % Num != 0)
6095     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6096            << Num << Arg->getSourceRange();
6097 
6098   return false;
6099 }
6100 
6101 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6102 /// TheCall is an ARM/AArch64 special register string literal.
6103 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6104                                     int ArgNum, unsigned ExpectedFieldNum,
6105                                     bool AllowName) {
6106   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6107                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6108                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6109                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6110                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6111                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6112   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6113                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6114                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6115                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6116                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6117                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6118   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6119 
6120   // We can't check the value of a dependent argument.
6121   Expr *Arg = TheCall->getArg(ArgNum);
6122   if (Arg->isTypeDependent() || Arg->isValueDependent())
6123     return false;
6124 
6125   // Check if the argument is a string literal.
6126   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6127     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6128            << Arg->getSourceRange();
6129 
6130   // Check the type of special register given.
6131   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6132   SmallVector<StringRef, 6> Fields;
6133   Reg.split(Fields, ":");
6134 
6135   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6136     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6137            << Arg->getSourceRange();
6138 
6139   // If the string is the name of a register then we cannot check that it is
6140   // valid here but if the string is of one the forms described in ACLE then we
6141   // can check that the supplied fields are integers and within the valid
6142   // ranges.
6143   if (Fields.size() > 1) {
6144     bool FiveFields = Fields.size() == 5;
6145 
6146     bool ValidString = true;
6147     if (IsARMBuiltin) {
6148       ValidString &= Fields[0].startswith_lower("cp") ||
6149                      Fields[0].startswith_lower("p");
6150       if (ValidString)
6151         Fields[0] =
6152           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6153 
6154       ValidString &= Fields[2].startswith_lower("c");
6155       if (ValidString)
6156         Fields[2] = Fields[2].drop_front(1);
6157 
6158       if (FiveFields) {
6159         ValidString &= Fields[3].startswith_lower("c");
6160         if (ValidString)
6161           Fields[3] = Fields[3].drop_front(1);
6162       }
6163     }
6164 
6165     SmallVector<int, 5> Ranges;
6166     if (FiveFields)
6167       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6168     else
6169       Ranges.append({15, 7, 15});
6170 
6171     for (unsigned i=0; i<Fields.size(); ++i) {
6172       int IntField;
6173       ValidString &= !Fields[i].getAsInteger(10, IntField);
6174       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6175     }
6176 
6177     if (!ValidString)
6178       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6179              << Arg->getSourceRange();
6180   } else if (IsAArch64Builtin && Fields.size() == 1) {
6181     // If the register name is one of those that appear in the condition below
6182     // and the special register builtin being used is one of the write builtins,
6183     // then we require that the argument provided for writing to the register
6184     // is an integer constant expression. This is because it will be lowered to
6185     // an MSR (immediate) instruction, so we need to know the immediate at
6186     // compile time.
6187     if (TheCall->getNumArgs() != 2)
6188       return false;
6189 
6190     std::string RegLower = Reg.lower();
6191     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6192         RegLower != "pan" && RegLower != "uao")
6193       return false;
6194 
6195     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6196   }
6197 
6198   return false;
6199 }
6200 
6201 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6202 /// This checks that the target supports __builtin_longjmp and
6203 /// that val is a constant 1.
6204 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6205   if (!Context.getTargetInfo().hasSjLjLowering())
6206     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6207            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6208 
6209   Expr *Arg = TheCall->getArg(1);
6210   llvm::APSInt Result;
6211 
6212   // TODO: This is less than ideal. Overload this to take a value.
6213   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6214     return true;
6215 
6216   if (Result != 1)
6217     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6218            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6219 
6220   return false;
6221 }
6222 
6223 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6224 /// This checks that the target supports __builtin_setjmp.
6225 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6226   if (!Context.getTargetInfo().hasSjLjLowering())
6227     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6228            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6229   return false;
6230 }
6231 
6232 namespace {
6233 
6234 class UncoveredArgHandler {
6235   enum { Unknown = -1, AllCovered = -2 };
6236 
6237   signed FirstUncoveredArg = Unknown;
6238   SmallVector<const Expr *, 4> DiagnosticExprs;
6239 
6240 public:
6241   UncoveredArgHandler() = default;
6242 
6243   bool hasUncoveredArg() const {
6244     return (FirstUncoveredArg >= 0);
6245   }
6246 
6247   unsigned getUncoveredArg() const {
6248     assert(hasUncoveredArg() && "no uncovered argument");
6249     return FirstUncoveredArg;
6250   }
6251 
6252   void setAllCovered() {
6253     // A string has been found with all arguments covered, so clear out
6254     // the diagnostics.
6255     DiagnosticExprs.clear();
6256     FirstUncoveredArg = AllCovered;
6257   }
6258 
6259   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6260     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6261 
6262     // Don't update if a previous string covers all arguments.
6263     if (FirstUncoveredArg == AllCovered)
6264       return;
6265 
6266     // UncoveredArgHandler tracks the highest uncovered argument index
6267     // and with it all the strings that match this index.
6268     if (NewFirstUncoveredArg == FirstUncoveredArg)
6269       DiagnosticExprs.push_back(StrExpr);
6270     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6271       DiagnosticExprs.clear();
6272       DiagnosticExprs.push_back(StrExpr);
6273       FirstUncoveredArg = NewFirstUncoveredArg;
6274     }
6275   }
6276 
6277   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6278 };
6279 
6280 enum StringLiteralCheckType {
6281   SLCT_NotALiteral,
6282   SLCT_UncheckedLiteral,
6283   SLCT_CheckedLiteral
6284 };
6285 
6286 } // namespace
6287 
6288 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6289                                      BinaryOperatorKind BinOpKind,
6290                                      bool AddendIsRight) {
6291   unsigned BitWidth = Offset.getBitWidth();
6292   unsigned AddendBitWidth = Addend.getBitWidth();
6293   // There might be negative interim results.
6294   if (Addend.isUnsigned()) {
6295     Addend = Addend.zext(++AddendBitWidth);
6296     Addend.setIsSigned(true);
6297   }
6298   // Adjust the bit width of the APSInts.
6299   if (AddendBitWidth > BitWidth) {
6300     Offset = Offset.sext(AddendBitWidth);
6301     BitWidth = AddendBitWidth;
6302   } else if (BitWidth > AddendBitWidth) {
6303     Addend = Addend.sext(BitWidth);
6304   }
6305 
6306   bool Ov = false;
6307   llvm::APSInt ResOffset = Offset;
6308   if (BinOpKind == BO_Add)
6309     ResOffset = Offset.sadd_ov(Addend, Ov);
6310   else {
6311     assert(AddendIsRight && BinOpKind == BO_Sub &&
6312            "operator must be add or sub with addend on the right");
6313     ResOffset = Offset.ssub_ov(Addend, Ov);
6314   }
6315 
6316   // We add an offset to a pointer here so we should support an offset as big as
6317   // possible.
6318   if (Ov) {
6319     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6320            "index (intermediate) result too big");
6321     Offset = Offset.sext(2 * BitWidth);
6322     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6323     return;
6324   }
6325 
6326   Offset = ResOffset;
6327 }
6328 
6329 namespace {
6330 
6331 // This is a wrapper class around StringLiteral to support offsetted string
6332 // literals as format strings. It takes the offset into account when returning
6333 // the string and its length or the source locations to display notes correctly.
6334 class FormatStringLiteral {
6335   const StringLiteral *FExpr;
6336   int64_t Offset;
6337 
6338  public:
6339   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6340       : FExpr(fexpr), Offset(Offset) {}
6341 
6342   StringRef getString() const {
6343     return FExpr->getString().drop_front(Offset);
6344   }
6345 
6346   unsigned getByteLength() const {
6347     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6348   }
6349 
6350   unsigned getLength() const { return FExpr->getLength() - Offset; }
6351   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6352 
6353   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6354 
6355   QualType getType() const { return FExpr->getType(); }
6356 
6357   bool isAscii() const { return FExpr->isAscii(); }
6358   bool isWide() const { return FExpr->isWide(); }
6359   bool isUTF8() const { return FExpr->isUTF8(); }
6360   bool isUTF16() const { return FExpr->isUTF16(); }
6361   bool isUTF32() const { return FExpr->isUTF32(); }
6362   bool isPascal() const { return FExpr->isPascal(); }
6363 
6364   SourceLocation getLocationOfByte(
6365       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6366       const TargetInfo &Target, unsigned *StartToken = nullptr,
6367       unsigned *StartTokenByteOffset = nullptr) const {
6368     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6369                                     StartToken, StartTokenByteOffset);
6370   }
6371 
6372   SourceLocation getBeginLoc() const LLVM_READONLY {
6373     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6374   }
6375 
6376   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6377 };
6378 
6379 }  // namespace
6380 
6381 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6382                               const Expr *OrigFormatExpr,
6383                               ArrayRef<const Expr *> Args,
6384                               bool HasVAListArg, unsigned format_idx,
6385                               unsigned firstDataArg,
6386                               Sema::FormatStringType Type,
6387                               bool inFunctionCall,
6388                               Sema::VariadicCallType CallType,
6389                               llvm::SmallBitVector &CheckedVarArgs,
6390                               UncoveredArgHandler &UncoveredArg);
6391 
6392 // Determine if an expression is a string literal or constant string.
6393 // If this function returns false on the arguments to a function expecting a
6394 // format string, we will usually need to emit a warning.
6395 // True string literals are then checked by CheckFormatString.
6396 static StringLiteralCheckType
6397 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6398                       bool HasVAListArg, unsigned format_idx,
6399                       unsigned firstDataArg, Sema::FormatStringType Type,
6400                       Sema::VariadicCallType CallType, bool InFunctionCall,
6401                       llvm::SmallBitVector &CheckedVarArgs,
6402                       UncoveredArgHandler &UncoveredArg,
6403                       llvm::APSInt Offset) {
6404  tryAgain:
6405   assert(Offset.isSigned() && "invalid offset");
6406 
6407   if (E->isTypeDependent() || E->isValueDependent())
6408     return SLCT_NotALiteral;
6409 
6410   E = E->IgnoreParenCasts();
6411 
6412   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6413     // Technically -Wformat-nonliteral does not warn about this case.
6414     // The behavior of printf and friends in this case is implementation
6415     // dependent.  Ideally if the format string cannot be null then
6416     // it should have a 'nonnull' attribute in the function prototype.
6417     return SLCT_UncheckedLiteral;
6418 
6419   switch (E->getStmtClass()) {
6420   case Stmt::BinaryConditionalOperatorClass:
6421   case Stmt::ConditionalOperatorClass: {
6422     // The expression is a literal if both sub-expressions were, and it was
6423     // completely checked only if both sub-expressions were checked.
6424     const AbstractConditionalOperator *C =
6425         cast<AbstractConditionalOperator>(E);
6426 
6427     // Determine whether it is necessary to check both sub-expressions, for
6428     // example, because the condition expression is a constant that can be
6429     // evaluated at compile time.
6430     bool CheckLeft = true, CheckRight = true;
6431 
6432     bool Cond;
6433     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6434       if (Cond)
6435         CheckRight = false;
6436       else
6437         CheckLeft = false;
6438     }
6439 
6440     // We need to maintain the offsets for the right and the left hand side
6441     // separately to check if every possible indexed expression is a valid
6442     // string literal. They might have different offsets for different string
6443     // literals in the end.
6444     StringLiteralCheckType Left;
6445     if (!CheckLeft)
6446       Left = SLCT_UncheckedLiteral;
6447     else {
6448       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6449                                    HasVAListArg, format_idx, firstDataArg,
6450                                    Type, CallType, InFunctionCall,
6451                                    CheckedVarArgs, UncoveredArg, Offset);
6452       if (Left == SLCT_NotALiteral || !CheckRight) {
6453         return Left;
6454       }
6455     }
6456 
6457     StringLiteralCheckType Right =
6458         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6459                               HasVAListArg, format_idx, firstDataArg,
6460                               Type, CallType, InFunctionCall, CheckedVarArgs,
6461                               UncoveredArg, Offset);
6462 
6463     return (CheckLeft && Left < Right) ? Left : Right;
6464   }
6465 
6466   case Stmt::ImplicitCastExprClass:
6467     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6468     goto tryAgain;
6469 
6470   case Stmt::OpaqueValueExprClass:
6471     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6472       E = src;
6473       goto tryAgain;
6474     }
6475     return SLCT_NotALiteral;
6476 
6477   case Stmt::PredefinedExprClass:
6478     // While __func__, etc., are technically not string literals, they
6479     // cannot contain format specifiers and thus are not a security
6480     // liability.
6481     return SLCT_UncheckedLiteral;
6482 
6483   case Stmt::DeclRefExprClass: {
6484     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6485 
6486     // As an exception, do not flag errors for variables binding to
6487     // const string literals.
6488     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6489       bool isConstant = false;
6490       QualType T = DR->getType();
6491 
6492       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6493         isConstant = AT->getElementType().isConstant(S.Context);
6494       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6495         isConstant = T.isConstant(S.Context) &&
6496                      PT->getPointeeType().isConstant(S.Context);
6497       } else if (T->isObjCObjectPointerType()) {
6498         // In ObjC, there is usually no "const ObjectPointer" type,
6499         // so don't check if the pointee type is constant.
6500         isConstant = T.isConstant(S.Context);
6501       }
6502 
6503       if (isConstant) {
6504         if (const Expr *Init = VD->getAnyInitializer()) {
6505           // Look through initializers like const char c[] = { "foo" }
6506           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6507             if (InitList->isStringLiteralInit())
6508               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6509           }
6510           return checkFormatStringExpr(S, Init, Args,
6511                                        HasVAListArg, format_idx,
6512                                        firstDataArg, Type, CallType,
6513                                        /*InFunctionCall*/ false, CheckedVarArgs,
6514                                        UncoveredArg, Offset);
6515         }
6516       }
6517 
6518       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6519       // special check to see if the format string is a function parameter
6520       // of the function calling the printf function.  If the function
6521       // has an attribute indicating it is a printf-like function, then we
6522       // should suppress warnings concerning non-literals being used in a call
6523       // to a vprintf function.  For example:
6524       //
6525       // void
6526       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6527       //      va_list ap;
6528       //      va_start(ap, fmt);
6529       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6530       //      ...
6531       // }
6532       if (HasVAListArg) {
6533         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6534           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6535             int PVIndex = PV->getFunctionScopeIndex() + 1;
6536             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6537               // adjust for implicit parameter
6538               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6539                 if (MD->isInstance())
6540                   ++PVIndex;
6541               // We also check if the formats are compatible.
6542               // We can't pass a 'scanf' string to a 'printf' function.
6543               if (PVIndex == PVFormat->getFormatIdx() &&
6544                   Type == S.GetFormatStringType(PVFormat))
6545                 return SLCT_UncheckedLiteral;
6546             }
6547           }
6548         }
6549       }
6550     }
6551 
6552     return SLCT_NotALiteral;
6553   }
6554 
6555   case Stmt::CallExprClass:
6556   case Stmt::CXXMemberCallExprClass: {
6557     const CallExpr *CE = cast<CallExpr>(E);
6558     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6559       bool IsFirst = true;
6560       StringLiteralCheckType CommonResult;
6561       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6562         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6563         StringLiteralCheckType Result = checkFormatStringExpr(
6564             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6565             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6566         if (IsFirst) {
6567           CommonResult = Result;
6568           IsFirst = false;
6569         }
6570       }
6571       if (!IsFirst)
6572         return CommonResult;
6573 
6574       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6575         unsigned BuiltinID = FD->getBuiltinID();
6576         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6577             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6578           const Expr *Arg = CE->getArg(0);
6579           return checkFormatStringExpr(S, Arg, Args,
6580                                        HasVAListArg, format_idx,
6581                                        firstDataArg, Type, CallType,
6582                                        InFunctionCall, CheckedVarArgs,
6583                                        UncoveredArg, Offset);
6584         }
6585       }
6586     }
6587 
6588     return SLCT_NotALiteral;
6589   }
6590   case Stmt::ObjCMessageExprClass: {
6591     const auto *ME = cast<ObjCMessageExpr>(E);
6592     if (const auto *ND = ME->getMethodDecl()) {
6593       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6594         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6595         return checkFormatStringExpr(
6596             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6597             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6598       }
6599     }
6600 
6601     return SLCT_NotALiteral;
6602   }
6603   case Stmt::ObjCStringLiteralClass:
6604   case Stmt::StringLiteralClass: {
6605     const StringLiteral *StrE = nullptr;
6606 
6607     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6608       StrE = ObjCFExpr->getString();
6609     else
6610       StrE = cast<StringLiteral>(E);
6611 
6612     if (StrE) {
6613       if (Offset.isNegative() || Offset > StrE->getLength()) {
6614         // TODO: It would be better to have an explicit warning for out of
6615         // bounds literals.
6616         return SLCT_NotALiteral;
6617       }
6618       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6619       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6620                         firstDataArg, Type, InFunctionCall, CallType,
6621                         CheckedVarArgs, UncoveredArg);
6622       return SLCT_CheckedLiteral;
6623     }
6624 
6625     return SLCT_NotALiteral;
6626   }
6627   case Stmt::BinaryOperatorClass: {
6628     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6629 
6630     // A string literal + an int offset is still a string literal.
6631     if (BinOp->isAdditiveOp()) {
6632       Expr::EvalResult LResult, RResult;
6633 
6634       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6635       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6636 
6637       if (LIsInt != RIsInt) {
6638         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6639 
6640         if (LIsInt) {
6641           if (BinOpKind == BO_Add) {
6642             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6643             E = BinOp->getRHS();
6644             goto tryAgain;
6645           }
6646         } else {
6647           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6648           E = BinOp->getLHS();
6649           goto tryAgain;
6650         }
6651       }
6652     }
6653 
6654     return SLCT_NotALiteral;
6655   }
6656   case Stmt::UnaryOperatorClass: {
6657     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6658     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6659     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6660       Expr::EvalResult IndexResult;
6661       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6662         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6663                    /*RHS is int*/ true);
6664         E = ASE->getBase();
6665         goto tryAgain;
6666       }
6667     }
6668 
6669     return SLCT_NotALiteral;
6670   }
6671 
6672   default:
6673     return SLCT_NotALiteral;
6674   }
6675 }
6676 
6677 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6678   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6679       .Case("scanf", FST_Scanf)
6680       .Cases("printf", "printf0", FST_Printf)
6681       .Cases("NSString", "CFString", FST_NSString)
6682       .Case("strftime", FST_Strftime)
6683       .Case("strfmon", FST_Strfmon)
6684       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6685       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6686       .Case("os_trace", FST_OSLog)
6687       .Case("os_log", FST_OSLog)
6688       .Default(FST_Unknown);
6689 }
6690 
6691 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6692 /// functions) for correct use of format strings.
6693 /// Returns true if a format string has been fully checked.
6694 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6695                                 ArrayRef<const Expr *> Args,
6696                                 bool IsCXXMember,
6697                                 VariadicCallType CallType,
6698                                 SourceLocation Loc, SourceRange Range,
6699                                 llvm::SmallBitVector &CheckedVarArgs) {
6700   FormatStringInfo FSI;
6701   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6702     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6703                                 FSI.FirstDataArg, GetFormatStringType(Format),
6704                                 CallType, Loc, Range, CheckedVarArgs);
6705   return false;
6706 }
6707 
6708 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6709                                 bool HasVAListArg, unsigned format_idx,
6710                                 unsigned firstDataArg, FormatStringType Type,
6711                                 VariadicCallType CallType,
6712                                 SourceLocation Loc, SourceRange Range,
6713                                 llvm::SmallBitVector &CheckedVarArgs) {
6714   // CHECK: printf/scanf-like function is called with no format string.
6715   if (format_idx >= Args.size()) {
6716     Diag(Loc, diag::warn_missing_format_string) << Range;
6717     return false;
6718   }
6719 
6720   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6721 
6722   // CHECK: format string is not a string literal.
6723   //
6724   // Dynamically generated format strings are difficult to
6725   // automatically vet at compile time.  Requiring that format strings
6726   // are string literals: (1) permits the checking of format strings by
6727   // the compiler and thereby (2) can practically remove the source of
6728   // many format string exploits.
6729 
6730   // Format string can be either ObjC string (e.g. @"%d") or
6731   // C string (e.g. "%d")
6732   // ObjC string uses the same format specifiers as C string, so we can use
6733   // the same format string checking logic for both ObjC and C strings.
6734   UncoveredArgHandler UncoveredArg;
6735   StringLiteralCheckType CT =
6736       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6737                             format_idx, firstDataArg, Type, CallType,
6738                             /*IsFunctionCall*/ true, CheckedVarArgs,
6739                             UncoveredArg,
6740                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6741 
6742   // Generate a diagnostic where an uncovered argument is detected.
6743   if (UncoveredArg.hasUncoveredArg()) {
6744     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6745     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6746     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6747   }
6748 
6749   if (CT != SLCT_NotALiteral)
6750     // Literal format string found, check done!
6751     return CT == SLCT_CheckedLiteral;
6752 
6753   // Strftime is particular as it always uses a single 'time' argument,
6754   // so it is safe to pass a non-literal string.
6755   if (Type == FST_Strftime)
6756     return false;
6757 
6758   // Do not emit diag when the string param is a macro expansion and the
6759   // format is either NSString or CFString. This is a hack to prevent
6760   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6761   // which are usually used in place of NS and CF string literals.
6762   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6763   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6764     return false;
6765 
6766   // If there are no arguments specified, warn with -Wformat-security, otherwise
6767   // warn only with -Wformat-nonliteral.
6768   if (Args.size() == firstDataArg) {
6769     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6770       << OrigFormatExpr->getSourceRange();
6771     switch (Type) {
6772     default:
6773       break;
6774     case FST_Kprintf:
6775     case FST_FreeBSDKPrintf:
6776     case FST_Printf:
6777       Diag(FormatLoc, diag::note_format_security_fixit)
6778         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6779       break;
6780     case FST_NSString:
6781       Diag(FormatLoc, diag::note_format_security_fixit)
6782         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6783       break;
6784     }
6785   } else {
6786     Diag(FormatLoc, diag::warn_format_nonliteral)
6787       << OrigFormatExpr->getSourceRange();
6788   }
6789   return false;
6790 }
6791 
6792 namespace {
6793 
6794 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6795 protected:
6796   Sema &S;
6797   const FormatStringLiteral *FExpr;
6798   const Expr *OrigFormatExpr;
6799   const Sema::FormatStringType FSType;
6800   const unsigned FirstDataArg;
6801   const unsigned NumDataArgs;
6802   const char *Beg; // Start of format string.
6803   const bool HasVAListArg;
6804   ArrayRef<const Expr *> Args;
6805   unsigned FormatIdx;
6806   llvm::SmallBitVector CoveredArgs;
6807   bool usesPositionalArgs = false;
6808   bool atFirstArg = true;
6809   bool inFunctionCall;
6810   Sema::VariadicCallType CallType;
6811   llvm::SmallBitVector &CheckedVarArgs;
6812   UncoveredArgHandler &UncoveredArg;
6813 
6814 public:
6815   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6816                      const Expr *origFormatExpr,
6817                      const Sema::FormatStringType type, unsigned firstDataArg,
6818                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6819                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6820                      bool inFunctionCall, Sema::VariadicCallType callType,
6821                      llvm::SmallBitVector &CheckedVarArgs,
6822                      UncoveredArgHandler &UncoveredArg)
6823       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6824         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6825         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6826         inFunctionCall(inFunctionCall), CallType(callType),
6827         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6828     CoveredArgs.resize(numDataArgs);
6829     CoveredArgs.reset();
6830   }
6831 
6832   void DoneProcessing();
6833 
6834   void HandleIncompleteSpecifier(const char *startSpecifier,
6835                                  unsigned specifierLen) override;
6836 
6837   void HandleInvalidLengthModifier(
6838                            const analyze_format_string::FormatSpecifier &FS,
6839                            const analyze_format_string::ConversionSpecifier &CS,
6840                            const char *startSpecifier, unsigned specifierLen,
6841                            unsigned DiagID);
6842 
6843   void HandleNonStandardLengthModifier(
6844                     const analyze_format_string::FormatSpecifier &FS,
6845                     const char *startSpecifier, unsigned specifierLen);
6846 
6847   void HandleNonStandardConversionSpecifier(
6848                     const analyze_format_string::ConversionSpecifier &CS,
6849                     const char *startSpecifier, unsigned specifierLen);
6850 
6851   void HandlePosition(const char *startPos, unsigned posLen) override;
6852 
6853   void HandleInvalidPosition(const char *startSpecifier,
6854                              unsigned specifierLen,
6855                              analyze_format_string::PositionContext p) override;
6856 
6857   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6858 
6859   void HandleNullChar(const char *nullCharacter) override;
6860 
6861   template <typename Range>
6862   static void
6863   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6864                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6865                        bool IsStringLocation, Range StringRange,
6866                        ArrayRef<FixItHint> Fixit = None);
6867 
6868 protected:
6869   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6870                                         const char *startSpec,
6871                                         unsigned specifierLen,
6872                                         const char *csStart, unsigned csLen);
6873 
6874   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6875                                          const char *startSpec,
6876                                          unsigned specifierLen);
6877 
6878   SourceRange getFormatStringRange();
6879   CharSourceRange getSpecifierRange(const char *startSpecifier,
6880                                     unsigned specifierLen);
6881   SourceLocation getLocationOfByte(const char *x);
6882 
6883   const Expr *getDataArg(unsigned i) const;
6884 
6885   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6886                     const analyze_format_string::ConversionSpecifier &CS,
6887                     const char *startSpecifier, unsigned specifierLen,
6888                     unsigned argIndex);
6889 
6890   template <typename Range>
6891   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6892                             bool IsStringLocation, Range StringRange,
6893                             ArrayRef<FixItHint> Fixit = None);
6894 };
6895 
6896 } // namespace
6897 
6898 SourceRange CheckFormatHandler::getFormatStringRange() {
6899   return OrigFormatExpr->getSourceRange();
6900 }
6901 
6902 CharSourceRange CheckFormatHandler::
6903 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6904   SourceLocation Start = getLocationOfByte(startSpecifier);
6905   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6906 
6907   // Advance the end SourceLocation by one due to half-open ranges.
6908   End = End.getLocWithOffset(1);
6909 
6910   return CharSourceRange::getCharRange(Start, End);
6911 }
6912 
6913 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6914   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6915                                   S.getLangOpts(), S.Context.getTargetInfo());
6916 }
6917 
6918 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6919                                                    unsigned specifierLen){
6920   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6921                        getLocationOfByte(startSpecifier),
6922                        /*IsStringLocation*/true,
6923                        getSpecifierRange(startSpecifier, specifierLen));
6924 }
6925 
6926 void CheckFormatHandler::HandleInvalidLengthModifier(
6927     const analyze_format_string::FormatSpecifier &FS,
6928     const analyze_format_string::ConversionSpecifier &CS,
6929     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6930   using namespace analyze_format_string;
6931 
6932   const LengthModifier &LM = FS.getLengthModifier();
6933   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6934 
6935   // See if we know how to fix this length modifier.
6936   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6937   if (FixedLM) {
6938     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6939                          getLocationOfByte(LM.getStart()),
6940                          /*IsStringLocation*/true,
6941                          getSpecifierRange(startSpecifier, specifierLen));
6942 
6943     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6944       << FixedLM->toString()
6945       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6946 
6947   } else {
6948     FixItHint Hint;
6949     if (DiagID == diag::warn_format_nonsensical_length)
6950       Hint = FixItHint::CreateRemoval(LMRange);
6951 
6952     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6953                          getLocationOfByte(LM.getStart()),
6954                          /*IsStringLocation*/true,
6955                          getSpecifierRange(startSpecifier, specifierLen),
6956                          Hint);
6957   }
6958 }
6959 
6960 void CheckFormatHandler::HandleNonStandardLengthModifier(
6961     const analyze_format_string::FormatSpecifier &FS,
6962     const char *startSpecifier, unsigned specifierLen) {
6963   using namespace analyze_format_string;
6964 
6965   const LengthModifier &LM = FS.getLengthModifier();
6966   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6967 
6968   // See if we know how to fix this length modifier.
6969   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6970   if (FixedLM) {
6971     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6972                            << LM.toString() << 0,
6973                          getLocationOfByte(LM.getStart()),
6974                          /*IsStringLocation*/true,
6975                          getSpecifierRange(startSpecifier, specifierLen));
6976 
6977     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6978       << FixedLM->toString()
6979       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6980 
6981   } else {
6982     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6983                            << LM.toString() << 0,
6984                          getLocationOfByte(LM.getStart()),
6985                          /*IsStringLocation*/true,
6986                          getSpecifierRange(startSpecifier, specifierLen));
6987   }
6988 }
6989 
6990 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6991     const analyze_format_string::ConversionSpecifier &CS,
6992     const char *startSpecifier, unsigned specifierLen) {
6993   using namespace analyze_format_string;
6994 
6995   // See if we know how to fix this conversion specifier.
6996   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6997   if (FixedCS) {
6998     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6999                           << CS.toString() << /*conversion specifier*/1,
7000                          getLocationOfByte(CS.getStart()),
7001                          /*IsStringLocation*/true,
7002                          getSpecifierRange(startSpecifier, specifierLen));
7003 
7004     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7005     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7006       << FixedCS->toString()
7007       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7008   } else {
7009     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7010                           << CS.toString() << /*conversion specifier*/1,
7011                          getLocationOfByte(CS.getStart()),
7012                          /*IsStringLocation*/true,
7013                          getSpecifierRange(startSpecifier, specifierLen));
7014   }
7015 }
7016 
7017 void CheckFormatHandler::HandlePosition(const char *startPos,
7018                                         unsigned posLen) {
7019   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7020                                getLocationOfByte(startPos),
7021                                /*IsStringLocation*/true,
7022                                getSpecifierRange(startPos, posLen));
7023 }
7024 
7025 void
7026 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7027                                      analyze_format_string::PositionContext p) {
7028   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7029                          << (unsigned) p,
7030                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7031                        getSpecifierRange(startPos, posLen));
7032 }
7033 
7034 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7035                                             unsigned posLen) {
7036   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7037                                getLocationOfByte(startPos),
7038                                /*IsStringLocation*/true,
7039                                getSpecifierRange(startPos, posLen));
7040 }
7041 
7042 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7043   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7044     // The presence of a null character is likely an error.
7045     EmitFormatDiagnostic(
7046       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7047       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7048       getFormatStringRange());
7049   }
7050 }
7051 
7052 // Note that this may return NULL if there was an error parsing or building
7053 // one of the argument expressions.
7054 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7055   return Args[FirstDataArg + i];
7056 }
7057 
7058 void CheckFormatHandler::DoneProcessing() {
7059   // Does the number of data arguments exceed the number of
7060   // format conversions in the format string?
7061   if (!HasVAListArg) {
7062       // Find any arguments that weren't covered.
7063     CoveredArgs.flip();
7064     signed notCoveredArg = CoveredArgs.find_first();
7065     if (notCoveredArg >= 0) {
7066       assert((unsigned)notCoveredArg < NumDataArgs);
7067       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7068     } else {
7069       UncoveredArg.setAllCovered();
7070     }
7071   }
7072 }
7073 
7074 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7075                                    const Expr *ArgExpr) {
7076   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7077          "Invalid state");
7078 
7079   if (!ArgExpr)
7080     return;
7081 
7082   SourceLocation Loc = ArgExpr->getBeginLoc();
7083 
7084   if (S.getSourceManager().isInSystemMacro(Loc))
7085     return;
7086 
7087   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7088   for (auto E : DiagnosticExprs)
7089     PDiag << E->getSourceRange();
7090 
7091   CheckFormatHandler::EmitFormatDiagnostic(
7092                                   S, IsFunctionCall, DiagnosticExprs[0],
7093                                   PDiag, Loc, /*IsStringLocation*/false,
7094                                   DiagnosticExprs[0]->getSourceRange());
7095 }
7096 
7097 bool
7098 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7099                                                      SourceLocation Loc,
7100                                                      const char *startSpec,
7101                                                      unsigned specifierLen,
7102                                                      const char *csStart,
7103                                                      unsigned csLen) {
7104   bool keepGoing = true;
7105   if (argIndex < NumDataArgs) {
7106     // Consider the argument coverered, even though the specifier doesn't
7107     // make sense.
7108     CoveredArgs.set(argIndex);
7109   }
7110   else {
7111     // If argIndex exceeds the number of data arguments we
7112     // don't issue a warning because that is just a cascade of warnings (and
7113     // they may have intended '%%' anyway). We don't want to continue processing
7114     // the format string after this point, however, as we will like just get
7115     // gibberish when trying to match arguments.
7116     keepGoing = false;
7117   }
7118 
7119   StringRef Specifier(csStart, csLen);
7120 
7121   // If the specifier in non-printable, it could be the first byte of a UTF-8
7122   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7123   // hex value.
7124   std::string CodePointStr;
7125   if (!llvm::sys::locale::isPrint(*csStart)) {
7126     llvm::UTF32 CodePoint;
7127     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7128     const llvm::UTF8 *E =
7129         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7130     llvm::ConversionResult Result =
7131         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7132 
7133     if (Result != llvm::conversionOK) {
7134       unsigned char FirstChar = *csStart;
7135       CodePoint = (llvm::UTF32)FirstChar;
7136     }
7137 
7138     llvm::raw_string_ostream OS(CodePointStr);
7139     if (CodePoint < 256)
7140       OS << "\\x" << llvm::format("%02x", CodePoint);
7141     else if (CodePoint <= 0xFFFF)
7142       OS << "\\u" << llvm::format("%04x", CodePoint);
7143     else
7144       OS << "\\U" << llvm::format("%08x", CodePoint);
7145     OS.flush();
7146     Specifier = CodePointStr;
7147   }
7148 
7149   EmitFormatDiagnostic(
7150       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7151       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7152 
7153   return keepGoing;
7154 }
7155 
7156 void
7157 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7158                                                       const char *startSpec,
7159                                                       unsigned specifierLen) {
7160   EmitFormatDiagnostic(
7161     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7162     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7163 }
7164 
7165 bool
7166 CheckFormatHandler::CheckNumArgs(
7167   const analyze_format_string::FormatSpecifier &FS,
7168   const analyze_format_string::ConversionSpecifier &CS,
7169   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7170 
7171   if (argIndex >= NumDataArgs) {
7172     PartialDiagnostic PDiag = FS.usesPositionalArg()
7173       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7174            << (argIndex+1) << NumDataArgs)
7175       : S.PDiag(diag::warn_printf_insufficient_data_args);
7176     EmitFormatDiagnostic(
7177       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7178       getSpecifierRange(startSpecifier, specifierLen));
7179 
7180     // Since more arguments than conversion tokens are given, by extension
7181     // all arguments are covered, so mark this as so.
7182     UncoveredArg.setAllCovered();
7183     return false;
7184   }
7185   return true;
7186 }
7187 
7188 template<typename Range>
7189 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7190                                               SourceLocation Loc,
7191                                               bool IsStringLocation,
7192                                               Range StringRange,
7193                                               ArrayRef<FixItHint> FixIt) {
7194   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7195                        Loc, IsStringLocation, StringRange, FixIt);
7196 }
7197 
7198 /// If the format string is not within the function call, emit a note
7199 /// so that the function call and string are in diagnostic messages.
7200 ///
7201 /// \param InFunctionCall if true, the format string is within the function
7202 /// call and only one diagnostic message will be produced.  Otherwise, an
7203 /// extra note will be emitted pointing to location of the format string.
7204 ///
7205 /// \param ArgumentExpr the expression that is passed as the format string
7206 /// argument in the function call.  Used for getting locations when two
7207 /// diagnostics are emitted.
7208 ///
7209 /// \param PDiag the callee should already have provided any strings for the
7210 /// diagnostic message.  This function only adds locations and fixits
7211 /// to diagnostics.
7212 ///
7213 /// \param Loc primary location for diagnostic.  If two diagnostics are
7214 /// required, one will be at Loc and a new SourceLocation will be created for
7215 /// the other one.
7216 ///
7217 /// \param IsStringLocation if true, Loc points to the format string should be
7218 /// used for the note.  Otherwise, Loc points to the argument list and will
7219 /// be used with PDiag.
7220 ///
7221 /// \param StringRange some or all of the string to highlight.  This is
7222 /// templated so it can accept either a CharSourceRange or a SourceRange.
7223 ///
7224 /// \param FixIt optional fix it hint for the format string.
7225 template <typename Range>
7226 void CheckFormatHandler::EmitFormatDiagnostic(
7227     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7228     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7229     Range StringRange, ArrayRef<FixItHint> FixIt) {
7230   if (InFunctionCall) {
7231     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7232     D << StringRange;
7233     D << FixIt;
7234   } else {
7235     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7236       << ArgumentExpr->getSourceRange();
7237 
7238     const Sema::SemaDiagnosticBuilder &Note =
7239       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7240              diag::note_format_string_defined);
7241 
7242     Note << StringRange;
7243     Note << FixIt;
7244   }
7245 }
7246 
7247 //===--- CHECK: Printf format string checking ------------------------------===//
7248 
7249 namespace {
7250 
7251 class CheckPrintfHandler : public CheckFormatHandler {
7252 public:
7253   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7254                      const Expr *origFormatExpr,
7255                      const Sema::FormatStringType type, unsigned firstDataArg,
7256                      unsigned numDataArgs, bool isObjC, const char *beg,
7257                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7258                      unsigned formatIdx, bool inFunctionCall,
7259                      Sema::VariadicCallType CallType,
7260                      llvm::SmallBitVector &CheckedVarArgs,
7261                      UncoveredArgHandler &UncoveredArg)
7262       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7263                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7264                            inFunctionCall, CallType, CheckedVarArgs,
7265                            UncoveredArg) {}
7266 
7267   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7268 
7269   /// Returns true if '%@' specifiers are allowed in the format string.
7270   bool allowsObjCArg() const {
7271     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7272            FSType == Sema::FST_OSTrace;
7273   }
7274 
7275   bool HandleInvalidPrintfConversionSpecifier(
7276                                       const analyze_printf::PrintfSpecifier &FS,
7277                                       const char *startSpecifier,
7278                                       unsigned specifierLen) override;
7279 
7280   void handleInvalidMaskType(StringRef MaskType) override;
7281 
7282   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7283                              const char *startSpecifier,
7284                              unsigned specifierLen) override;
7285   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7286                        const char *StartSpecifier,
7287                        unsigned SpecifierLen,
7288                        const Expr *E);
7289 
7290   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7291                     const char *startSpecifier, unsigned specifierLen);
7292   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7293                            const analyze_printf::OptionalAmount &Amt,
7294                            unsigned type,
7295                            const char *startSpecifier, unsigned specifierLen);
7296   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7297                   const analyze_printf::OptionalFlag &flag,
7298                   const char *startSpecifier, unsigned specifierLen);
7299   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7300                          const analyze_printf::OptionalFlag &ignoredFlag,
7301                          const analyze_printf::OptionalFlag &flag,
7302                          const char *startSpecifier, unsigned specifierLen);
7303   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7304                            const Expr *E);
7305 
7306   void HandleEmptyObjCModifierFlag(const char *startFlag,
7307                                    unsigned flagLen) override;
7308 
7309   void HandleInvalidObjCModifierFlag(const char *startFlag,
7310                                             unsigned flagLen) override;
7311 
7312   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7313                                            const char *flagsEnd,
7314                                            const char *conversionPosition)
7315                                              override;
7316 };
7317 
7318 } // namespace
7319 
7320 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7321                                       const analyze_printf::PrintfSpecifier &FS,
7322                                       const char *startSpecifier,
7323                                       unsigned specifierLen) {
7324   const analyze_printf::PrintfConversionSpecifier &CS =
7325     FS.getConversionSpecifier();
7326 
7327   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7328                                           getLocationOfByte(CS.getStart()),
7329                                           startSpecifier, specifierLen,
7330                                           CS.getStart(), CS.getLength());
7331 }
7332 
7333 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7334   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7335 }
7336 
7337 bool CheckPrintfHandler::HandleAmount(
7338                                const analyze_format_string::OptionalAmount &Amt,
7339                                unsigned k, const char *startSpecifier,
7340                                unsigned specifierLen) {
7341   if (Amt.hasDataArgument()) {
7342     if (!HasVAListArg) {
7343       unsigned argIndex = Amt.getArgIndex();
7344       if (argIndex >= NumDataArgs) {
7345         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7346                                << k,
7347                              getLocationOfByte(Amt.getStart()),
7348                              /*IsStringLocation*/true,
7349                              getSpecifierRange(startSpecifier, specifierLen));
7350         // Don't do any more checking.  We will just emit
7351         // spurious errors.
7352         return false;
7353       }
7354 
7355       // Type check the data argument.  It should be an 'int'.
7356       // Although not in conformance with C99, we also allow the argument to be
7357       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7358       // doesn't emit a warning for that case.
7359       CoveredArgs.set(argIndex);
7360       const Expr *Arg = getDataArg(argIndex);
7361       if (!Arg)
7362         return false;
7363 
7364       QualType T = Arg->getType();
7365 
7366       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7367       assert(AT.isValid());
7368 
7369       if (!AT.matchesType(S.Context, T)) {
7370         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7371                                << k << AT.getRepresentativeTypeName(S.Context)
7372                                << T << Arg->getSourceRange(),
7373                              getLocationOfByte(Amt.getStart()),
7374                              /*IsStringLocation*/true,
7375                              getSpecifierRange(startSpecifier, specifierLen));
7376         // Don't do any more checking.  We will just emit
7377         // spurious errors.
7378         return false;
7379       }
7380     }
7381   }
7382   return true;
7383 }
7384 
7385 void CheckPrintfHandler::HandleInvalidAmount(
7386                                       const analyze_printf::PrintfSpecifier &FS,
7387                                       const analyze_printf::OptionalAmount &Amt,
7388                                       unsigned type,
7389                                       const char *startSpecifier,
7390                                       unsigned specifierLen) {
7391   const analyze_printf::PrintfConversionSpecifier &CS =
7392     FS.getConversionSpecifier();
7393 
7394   FixItHint fixit =
7395     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7396       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7397                                  Amt.getConstantLength()))
7398       : FixItHint();
7399 
7400   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7401                          << type << CS.toString(),
7402                        getLocationOfByte(Amt.getStart()),
7403                        /*IsStringLocation*/true,
7404                        getSpecifierRange(startSpecifier, specifierLen),
7405                        fixit);
7406 }
7407 
7408 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7409                                     const analyze_printf::OptionalFlag &flag,
7410                                     const char *startSpecifier,
7411                                     unsigned specifierLen) {
7412   // Warn about pointless flag with a fixit removal.
7413   const analyze_printf::PrintfConversionSpecifier &CS =
7414     FS.getConversionSpecifier();
7415   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7416                          << flag.toString() << CS.toString(),
7417                        getLocationOfByte(flag.getPosition()),
7418                        /*IsStringLocation*/true,
7419                        getSpecifierRange(startSpecifier, specifierLen),
7420                        FixItHint::CreateRemoval(
7421                          getSpecifierRange(flag.getPosition(), 1)));
7422 }
7423 
7424 void CheckPrintfHandler::HandleIgnoredFlag(
7425                                 const analyze_printf::PrintfSpecifier &FS,
7426                                 const analyze_printf::OptionalFlag &ignoredFlag,
7427                                 const analyze_printf::OptionalFlag &flag,
7428                                 const char *startSpecifier,
7429                                 unsigned specifierLen) {
7430   // Warn about ignored flag with a fixit removal.
7431   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7432                          << ignoredFlag.toString() << flag.toString(),
7433                        getLocationOfByte(ignoredFlag.getPosition()),
7434                        /*IsStringLocation*/true,
7435                        getSpecifierRange(startSpecifier, specifierLen),
7436                        FixItHint::CreateRemoval(
7437                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7438 }
7439 
7440 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7441                                                      unsigned flagLen) {
7442   // Warn about an empty flag.
7443   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7444                        getLocationOfByte(startFlag),
7445                        /*IsStringLocation*/true,
7446                        getSpecifierRange(startFlag, flagLen));
7447 }
7448 
7449 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7450                                                        unsigned flagLen) {
7451   // Warn about an invalid flag.
7452   auto Range = getSpecifierRange(startFlag, flagLen);
7453   StringRef flag(startFlag, flagLen);
7454   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7455                       getLocationOfByte(startFlag),
7456                       /*IsStringLocation*/true,
7457                       Range, FixItHint::CreateRemoval(Range));
7458 }
7459 
7460 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7461     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7462     // Warn about using '[...]' without a '@' conversion.
7463     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7464     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7465     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7466                          getLocationOfByte(conversionPosition),
7467                          /*IsStringLocation*/true,
7468                          Range, FixItHint::CreateRemoval(Range));
7469 }
7470 
7471 // Determines if the specified is a C++ class or struct containing
7472 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7473 // "c_str()").
7474 template<typename MemberKind>
7475 static llvm::SmallPtrSet<MemberKind*, 1>
7476 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7477   const RecordType *RT = Ty->getAs<RecordType>();
7478   llvm::SmallPtrSet<MemberKind*, 1> Results;
7479 
7480   if (!RT)
7481     return Results;
7482   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7483   if (!RD || !RD->getDefinition())
7484     return Results;
7485 
7486   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7487                  Sema::LookupMemberName);
7488   R.suppressDiagnostics();
7489 
7490   // We just need to include all members of the right kind turned up by the
7491   // filter, at this point.
7492   if (S.LookupQualifiedName(R, RT->getDecl()))
7493     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7494       NamedDecl *decl = (*I)->getUnderlyingDecl();
7495       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7496         Results.insert(FK);
7497     }
7498   return Results;
7499 }
7500 
7501 /// Check if we could call '.c_str()' on an object.
7502 ///
7503 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7504 /// allow the call, or if it would be ambiguous).
7505 bool Sema::hasCStrMethod(const Expr *E) {
7506   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7507 
7508   MethodSet Results =
7509       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7510   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7511        MI != ME; ++MI)
7512     if ((*MI)->getMinRequiredArguments() == 0)
7513       return true;
7514   return false;
7515 }
7516 
7517 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7518 // better diagnostic if so. AT is assumed to be valid.
7519 // Returns true when a c_str() conversion method is found.
7520 bool CheckPrintfHandler::checkForCStrMembers(
7521     const analyze_printf::ArgType &AT, const Expr *E) {
7522   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7523 
7524   MethodSet Results =
7525       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7526 
7527   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7528        MI != ME; ++MI) {
7529     const CXXMethodDecl *Method = *MI;
7530     if (Method->getMinRequiredArguments() == 0 &&
7531         AT.matchesType(S.Context, Method->getReturnType())) {
7532       // FIXME: Suggest parens if the expression needs them.
7533       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7534       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7535           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7536       return true;
7537     }
7538   }
7539 
7540   return false;
7541 }
7542 
7543 bool
7544 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7545                                             &FS,
7546                                           const char *startSpecifier,
7547                                           unsigned specifierLen) {
7548   using namespace analyze_format_string;
7549   using namespace analyze_printf;
7550 
7551   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7552 
7553   if (FS.consumesDataArgument()) {
7554     if (atFirstArg) {
7555         atFirstArg = false;
7556         usesPositionalArgs = FS.usesPositionalArg();
7557     }
7558     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7559       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7560                                         startSpecifier, specifierLen);
7561       return false;
7562     }
7563   }
7564 
7565   // First check if the field width, precision, and conversion specifier
7566   // have matching data arguments.
7567   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7568                     startSpecifier, specifierLen)) {
7569     return false;
7570   }
7571 
7572   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7573                     startSpecifier, specifierLen)) {
7574     return false;
7575   }
7576 
7577   if (!CS.consumesDataArgument()) {
7578     // FIXME: Technically specifying a precision or field width here
7579     // makes no sense.  Worth issuing a warning at some point.
7580     return true;
7581   }
7582 
7583   // Consume the argument.
7584   unsigned argIndex = FS.getArgIndex();
7585   if (argIndex < NumDataArgs) {
7586     // The check to see if the argIndex is valid will come later.
7587     // We set the bit here because we may exit early from this
7588     // function if we encounter some other error.
7589     CoveredArgs.set(argIndex);
7590   }
7591 
7592   // FreeBSD kernel extensions.
7593   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7594       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7595     // We need at least two arguments.
7596     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7597       return false;
7598 
7599     // Claim the second argument.
7600     CoveredArgs.set(argIndex + 1);
7601 
7602     // Type check the first argument (int for %b, pointer for %D)
7603     const Expr *Ex = getDataArg(argIndex);
7604     const analyze_printf::ArgType &AT =
7605       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7606         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7607     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7608       EmitFormatDiagnostic(
7609           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7610               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7611               << false << Ex->getSourceRange(),
7612           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7613           getSpecifierRange(startSpecifier, specifierLen));
7614 
7615     // Type check the second argument (char * for both %b and %D)
7616     Ex = getDataArg(argIndex + 1);
7617     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7618     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7619       EmitFormatDiagnostic(
7620           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7621               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7622               << false << Ex->getSourceRange(),
7623           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7624           getSpecifierRange(startSpecifier, specifierLen));
7625 
7626      return true;
7627   }
7628 
7629   // Check for using an Objective-C specific conversion specifier
7630   // in a non-ObjC literal.
7631   if (!allowsObjCArg() && CS.isObjCArg()) {
7632     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7633                                                   specifierLen);
7634   }
7635 
7636   // %P can only be used with os_log.
7637   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7638     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7639                                                   specifierLen);
7640   }
7641 
7642   // %n is not allowed with os_log.
7643   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7644     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7645                          getLocationOfByte(CS.getStart()),
7646                          /*IsStringLocation*/ false,
7647                          getSpecifierRange(startSpecifier, specifierLen));
7648 
7649     return true;
7650   }
7651 
7652   // Only scalars are allowed for os_trace.
7653   if (FSType == Sema::FST_OSTrace &&
7654       (CS.getKind() == ConversionSpecifier::PArg ||
7655        CS.getKind() == ConversionSpecifier::sArg ||
7656        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7657     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7658                                                   specifierLen);
7659   }
7660 
7661   // Check for use of public/private annotation outside of os_log().
7662   if (FSType != Sema::FST_OSLog) {
7663     if (FS.isPublic().isSet()) {
7664       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7665                                << "public",
7666                            getLocationOfByte(FS.isPublic().getPosition()),
7667                            /*IsStringLocation*/ false,
7668                            getSpecifierRange(startSpecifier, specifierLen));
7669     }
7670     if (FS.isPrivate().isSet()) {
7671       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7672                                << "private",
7673                            getLocationOfByte(FS.isPrivate().getPosition()),
7674                            /*IsStringLocation*/ false,
7675                            getSpecifierRange(startSpecifier, specifierLen));
7676     }
7677   }
7678 
7679   // Check for invalid use of field width
7680   if (!FS.hasValidFieldWidth()) {
7681     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7682         startSpecifier, specifierLen);
7683   }
7684 
7685   // Check for invalid use of precision
7686   if (!FS.hasValidPrecision()) {
7687     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7688         startSpecifier, specifierLen);
7689   }
7690 
7691   // Precision is mandatory for %P specifier.
7692   if (CS.getKind() == ConversionSpecifier::PArg &&
7693       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7694     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7695                          getLocationOfByte(startSpecifier),
7696                          /*IsStringLocation*/ false,
7697                          getSpecifierRange(startSpecifier, specifierLen));
7698   }
7699 
7700   // Check each flag does not conflict with any other component.
7701   if (!FS.hasValidThousandsGroupingPrefix())
7702     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7703   if (!FS.hasValidLeadingZeros())
7704     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7705   if (!FS.hasValidPlusPrefix())
7706     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7707   if (!FS.hasValidSpacePrefix())
7708     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7709   if (!FS.hasValidAlternativeForm())
7710     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7711   if (!FS.hasValidLeftJustified())
7712     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7713 
7714   // Check that flags are not ignored by another flag
7715   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7716     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7717         startSpecifier, specifierLen);
7718   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7719     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7720             startSpecifier, specifierLen);
7721 
7722   // Check the length modifier is valid with the given conversion specifier.
7723   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7724                                  S.getLangOpts()))
7725     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7726                                 diag::warn_format_nonsensical_length);
7727   else if (!FS.hasStandardLengthModifier())
7728     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7729   else if (!FS.hasStandardLengthConversionCombination())
7730     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7731                                 diag::warn_format_non_standard_conversion_spec);
7732 
7733   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7734     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7735 
7736   // The remaining checks depend on the data arguments.
7737   if (HasVAListArg)
7738     return true;
7739 
7740   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7741     return false;
7742 
7743   const Expr *Arg = getDataArg(argIndex);
7744   if (!Arg)
7745     return true;
7746 
7747   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7748 }
7749 
7750 static bool requiresParensToAddCast(const Expr *E) {
7751   // FIXME: We should have a general way to reason about operator
7752   // precedence and whether parens are actually needed here.
7753   // Take care of a few common cases where they aren't.
7754   const Expr *Inside = E->IgnoreImpCasts();
7755   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7756     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7757 
7758   switch (Inside->getStmtClass()) {
7759   case Stmt::ArraySubscriptExprClass:
7760   case Stmt::CallExprClass:
7761   case Stmt::CharacterLiteralClass:
7762   case Stmt::CXXBoolLiteralExprClass:
7763   case Stmt::DeclRefExprClass:
7764   case Stmt::FloatingLiteralClass:
7765   case Stmt::IntegerLiteralClass:
7766   case Stmt::MemberExprClass:
7767   case Stmt::ObjCArrayLiteralClass:
7768   case Stmt::ObjCBoolLiteralExprClass:
7769   case Stmt::ObjCBoxedExprClass:
7770   case Stmt::ObjCDictionaryLiteralClass:
7771   case Stmt::ObjCEncodeExprClass:
7772   case Stmt::ObjCIvarRefExprClass:
7773   case Stmt::ObjCMessageExprClass:
7774   case Stmt::ObjCPropertyRefExprClass:
7775   case Stmt::ObjCStringLiteralClass:
7776   case Stmt::ObjCSubscriptRefExprClass:
7777   case Stmt::ParenExprClass:
7778   case Stmt::StringLiteralClass:
7779   case Stmt::UnaryOperatorClass:
7780     return false;
7781   default:
7782     return true;
7783   }
7784 }
7785 
7786 static std::pair<QualType, StringRef>
7787 shouldNotPrintDirectly(const ASTContext &Context,
7788                        QualType IntendedTy,
7789                        const Expr *E) {
7790   // Use a 'while' to peel off layers of typedefs.
7791   QualType TyTy = IntendedTy;
7792   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7793     StringRef Name = UserTy->getDecl()->getName();
7794     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7795       .Case("CFIndex", Context.getNSIntegerType())
7796       .Case("NSInteger", Context.getNSIntegerType())
7797       .Case("NSUInteger", Context.getNSUIntegerType())
7798       .Case("SInt32", Context.IntTy)
7799       .Case("UInt32", Context.UnsignedIntTy)
7800       .Default(QualType());
7801 
7802     if (!CastTy.isNull())
7803       return std::make_pair(CastTy, Name);
7804 
7805     TyTy = UserTy->desugar();
7806   }
7807 
7808   // Strip parens if necessary.
7809   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7810     return shouldNotPrintDirectly(Context,
7811                                   PE->getSubExpr()->getType(),
7812                                   PE->getSubExpr());
7813 
7814   // If this is a conditional expression, then its result type is constructed
7815   // via usual arithmetic conversions and thus there might be no necessary
7816   // typedef sugar there.  Recurse to operands to check for NSInteger &
7817   // Co. usage condition.
7818   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7819     QualType TrueTy, FalseTy;
7820     StringRef TrueName, FalseName;
7821 
7822     std::tie(TrueTy, TrueName) =
7823       shouldNotPrintDirectly(Context,
7824                              CO->getTrueExpr()->getType(),
7825                              CO->getTrueExpr());
7826     std::tie(FalseTy, FalseName) =
7827       shouldNotPrintDirectly(Context,
7828                              CO->getFalseExpr()->getType(),
7829                              CO->getFalseExpr());
7830 
7831     if (TrueTy == FalseTy)
7832       return std::make_pair(TrueTy, TrueName);
7833     else if (TrueTy.isNull())
7834       return std::make_pair(FalseTy, FalseName);
7835     else if (FalseTy.isNull())
7836       return std::make_pair(TrueTy, TrueName);
7837   }
7838 
7839   return std::make_pair(QualType(), StringRef());
7840 }
7841 
7842 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7843 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7844 /// type do not count.
7845 static bool
7846 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7847   QualType From = ICE->getSubExpr()->getType();
7848   QualType To = ICE->getType();
7849   // It's an integer promotion if the destination type is the promoted
7850   // source type.
7851   if (ICE->getCastKind() == CK_IntegralCast &&
7852       From->isPromotableIntegerType() &&
7853       S.Context.getPromotedIntegerType(From) == To)
7854     return true;
7855   // Look through vector types, since we do default argument promotion for
7856   // those in OpenCL.
7857   if (const auto *VecTy = From->getAs<ExtVectorType>())
7858     From = VecTy->getElementType();
7859   if (const auto *VecTy = To->getAs<ExtVectorType>())
7860     To = VecTy->getElementType();
7861   // It's a floating promotion if the source type is a lower rank.
7862   return ICE->getCastKind() == CK_FloatingCast &&
7863          S.Context.getFloatingTypeOrder(From, To) < 0;
7864 }
7865 
7866 bool
7867 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7868                                     const char *StartSpecifier,
7869                                     unsigned SpecifierLen,
7870                                     const Expr *E) {
7871   using namespace analyze_format_string;
7872   using namespace analyze_printf;
7873 
7874   // Now type check the data expression that matches the
7875   // format specifier.
7876   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7877   if (!AT.isValid())
7878     return true;
7879 
7880   QualType ExprTy = E->getType();
7881   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7882     ExprTy = TET->getUnderlyingExpr()->getType();
7883   }
7884 
7885   const analyze_printf::ArgType::MatchKind Match =
7886       AT.matchesType(S.Context, ExprTy);
7887   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7888   if (Match == analyze_printf::ArgType::Match)
7889     return true;
7890 
7891   // Look through argument promotions for our error message's reported type.
7892   // This includes the integral and floating promotions, but excludes array
7893   // and function pointer decay (seeing that an argument intended to be a
7894   // string has type 'char [6]' is probably more confusing than 'char *') and
7895   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7896   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7897     if (isArithmeticArgumentPromotion(S, ICE)) {
7898       E = ICE->getSubExpr();
7899       ExprTy = E->getType();
7900 
7901       // Check if we didn't match because of an implicit cast from a 'char'
7902       // or 'short' to an 'int'.  This is done because printf is a varargs
7903       // function.
7904       if (ICE->getType() == S.Context.IntTy ||
7905           ICE->getType() == S.Context.UnsignedIntTy) {
7906         // All further checking is done on the subexpression.
7907         if (AT.matchesType(S.Context, ExprTy))
7908           return true;
7909       }
7910     }
7911   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7912     // Special case for 'a', which has type 'int' in C.
7913     // Note, however, that we do /not/ want to treat multibyte constants like
7914     // 'MooV' as characters! This form is deprecated but still exists.
7915     if (ExprTy == S.Context.IntTy)
7916       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7917         ExprTy = S.Context.CharTy;
7918   }
7919 
7920   // Look through enums to their underlying type.
7921   bool IsEnum = false;
7922   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7923     ExprTy = EnumTy->getDecl()->getIntegerType();
7924     IsEnum = true;
7925   }
7926 
7927   // %C in an Objective-C context prints a unichar, not a wchar_t.
7928   // If the argument is an integer of some kind, believe the %C and suggest
7929   // a cast instead of changing the conversion specifier.
7930   QualType IntendedTy = ExprTy;
7931   if (isObjCContext() &&
7932       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7933     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7934         !ExprTy->isCharType()) {
7935       // 'unichar' is defined as a typedef of unsigned short, but we should
7936       // prefer using the typedef if it is visible.
7937       IntendedTy = S.Context.UnsignedShortTy;
7938 
7939       // While we are here, check if the value is an IntegerLiteral that happens
7940       // to be within the valid range.
7941       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7942         const llvm::APInt &V = IL->getValue();
7943         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7944           return true;
7945       }
7946 
7947       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7948                           Sema::LookupOrdinaryName);
7949       if (S.LookupName(Result, S.getCurScope())) {
7950         NamedDecl *ND = Result.getFoundDecl();
7951         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7952           if (TD->getUnderlyingType() == IntendedTy)
7953             IntendedTy = S.Context.getTypedefType(TD);
7954       }
7955     }
7956   }
7957 
7958   // Special-case some of Darwin's platform-independence types by suggesting
7959   // casts to primitive types that are known to be large enough.
7960   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7961   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7962     QualType CastTy;
7963     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7964     if (!CastTy.isNull()) {
7965       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7966       // (long in ASTContext). Only complain to pedants.
7967       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7968           (AT.isSizeT() || AT.isPtrdiffT()) &&
7969           AT.matchesType(S.Context, CastTy))
7970         Pedantic = true;
7971       IntendedTy = CastTy;
7972       ShouldNotPrintDirectly = true;
7973     }
7974   }
7975 
7976   // We may be able to offer a FixItHint if it is a supported type.
7977   PrintfSpecifier fixedFS = FS;
7978   bool Success =
7979       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7980 
7981   if (Success) {
7982     // Get the fix string from the fixed format specifier
7983     SmallString<16> buf;
7984     llvm::raw_svector_ostream os(buf);
7985     fixedFS.toString(os);
7986 
7987     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7988 
7989     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7990       unsigned Diag =
7991           Pedantic
7992               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7993               : diag::warn_format_conversion_argument_type_mismatch;
7994       // In this case, the specifier is wrong and should be changed to match
7995       // the argument.
7996       EmitFormatDiagnostic(S.PDiag(Diag)
7997                                << AT.getRepresentativeTypeName(S.Context)
7998                                << IntendedTy << IsEnum << E->getSourceRange(),
7999                            E->getBeginLoc(),
8000                            /*IsStringLocation*/ false, SpecRange,
8001                            FixItHint::CreateReplacement(SpecRange, os.str()));
8002     } else {
8003       // The canonical type for formatting this value is different from the
8004       // actual type of the expression. (This occurs, for example, with Darwin's
8005       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8006       // should be printed as 'long' for 64-bit compatibility.)
8007       // Rather than emitting a normal format/argument mismatch, we want to
8008       // add a cast to the recommended type (and correct the format string
8009       // if necessary).
8010       SmallString<16> CastBuf;
8011       llvm::raw_svector_ostream CastFix(CastBuf);
8012       CastFix << "(";
8013       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8014       CastFix << ")";
8015 
8016       SmallVector<FixItHint,4> Hints;
8017       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8018         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8019 
8020       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8021         // If there's already a cast present, just replace it.
8022         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8023         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8024 
8025       } else if (!requiresParensToAddCast(E)) {
8026         // If the expression has high enough precedence,
8027         // just write the C-style cast.
8028         Hints.push_back(
8029             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8030       } else {
8031         // Otherwise, add parens around the expression as well as the cast.
8032         CastFix << "(";
8033         Hints.push_back(
8034             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8035 
8036         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8037         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8038       }
8039 
8040       if (ShouldNotPrintDirectly) {
8041         // The expression has a type that should not be printed directly.
8042         // We extract the name from the typedef because we don't want to show
8043         // the underlying type in the diagnostic.
8044         StringRef Name;
8045         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8046           Name = TypedefTy->getDecl()->getName();
8047         else
8048           Name = CastTyName;
8049         unsigned Diag = Pedantic
8050                             ? diag::warn_format_argument_needs_cast_pedantic
8051                             : diag::warn_format_argument_needs_cast;
8052         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8053                                            << E->getSourceRange(),
8054                              E->getBeginLoc(), /*IsStringLocation=*/false,
8055                              SpecRange, Hints);
8056       } else {
8057         // In this case, the expression could be printed using a different
8058         // specifier, but we've decided that the specifier is probably correct
8059         // and we should cast instead. Just use the normal warning message.
8060         EmitFormatDiagnostic(
8061             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8062                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8063                 << E->getSourceRange(),
8064             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8065       }
8066     }
8067   } else {
8068     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8069                                                    SpecifierLen);
8070     // Since the warning for passing non-POD types to variadic functions
8071     // was deferred until now, we emit a warning for non-POD
8072     // arguments here.
8073     switch (S.isValidVarArgType(ExprTy)) {
8074     case Sema::VAK_Valid:
8075     case Sema::VAK_ValidInCXX11: {
8076       unsigned Diag =
8077           Pedantic
8078               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8079               : diag::warn_format_conversion_argument_type_mismatch;
8080 
8081       EmitFormatDiagnostic(
8082           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8083                         << IsEnum << CSR << E->getSourceRange(),
8084           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8085       break;
8086     }
8087     case Sema::VAK_Undefined:
8088     case Sema::VAK_MSVCUndefined:
8089       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8090                                << S.getLangOpts().CPlusPlus11 << ExprTy
8091                                << CallType
8092                                << AT.getRepresentativeTypeName(S.Context) << CSR
8093                                << E->getSourceRange(),
8094                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8095       checkForCStrMembers(AT, E);
8096       break;
8097 
8098     case Sema::VAK_Invalid:
8099       if (ExprTy->isObjCObjectType())
8100         EmitFormatDiagnostic(
8101             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8102                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8103                 << AT.getRepresentativeTypeName(S.Context) << CSR
8104                 << E->getSourceRange(),
8105             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8106       else
8107         // FIXME: If this is an initializer list, suggest removing the braces
8108         // or inserting a cast to the target type.
8109         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8110             << isa<InitListExpr>(E) << ExprTy << CallType
8111             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8112       break;
8113     }
8114 
8115     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8116            "format string specifier index out of range");
8117     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8118   }
8119 
8120   return true;
8121 }
8122 
8123 //===--- CHECK: Scanf format string checking ------------------------------===//
8124 
8125 namespace {
8126 
8127 class CheckScanfHandler : public CheckFormatHandler {
8128 public:
8129   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8130                     const Expr *origFormatExpr, Sema::FormatStringType type,
8131                     unsigned firstDataArg, unsigned numDataArgs,
8132                     const char *beg, bool hasVAListArg,
8133                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8134                     bool inFunctionCall, Sema::VariadicCallType CallType,
8135                     llvm::SmallBitVector &CheckedVarArgs,
8136                     UncoveredArgHandler &UncoveredArg)
8137       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8138                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8139                            inFunctionCall, CallType, CheckedVarArgs,
8140                            UncoveredArg) {}
8141 
8142   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8143                             const char *startSpecifier,
8144                             unsigned specifierLen) override;
8145 
8146   bool HandleInvalidScanfConversionSpecifier(
8147           const analyze_scanf::ScanfSpecifier &FS,
8148           const char *startSpecifier,
8149           unsigned specifierLen) override;
8150 
8151   void HandleIncompleteScanList(const char *start, const char *end) override;
8152 };
8153 
8154 } // namespace
8155 
8156 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8157                                                  const char *end) {
8158   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8159                        getLocationOfByte(end), /*IsStringLocation*/true,
8160                        getSpecifierRange(start, end - start));
8161 }
8162 
8163 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8164                                         const analyze_scanf::ScanfSpecifier &FS,
8165                                         const char *startSpecifier,
8166                                         unsigned specifierLen) {
8167   const analyze_scanf::ScanfConversionSpecifier &CS =
8168     FS.getConversionSpecifier();
8169 
8170   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8171                                           getLocationOfByte(CS.getStart()),
8172                                           startSpecifier, specifierLen,
8173                                           CS.getStart(), CS.getLength());
8174 }
8175 
8176 bool CheckScanfHandler::HandleScanfSpecifier(
8177                                        const analyze_scanf::ScanfSpecifier &FS,
8178                                        const char *startSpecifier,
8179                                        unsigned specifierLen) {
8180   using namespace analyze_scanf;
8181   using namespace analyze_format_string;
8182 
8183   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8184 
8185   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8186   // be used to decide if we are using positional arguments consistently.
8187   if (FS.consumesDataArgument()) {
8188     if (atFirstArg) {
8189       atFirstArg = false;
8190       usesPositionalArgs = FS.usesPositionalArg();
8191     }
8192     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8193       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8194                                         startSpecifier, specifierLen);
8195       return false;
8196     }
8197   }
8198 
8199   // Check if the field with is non-zero.
8200   const OptionalAmount &Amt = FS.getFieldWidth();
8201   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8202     if (Amt.getConstantAmount() == 0) {
8203       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8204                                                    Amt.getConstantLength());
8205       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8206                            getLocationOfByte(Amt.getStart()),
8207                            /*IsStringLocation*/true, R,
8208                            FixItHint::CreateRemoval(R));
8209     }
8210   }
8211 
8212   if (!FS.consumesDataArgument()) {
8213     // FIXME: Technically specifying a precision or field width here
8214     // makes no sense.  Worth issuing a warning at some point.
8215     return true;
8216   }
8217 
8218   // Consume the argument.
8219   unsigned argIndex = FS.getArgIndex();
8220   if (argIndex < NumDataArgs) {
8221       // The check to see if the argIndex is valid will come later.
8222       // We set the bit here because we may exit early from this
8223       // function if we encounter some other error.
8224     CoveredArgs.set(argIndex);
8225   }
8226 
8227   // Check the length modifier is valid with the given conversion specifier.
8228   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8229                                  S.getLangOpts()))
8230     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8231                                 diag::warn_format_nonsensical_length);
8232   else if (!FS.hasStandardLengthModifier())
8233     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8234   else if (!FS.hasStandardLengthConversionCombination())
8235     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8236                                 diag::warn_format_non_standard_conversion_spec);
8237 
8238   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8239     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8240 
8241   // The remaining checks depend on the data arguments.
8242   if (HasVAListArg)
8243     return true;
8244 
8245   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8246     return false;
8247 
8248   // Check that the argument type matches the format specifier.
8249   const Expr *Ex = getDataArg(argIndex);
8250   if (!Ex)
8251     return true;
8252 
8253   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8254 
8255   if (!AT.isValid()) {
8256     return true;
8257   }
8258 
8259   analyze_format_string::ArgType::MatchKind Match =
8260       AT.matchesType(S.Context, Ex->getType());
8261   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8262   if (Match == analyze_format_string::ArgType::Match)
8263     return true;
8264 
8265   ScanfSpecifier fixedFS = FS;
8266   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8267                                  S.getLangOpts(), S.Context);
8268 
8269   unsigned Diag =
8270       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8271                : diag::warn_format_conversion_argument_type_mismatch;
8272 
8273   if (Success) {
8274     // Get the fix string from the fixed format specifier.
8275     SmallString<128> buf;
8276     llvm::raw_svector_ostream os(buf);
8277     fixedFS.toString(os);
8278 
8279     EmitFormatDiagnostic(
8280         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8281                       << Ex->getType() << false << Ex->getSourceRange(),
8282         Ex->getBeginLoc(),
8283         /*IsStringLocation*/ false,
8284         getSpecifierRange(startSpecifier, specifierLen),
8285         FixItHint::CreateReplacement(
8286             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8287   } else {
8288     EmitFormatDiagnostic(S.PDiag(Diag)
8289                              << AT.getRepresentativeTypeName(S.Context)
8290                              << Ex->getType() << false << Ex->getSourceRange(),
8291                          Ex->getBeginLoc(),
8292                          /*IsStringLocation*/ false,
8293                          getSpecifierRange(startSpecifier, specifierLen));
8294   }
8295 
8296   return true;
8297 }
8298 
8299 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8300                               const Expr *OrigFormatExpr,
8301                               ArrayRef<const Expr *> Args,
8302                               bool HasVAListArg, unsigned format_idx,
8303                               unsigned firstDataArg,
8304                               Sema::FormatStringType Type,
8305                               bool inFunctionCall,
8306                               Sema::VariadicCallType CallType,
8307                               llvm::SmallBitVector &CheckedVarArgs,
8308                               UncoveredArgHandler &UncoveredArg) {
8309   // CHECK: is the format string a wide literal?
8310   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8311     CheckFormatHandler::EmitFormatDiagnostic(
8312         S, inFunctionCall, Args[format_idx],
8313         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8314         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8315     return;
8316   }
8317 
8318   // Str - The format string.  NOTE: this is NOT null-terminated!
8319   StringRef StrRef = FExpr->getString();
8320   const char *Str = StrRef.data();
8321   // Account for cases where the string literal is truncated in a declaration.
8322   const ConstantArrayType *T =
8323     S.Context.getAsConstantArrayType(FExpr->getType());
8324   assert(T && "String literal not of constant array type!");
8325   size_t TypeSize = T->getSize().getZExtValue();
8326   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8327   const unsigned numDataArgs = Args.size() - firstDataArg;
8328 
8329   // Emit a warning if the string literal is truncated and does not contain an
8330   // embedded null character.
8331   if (TypeSize <= StrRef.size() &&
8332       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8333     CheckFormatHandler::EmitFormatDiagnostic(
8334         S, inFunctionCall, Args[format_idx],
8335         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8336         FExpr->getBeginLoc(),
8337         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8338     return;
8339   }
8340 
8341   // CHECK: empty format string?
8342   if (StrLen == 0 && numDataArgs > 0) {
8343     CheckFormatHandler::EmitFormatDiagnostic(
8344         S, inFunctionCall, Args[format_idx],
8345         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8346         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8347     return;
8348   }
8349 
8350   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8351       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8352       Type == Sema::FST_OSTrace) {
8353     CheckPrintfHandler H(
8354         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8355         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8356         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8357         CheckedVarArgs, UncoveredArg);
8358 
8359     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8360                                                   S.getLangOpts(),
8361                                                   S.Context.getTargetInfo(),
8362                                             Type == Sema::FST_FreeBSDKPrintf))
8363       H.DoneProcessing();
8364   } else if (Type == Sema::FST_Scanf) {
8365     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8366                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8367                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8368 
8369     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8370                                                  S.getLangOpts(),
8371                                                  S.Context.getTargetInfo()))
8372       H.DoneProcessing();
8373   } // TODO: handle other formats
8374 }
8375 
8376 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8377   // Str - The format string.  NOTE: this is NOT null-terminated!
8378   StringRef StrRef = FExpr->getString();
8379   const char *Str = StrRef.data();
8380   // Account for cases where the string literal is truncated in a declaration.
8381   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8382   assert(T && "String literal not of constant array type!");
8383   size_t TypeSize = T->getSize().getZExtValue();
8384   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8385   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8386                                                          getLangOpts(),
8387                                                          Context.getTargetInfo());
8388 }
8389 
8390 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8391 
8392 // Returns the related absolute value function that is larger, of 0 if one
8393 // does not exist.
8394 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8395   switch (AbsFunction) {
8396   default:
8397     return 0;
8398 
8399   case Builtin::BI__builtin_abs:
8400     return Builtin::BI__builtin_labs;
8401   case Builtin::BI__builtin_labs:
8402     return Builtin::BI__builtin_llabs;
8403   case Builtin::BI__builtin_llabs:
8404     return 0;
8405 
8406   case Builtin::BI__builtin_fabsf:
8407     return Builtin::BI__builtin_fabs;
8408   case Builtin::BI__builtin_fabs:
8409     return Builtin::BI__builtin_fabsl;
8410   case Builtin::BI__builtin_fabsl:
8411     return 0;
8412 
8413   case Builtin::BI__builtin_cabsf:
8414     return Builtin::BI__builtin_cabs;
8415   case Builtin::BI__builtin_cabs:
8416     return Builtin::BI__builtin_cabsl;
8417   case Builtin::BI__builtin_cabsl:
8418     return 0;
8419 
8420   case Builtin::BIabs:
8421     return Builtin::BIlabs;
8422   case Builtin::BIlabs:
8423     return Builtin::BIllabs;
8424   case Builtin::BIllabs:
8425     return 0;
8426 
8427   case Builtin::BIfabsf:
8428     return Builtin::BIfabs;
8429   case Builtin::BIfabs:
8430     return Builtin::BIfabsl;
8431   case Builtin::BIfabsl:
8432     return 0;
8433 
8434   case Builtin::BIcabsf:
8435    return Builtin::BIcabs;
8436   case Builtin::BIcabs:
8437     return Builtin::BIcabsl;
8438   case Builtin::BIcabsl:
8439     return 0;
8440   }
8441 }
8442 
8443 // Returns the argument type of the absolute value function.
8444 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8445                                              unsigned AbsType) {
8446   if (AbsType == 0)
8447     return QualType();
8448 
8449   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8450   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8451   if (Error != ASTContext::GE_None)
8452     return QualType();
8453 
8454   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8455   if (!FT)
8456     return QualType();
8457 
8458   if (FT->getNumParams() != 1)
8459     return QualType();
8460 
8461   return FT->getParamType(0);
8462 }
8463 
8464 // Returns the best absolute value function, or zero, based on type and
8465 // current absolute value function.
8466 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8467                                    unsigned AbsFunctionKind) {
8468   unsigned BestKind = 0;
8469   uint64_t ArgSize = Context.getTypeSize(ArgType);
8470   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8471        Kind = getLargerAbsoluteValueFunction(Kind)) {
8472     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8473     if (Context.getTypeSize(ParamType) >= ArgSize) {
8474       if (BestKind == 0)
8475         BestKind = Kind;
8476       else if (Context.hasSameType(ParamType, ArgType)) {
8477         BestKind = Kind;
8478         break;
8479       }
8480     }
8481   }
8482   return BestKind;
8483 }
8484 
8485 enum AbsoluteValueKind {
8486   AVK_Integer,
8487   AVK_Floating,
8488   AVK_Complex
8489 };
8490 
8491 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8492   if (T->isIntegralOrEnumerationType())
8493     return AVK_Integer;
8494   if (T->isRealFloatingType())
8495     return AVK_Floating;
8496   if (T->isAnyComplexType())
8497     return AVK_Complex;
8498 
8499   llvm_unreachable("Type not integer, floating, or complex");
8500 }
8501 
8502 // Changes the absolute value function to a different type.  Preserves whether
8503 // the function is a builtin.
8504 static unsigned changeAbsFunction(unsigned AbsKind,
8505                                   AbsoluteValueKind ValueKind) {
8506   switch (ValueKind) {
8507   case AVK_Integer:
8508     switch (AbsKind) {
8509     default:
8510       return 0;
8511     case Builtin::BI__builtin_fabsf:
8512     case Builtin::BI__builtin_fabs:
8513     case Builtin::BI__builtin_fabsl:
8514     case Builtin::BI__builtin_cabsf:
8515     case Builtin::BI__builtin_cabs:
8516     case Builtin::BI__builtin_cabsl:
8517       return Builtin::BI__builtin_abs;
8518     case Builtin::BIfabsf:
8519     case Builtin::BIfabs:
8520     case Builtin::BIfabsl:
8521     case Builtin::BIcabsf:
8522     case Builtin::BIcabs:
8523     case Builtin::BIcabsl:
8524       return Builtin::BIabs;
8525     }
8526   case AVK_Floating:
8527     switch (AbsKind) {
8528     default:
8529       return 0;
8530     case Builtin::BI__builtin_abs:
8531     case Builtin::BI__builtin_labs:
8532     case Builtin::BI__builtin_llabs:
8533     case Builtin::BI__builtin_cabsf:
8534     case Builtin::BI__builtin_cabs:
8535     case Builtin::BI__builtin_cabsl:
8536       return Builtin::BI__builtin_fabsf;
8537     case Builtin::BIabs:
8538     case Builtin::BIlabs:
8539     case Builtin::BIllabs:
8540     case Builtin::BIcabsf:
8541     case Builtin::BIcabs:
8542     case Builtin::BIcabsl:
8543       return Builtin::BIfabsf;
8544     }
8545   case AVK_Complex:
8546     switch (AbsKind) {
8547     default:
8548       return 0;
8549     case Builtin::BI__builtin_abs:
8550     case Builtin::BI__builtin_labs:
8551     case Builtin::BI__builtin_llabs:
8552     case Builtin::BI__builtin_fabsf:
8553     case Builtin::BI__builtin_fabs:
8554     case Builtin::BI__builtin_fabsl:
8555       return Builtin::BI__builtin_cabsf;
8556     case Builtin::BIabs:
8557     case Builtin::BIlabs:
8558     case Builtin::BIllabs:
8559     case Builtin::BIfabsf:
8560     case Builtin::BIfabs:
8561     case Builtin::BIfabsl:
8562       return Builtin::BIcabsf;
8563     }
8564   }
8565   llvm_unreachable("Unable to convert function");
8566 }
8567 
8568 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8569   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8570   if (!FnInfo)
8571     return 0;
8572 
8573   switch (FDecl->getBuiltinID()) {
8574   default:
8575     return 0;
8576   case Builtin::BI__builtin_abs:
8577   case Builtin::BI__builtin_fabs:
8578   case Builtin::BI__builtin_fabsf:
8579   case Builtin::BI__builtin_fabsl:
8580   case Builtin::BI__builtin_labs:
8581   case Builtin::BI__builtin_llabs:
8582   case Builtin::BI__builtin_cabs:
8583   case Builtin::BI__builtin_cabsf:
8584   case Builtin::BI__builtin_cabsl:
8585   case Builtin::BIabs:
8586   case Builtin::BIlabs:
8587   case Builtin::BIllabs:
8588   case Builtin::BIfabs:
8589   case Builtin::BIfabsf:
8590   case Builtin::BIfabsl:
8591   case Builtin::BIcabs:
8592   case Builtin::BIcabsf:
8593   case Builtin::BIcabsl:
8594     return FDecl->getBuiltinID();
8595   }
8596   llvm_unreachable("Unknown Builtin type");
8597 }
8598 
8599 // If the replacement is valid, emit a note with replacement function.
8600 // Additionally, suggest including the proper header if not already included.
8601 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8602                             unsigned AbsKind, QualType ArgType) {
8603   bool EmitHeaderHint = true;
8604   const char *HeaderName = nullptr;
8605   const char *FunctionName = nullptr;
8606   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8607     FunctionName = "std::abs";
8608     if (ArgType->isIntegralOrEnumerationType()) {
8609       HeaderName = "cstdlib";
8610     } else if (ArgType->isRealFloatingType()) {
8611       HeaderName = "cmath";
8612     } else {
8613       llvm_unreachable("Invalid Type");
8614     }
8615 
8616     // Lookup all std::abs
8617     if (NamespaceDecl *Std = S.getStdNamespace()) {
8618       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8619       R.suppressDiagnostics();
8620       S.LookupQualifiedName(R, Std);
8621 
8622       for (const auto *I : R) {
8623         const FunctionDecl *FDecl = nullptr;
8624         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8625           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8626         } else {
8627           FDecl = dyn_cast<FunctionDecl>(I);
8628         }
8629         if (!FDecl)
8630           continue;
8631 
8632         // Found std::abs(), check that they are the right ones.
8633         if (FDecl->getNumParams() != 1)
8634           continue;
8635 
8636         // Check that the parameter type can handle the argument.
8637         QualType ParamType = FDecl->getParamDecl(0)->getType();
8638         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8639             S.Context.getTypeSize(ArgType) <=
8640                 S.Context.getTypeSize(ParamType)) {
8641           // Found a function, don't need the header hint.
8642           EmitHeaderHint = false;
8643           break;
8644         }
8645       }
8646     }
8647   } else {
8648     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8649     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8650 
8651     if (HeaderName) {
8652       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8653       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8654       R.suppressDiagnostics();
8655       S.LookupName(R, S.getCurScope());
8656 
8657       if (R.isSingleResult()) {
8658         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8659         if (FD && FD->getBuiltinID() == AbsKind) {
8660           EmitHeaderHint = false;
8661         } else {
8662           return;
8663         }
8664       } else if (!R.empty()) {
8665         return;
8666       }
8667     }
8668   }
8669 
8670   S.Diag(Loc, diag::note_replace_abs_function)
8671       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8672 
8673   if (!HeaderName)
8674     return;
8675 
8676   if (!EmitHeaderHint)
8677     return;
8678 
8679   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8680                                                     << FunctionName;
8681 }
8682 
8683 template <std::size_t StrLen>
8684 static bool IsStdFunction(const FunctionDecl *FDecl,
8685                           const char (&Str)[StrLen]) {
8686   if (!FDecl)
8687     return false;
8688   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8689     return false;
8690   if (!FDecl->isInStdNamespace())
8691     return false;
8692 
8693   return true;
8694 }
8695 
8696 // Warn when using the wrong abs() function.
8697 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8698                                       const FunctionDecl *FDecl) {
8699   if (Call->getNumArgs() != 1)
8700     return;
8701 
8702   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8703   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8704   if (AbsKind == 0 && !IsStdAbs)
8705     return;
8706 
8707   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8708   QualType ParamType = Call->getArg(0)->getType();
8709 
8710   // Unsigned types cannot be negative.  Suggest removing the absolute value
8711   // function call.
8712   if (ArgType->isUnsignedIntegerType()) {
8713     const char *FunctionName =
8714         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8715     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8716     Diag(Call->getExprLoc(), diag::note_remove_abs)
8717         << FunctionName
8718         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8719     return;
8720   }
8721 
8722   // Taking the absolute value of a pointer is very suspicious, they probably
8723   // wanted to index into an array, dereference a pointer, call a function, etc.
8724   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8725     unsigned DiagType = 0;
8726     if (ArgType->isFunctionType())
8727       DiagType = 1;
8728     else if (ArgType->isArrayType())
8729       DiagType = 2;
8730 
8731     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8732     return;
8733   }
8734 
8735   // std::abs has overloads which prevent most of the absolute value problems
8736   // from occurring.
8737   if (IsStdAbs)
8738     return;
8739 
8740   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8741   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8742 
8743   // The argument and parameter are the same kind.  Check if they are the right
8744   // size.
8745   if (ArgValueKind == ParamValueKind) {
8746     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8747       return;
8748 
8749     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8750     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8751         << FDecl << ArgType << ParamType;
8752 
8753     if (NewAbsKind == 0)
8754       return;
8755 
8756     emitReplacement(*this, Call->getExprLoc(),
8757                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8758     return;
8759   }
8760 
8761   // ArgValueKind != ParamValueKind
8762   // The wrong type of absolute value function was used.  Attempt to find the
8763   // proper one.
8764   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8765   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8766   if (NewAbsKind == 0)
8767     return;
8768 
8769   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8770       << FDecl << ParamValueKind << ArgValueKind;
8771 
8772   emitReplacement(*this, Call->getExprLoc(),
8773                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8774 }
8775 
8776 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8777 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8778                                 const FunctionDecl *FDecl) {
8779   if (!Call || !FDecl) return;
8780 
8781   // Ignore template specializations and macros.
8782   if (inTemplateInstantiation()) return;
8783   if (Call->getExprLoc().isMacroID()) return;
8784 
8785   // Only care about the one template argument, two function parameter std::max
8786   if (Call->getNumArgs() != 2) return;
8787   if (!IsStdFunction(FDecl, "max")) return;
8788   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8789   if (!ArgList) return;
8790   if (ArgList->size() != 1) return;
8791 
8792   // Check that template type argument is unsigned integer.
8793   const auto& TA = ArgList->get(0);
8794   if (TA.getKind() != TemplateArgument::Type) return;
8795   QualType ArgType = TA.getAsType();
8796   if (!ArgType->isUnsignedIntegerType()) return;
8797 
8798   // See if either argument is a literal zero.
8799   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8800     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8801     if (!MTE) return false;
8802     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8803     if (!Num) return false;
8804     if (Num->getValue() != 0) return false;
8805     return true;
8806   };
8807 
8808   const Expr *FirstArg = Call->getArg(0);
8809   const Expr *SecondArg = Call->getArg(1);
8810   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8811   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8812 
8813   // Only warn when exactly one argument is zero.
8814   if (IsFirstArgZero == IsSecondArgZero) return;
8815 
8816   SourceRange FirstRange = FirstArg->getSourceRange();
8817   SourceRange SecondRange = SecondArg->getSourceRange();
8818 
8819   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8820 
8821   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8822       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8823 
8824   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8825   SourceRange RemovalRange;
8826   if (IsFirstArgZero) {
8827     RemovalRange = SourceRange(FirstRange.getBegin(),
8828                                SecondRange.getBegin().getLocWithOffset(-1));
8829   } else {
8830     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8831                                SecondRange.getEnd());
8832   }
8833 
8834   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8835         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8836         << FixItHint::CreateRemoval(RemovalRange);
8837 }
8838 
8839 //===--- CHECK: Standard memory functions ---------------------------------===//
8840 
8841 /// Takes the expression passed to the size_t parameter of functions
8842 /// such as memcmp, strncat, etc and warns if it's a comparison.
8843 ///
8844 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8845 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8846                                            IdentifierInfo *FnName,
8847                                            SourceLocation FnLoc,
8848                                            SourceLocation RParenLoc) {
8849   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8850   if (!Size)
8851     return false;
8852 
8853   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8854   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8855     return false;
8856 
8857   SourceRange SizeRange = Size->getSourceRange();
8858   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8859       << SizeRange << FnName;
8860   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8861       << FnName
8862       << FixItHint::CreateInsertion(
8863              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8864       << FixItHint::CreateRemoval(RParenLoc);
8865   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8866       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8867       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8868                                     ")");
8869 
8870   return true;
8871 }
8872 
8873 /// Determine whether the given type is or contains a dynamic class type
8874 /// (e.g., whether it has a vtable).
8875 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8876                                                      bool &IsContained) {
8877   // Look through array types while ignoring qualifiers.
8878   const Type *Ty = T->getBaseElementTypeUnsafe();
8879   IsContained = false;
8880 
8881   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8882   RD = RD ? RD->getDefinition() : nullptr;
8883   if (!RD || RD->isInvalidDecl())
8884     return nullptr;
8885 
8886   if (RD->isDynamicClass())
8887     return RD;
8888 
8889   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8890   // It's impossible for a class to transitively contain itself by value, so
8891   // infinite recursion is impossible.
8892   for (auto *FD : RD->fields()) {
8893     bool SubContained;
8894     if (const CXXRecordDecl *ContainedRD =
8895             getContainedDynamicClass(FD->getType(), SubContained)) {
8896       IsContained = true;
8897       return ContainedRD;
8898     }
8899   }
8900 
8901   return nullptr;
8902 }
8903 
8904 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8905   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8906     if (Unary->getKind() == UETT_SizeOf)
8907       return Unary;
8908   return nullptr;
8909 }
8910 
8911 /// If E is a sizeof expression, returns its argument expression,
8912 /// otherwise returns NULL.
8913 static const Expr *getSizeOfExprArg(const Expr *E) {
8914   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8915     if (!SizeOf->isArgumentType())
8916       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8917   return nullptr;
8918 }
8919 
8920 /// If E is a sizeof expression, returns its argument type.
8921 static QualType getSizeOfArgType(const Expr *E) {
8922   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8923     return SizeOf->getTypeOfArgument();
8924   return QualType();
8925 }
8926 
8927 namespace {
8928 
8929 struct SearchNonTrivialToInitializeField
8930     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8931   using Super =
8932       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8933 
8934   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8935 
8936   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8937                      SourceLocation SL) {
8938     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8939       asDerived().visitArray(PDIK, AT, SL);
8940       return;
8941     }
8942 
8943     Super::visitWithKind(PDIK, FT, SL);
8944   }
8945 
8946   void visitARCStrong(QualType FT, SourceLocation SL) {
8947     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8948   }
8949   void visitARCWeak(QualType FT, SourceLocation SL) {
8950     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8951   }
8952   void visitStruct(QualType FT, SourceLocation SL) {
8953     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8954       visit(FD->getType(), FD->getLocation());
8955   }
8956   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8957                   const ArrayType *AT, SourceLocation SL) {
8958     visit(getContext().getBaseElementType(AT), SL);
8959   }
8960   void visitTrivial(QualType FT, SourceLocation SL) {}
8961 
8962   static void diag(QualType RT, const Expr *E, Sema &S) {
8963     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8964   }
8965 
8966   ASTContext &getContext() { return S.getASTContext(); }
8967 
8968   const Expr *E;
8969   Sema &S;
8970 };
8971 
8972 struct SearchNonTrivialToCopyField
8973     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8974   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8975 
8976   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8977 
8978   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8979                      SourceLocation SL) {
8980     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8981       asDerived().visitArray(PCK, AT, SL);
8982       return;
8983     }
8984 
8985     Super::visitWithKind(PCK, FT, SL);
8986   }
8987 
8988   void visitARCStrong(QualType FT, SourceLocation SL) {
8989     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8990   }
8991   void visitARCWeak(QualType FT, SourceLocation SL) {
8992     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8993   }
8994   void visitStruct(QualType FT, SourceLocation SL) {
8995     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8996       visit(FD->getType(), FD->getLocation());
8997   }
8998   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8999                   SourceLocation SL) {
9000     visit(getContext().getBaseElementType(AT), SL);
9001   }
9002   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9003                 SourceLocation SL) {}
9004   void visitTrivial(QualType FT, SourceLocation SL) {}
9005   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9006 
9007   static void diag(QualType RT, const Expr *E, Sema &S) {
9008     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9009   }
9010 
9011   ASTContext &getContext() { return S.getASTContext(); }
9012 
9013   const Expr *E;
9014   Sema &S;
9015 };
9016 
9017 }
9018 
9019 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9020 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9021   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9022 
9023   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9024     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9025       return false;
9026 
9027     return doesExprLikelyComputeSize(BO->getLHS()) ||
9028            doesExprLikelyComputeSize(BO->getRHS());
9029   }
9030 
9031   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9032 }
9033 
9034 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9035 ///
9036 /// \code
9037 ///   #define MACRO 0
9038 ///   foo(MACRO);
9039 ///   foo(0);
9040 /// \endcode
9041 ///
9042 /// This should return true for the first call to foo, but not for the second
9043 /// (regardless of whether foo is a macro or function).
9044 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9045                                         SourceLocation CallLoc,
9046                                         SourceLocation ArgLoc) {
9047   if (!CallLoc.isMacroID())
9048     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9049 
9050   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9051          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9052 }
9053 
9054 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9055 /// last two arguments transposed.
9056 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9057   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9058     return;
9059 
9060   const Expr *SizeArg =
9061     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9062 
9063   auto isLiteralZero = [](const Expr *E) {
9064     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9065   };
9066 
9067   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9068   SourceLocation CallLoc = Call->getRParenLoc();
9069   SourceManager &SM = S.getSourceManager();
9070   if (isLiteralZero(SizeArg) &&
9071       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9072 
9073     SourceLocation DiagLoc = SizeArg->getExprLoc();
9074 
9075     // Some platforms #define bzero to __builtin_memset. See if this is the
9076     // case, and if so, emit a better diagnostic.
9077     if (BId == Builtin::BIbzero ||
9078         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9079                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9080       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9081       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9082     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9083       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9084       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9085     }
9086     return;
9087   }
9088 
9089   // If the second argument to a memset is a sizeof expression and the third
9090   // isn't, this is also likely an error. This should catch
9091   // 'memset(buf, sizeof(buf), 0xff)'.
9092   if (BId == Builtin::BImemset &&
9093       doesExprLikelyComputeSize(Call->getArg(1)) &&
9094       !doesExprLikelyComputeSize(Call->getArg(2))) {
9095     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9096     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9097     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9098     return;
9099   }
9100 }
9101 
9102 /// Check for dangerous or invalid arguments to memset().
9103 ///
9104 /// This issues warnings on known problematic, dangerous or unspecified
9105 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9106 /// function calls.
9107 ///
9108 /// \param Call The call expression to diagnose.
9109 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9110                                    unsigned BId,
9111                                    IdentifierInfo *FnName) {
9112   assert(BId != 0);
9113 
9114   // It is possible to have a non-standard definition of memset.  Validate
9115   // we have enough arguments, and if not, abort further checking.
9116   unsigned ExpectedNumArgs =
9117       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9118   if (Call->getNumArgs() < ExpectedNumArgs)
9119     return;
9120 
9121   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9122                       BId == Builtin::BIstrndup ? 1 : 2);
9123   unsigned LenArg =
9124       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9125   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9126 
9127   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9128                                      Call->getBeginLoc(), Call->getRParenLoc()))
9129     return;
9130 
9131   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9132   CheckMemaccessSize(*this, BId, Call);
9133 
9134   // We have special checking when the length is a sizeof expression.
9135   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9136   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9137   llvm::FoldingSetNodeID SizeOfArgID;
9138 
9139   // Although widely used, 'bzero' is not a standard function. Be more strict
9140   // with the argument types before allowing diagnostics and only allow the
9141   // form bzero(ptr, sizeof(...)).
9142   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9143   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9144     return;
9145 
9146   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9147     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9148     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9149 
9150     QualType DestTy = Dest->getType();
9151     QualType PointeeTy;
9152     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9153       PointeeTy = DestPtrTy->getPointeeType();
9154 
9155       // Never warn about void type pointers. This can be used to suppress
9156       // false positives.
9157       if (PointeeTy->isVoidType())
9158         continue;
9159 
9160       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9161       // actually comparing the expressions for equality. Because computing the
9162       // expression IDs can be expensive, we only do this if the diagnostic is
9163       // enabled.
9164       if (SizeOfArg &&
9165           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9166                            SizeOfArg->getExprLoc())) {
9167         // We only compute IDs for expressions if the warning is enabled, and
9168         // cache the sizeof arg's ID.
9169         if (SizeOfArgID == llvm::FoldingSetNodeID())
9170           SizeOfArg->Profile(SizeOfArgID, Context, true);
9171         llvm::FoldingSetNodeID DestID;
9172         Dest->Profile(DestID, Context, true);
9173         if (DestID == SizeOfArgID) {
9174           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9175           //       over sizeof(src) as well.
9176           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9177           StringRef ReadableName = FnName->getName();
9178 
9179           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9180             if (UnaryOp->getOpcode() == UO_AddrOf)
9181               ActionIdx = 1; // If its an address-of operator, just remove it.
9182           if (!PointeeTy->isIncompleteType() &&
9183               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9184             ActionIdx = 2; // If the pointee's size is sizeof(char),
9185                            // suggest an explicit length.
9186 
9187           // If the function is defined as a builtin macro, do not show macro
9188           // expansion.
9189           SourceLocation SL = SizeOfArg->getExprLoc();
9190           SourceRange DSR = Dest->getSourceRange();
9191           SourceRange SSR = SizeOfArg->getSourceRange();
9192           SourceManager &SM = getSourceManager();
9193 
9194           if (SM.isMacroArgExpansion(SL)) {
9195             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9196             SL = SM.getSpellingLoc(SL);
9197             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9198                              SM.getSpellingLoc(DSR.getEnd()));
9199             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9200                              SM.getSpellingLoc(SSR.getEnd()));
9201           }
9202 
9203           DiagRuntimeBehavior(SL, SizeOfArg,
9204                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9205                                 << ReadableName
9206                                 << PointeeTy
9207                                 << DestTy
9208                                 << DSR
9209                                 << SSR);
9210           DiagRuntimeBehavior(SL, SizeOfArg,
9211                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9212                                 << ActionIdx
9213                                 << SSR);
9214 
9215           break;
9216         }
9217       }
9218 
9219       // Also check for cases where the sizeof argument is the exact same
9220       // type as the memory argument, and where it points to a user-defined
9221       // record type.
9222       if (SizeOfArgTy != QualType()) {
9223         if (PointeeTy->isRecordType() &&
9224             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9225           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9226                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9227                                 << FnName << SizeOfArgTy << ArgIdx
9228                                 << PointeeTy << Dest->getSourceRange()
9229                                 << LenExpr->getSourceRange());
9230           break;
9231         }
9232       }
9233     } else if (DestTy->isArrayType()) {
9234       PointeeTy = DestTy;
9235     }
9236 
9237     if (PointeeTy == QualType())
9238       continue;
9239 
9240     // Always complain about dynamic classes.
9241     bool IsContained;
9242     if (const CXXRecordDecl *ContainedRD =
9243             getContainedDynamicClass(PointeeTy, IsContained)) {
9244 
9245       unsigned OperationType = 0;
9246       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9247       // "overwritten" if we're warning about the destination for any call
9248       // but memcmp; otherwise a verb appropriate to the call.
9249       if (ArgIdx != 0 || IsCmp) {
9250         if (BId == Builtin::BImemcpy)
9251           OperationType = 1;
9252         else if(BId == Builtin::BImemmove)
9253           OperationType = 2;
9254         else if (IsCmp)
9255           OperationType = 3;
9256       }
9257 
9258       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9259                           PDiag(diag::warn_dyn_class_memaccess)
9260                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9261                               << IsContained << ContainedRD << OperationType
9262                               << Call->getCallee()->getSourceRange());
9263     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9264              BId != Builtin::BImemset)
9265       DiagRuntimeBehavior(
9266         Dest->getExprLoc(), Dest,
9267         PDiag(diag::warn_arc_object_memaccess)
9268           << ArgIdx << FnName << PointeeTy
9269           << Call->getCallee()->getSourceRange());
9270     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9271       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9272           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9273         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9274                             PDiag(diag::warn_cstruct_memaccess)
9275                                 << ArgIdx << FnName << PointeeTy << 0);
9276         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9277       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9278                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9279         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9280                             PDiag(diag::warn_cstruct_memaccess)
9281                                 << ArgIdx << FnName << PointeeTy << 1);
9282         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9283       } else {
9284         continue;
9285       }
9286     } else
9287       continue;
9288 
9289     DiagRuntimeBehavior(
9290       Dest->getExprLoc(), Dest,
9291       PDiag(diag::note_bad_memaccess_silence)
9292         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9293     break;
9294   }
9295 }
9296 
9297 // A little helper routine: ignore addition and subtraction of integer literals.
9298 // This intentionally does not ignore all integer constant expressions because
9299 // we don't want to remove sizeof().
9300 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9301   Ex = Ex->IgnoreParenCasts();
9302 
9303   while (true) {
9304     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9305     if (!BO || !BO->isAdditiveOp())
9306       break;
9307 
9308     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9309     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9310 
9311     if (isa<IntegerLiteral>(RHS))
9312       Ex = LHS;
9313     else if (isa<IntegerLiteral>(LHS))
9314       Ex = RHS;
9315     else
9316       break;
9317   }
9318 
9319   return Ex;
9320 }
9321 
9322 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9323                                                       ASTContext &Context) {
9324   // Only handle constant-sized or VLAs, but not flexible members.
9325   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9326     // Only issue the FIXIT for arrays of size > 1.
9327     if (CAT->getSize().getSExtValue() <= 1)
9328       return false;
9329   } else if (!Ty->isVariableArrayType()) {
9330     return false;
9331   }
9332   return true;
9333 }
9334 
9335 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9336 // be the size of the source, instead of the destination.
9337 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9338                                     IdentifierInfo *FnName) {
9339 
9340   // Don't crash if the user has the wrong number of arguments
9341   unsigned NumArgs = Call->getNumArgs();
9342   if ((NumArgs != 3) && (NumArgs != 4))
9343     return;
9344 
9345   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9346   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9347   const Expr *CompareWithSrc = nullptr;
9348 
9349   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9350                                      Call->getBeginLoc(), Call->getRParenLoc()))
9351     return;
9352 
9353   // Look for 'strlcpy(dst, x, sizeof(x))'
9354   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9355     CompareWithSrc = Ex;
9356   else {
9357     // Look for 'strlcpy(dst, x, strlen(x))'
9358     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9359       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9360           SizeCall->getNumArgs() == 1)
9361         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9362     }
9363   }
9364 
9365   if (!CompareWithSrc)
9366     return;
9367 
9368   // Determine if the argument to sizeof/strlen is equal to the source
9369   // argument.  In principle there's all kinds of things you could do
9370   // here, for instance creating an == expression and evaluating it with
9371   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9372   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9373   if (!SrcArgDRE)
9374     return;
9375 
9376   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9377   if (!CompareWithSrcDRE ||
9378       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9379     return;
9380 
9381   const Expr *OriginalSizeArg = Call->getArg(2);
9382   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9383       << OriginalSizeArg->getSourceRange() << FnName;
9384 
9385   // Output a FIXIT hint if the destination is an array (rather than a
9386   // pointer to an array).  This could be enhanced to handle some
9387   // pointers if we know the actual size, like if DstArg is 'array+2'
9388   // we could say 'sizeof(array)-2'.
9389   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9390   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9391     return;
9392 
9393   SmallString<128> sizeString;
9394   llvm::raw_svector_ostream OS(sizeString);
9395   OS << "sizeof(";
9396   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9397   OS << ")";
9398 
9399   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9400       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9401                                       OS.str());
9402 }
9403 
9404 /// Check if two expressions refer to the same declaration.
9405 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9406   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9407     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9408       return D1->getDecl() == D2->getDecl();
9409   return false;
9410 }
9411 
9412 static const Expr *getStrlenExprArg(const Expr *E) {
9413   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9414     const FunctionDecl *FD = CE->getDirectCallee();
9415     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9416       return nullptr;
9417     return CE->getArg(0)->IgnoreParenCasts();
9418   }
9419   return nullptr;
9420 }
9421 
9422 // Warn on anti-patterns as the 'size' argument to strncat.
9423 // The correct size argument should look like following:
9424 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9425 void Sema::CheckStrncatArguments(const CallExpr *CE,
9426                                  IdentifierInfo *FnName) {
9427   // Don't crash if the user has the wrong number of arguments.
9428   if (CE->getNumArgs() < 3)
9429     return;
9430   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9431   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9432   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9433 
9434   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9435                                      CE->getRParenLoc()))
9436     return;
9437 
9438   // Identify common expressions, which are wrongly used as the size argument
9439   // to strncat and may lead to buffer overflows.
9440   unsigned PatternType = 0;
9441   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9442     // - sizeof(dst)
9443     if (referToTheSameDecl(SizeOfArg, DstArg))
9444       PatternType = 1;
9445     // - sizeof(src)
9446     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9447       PatternType = 2;
9448   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9449     if (BE->getOpcode() == BO_Sub) {
9450       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9451       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9452       // - sizeof(dst) - strlen(dst)
9453       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9454           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9455         PatternType = 1;
9456       // - sizeof(src) - (anything)
9457       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9458         PatternType = 2;
9459     }
9460   }
9461 
9462   if (PatternType == 0)
9463     return;
9464 
9465   // Generate the diagnostic.
9466   SourceLocation SL = LenArg->getBeginLoc();
9467   SourceRange SR = LenArg->getSourceRange();
9468   SourceManager &SM = getSourceManager();
9469 
9470   // If the function is defined as a builtin macro, do not show macro expansion.
9471   if (SM.isMacroArgExpansion(SL)) {
9472     SL = SM.getSpellingLoc(SL);
9473     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9474                      SM.getSpellingLoc(SR.getEnd()));
9475   }
9476 
9477   // Check if the destination is an array (rather than a pointer to an array).
9478   QualType DstTy = DstArg->getType();
9479   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9480                                                                     Context);
9481   if (!isKnownSizeArray) {
9482     if (PatternType == 1)
9483       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9484     else
9485       Diag(SL, diag::warn_strncat_src_size) << SR;
9486     return;
9487   }
9488 
9489   if (PatternType == 1)
9490     Diag(SL, diag::warn_strncat_large_size) << SR;
9491   else
9492     Diag(SL, diag::warn_strncat_src_size) << SR;
9493 
9494   SmallString<128> sizeString;
9495   llvm::raw_svector_ostream OS(sizeString);
9496   OS << "sizeof(";
9497   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9498   OS << ") - ";
9499   OS << "strlen(";
9500   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9501   OS << ") - 1";
9502 
9503   Diag(SL, diag::note_strncat_wrong_size)
9504     << FixItHint::CreateReplacement(SR, OS.str());
9505 }
9506 
9507 void
9508 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9509                          SourceLocation ReturnLoc,
9510                          bool isObjCMethod,
9511                          const AttrVec *Attrs,
9512                          const FunctionDecl *FD) {
9513   // Check if the return value is null but should not be.
9514   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9515        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9516       CheckNonNullExpr(*this, RetValExp))
9517     Diag(ReturnLoc, diag::warn_null_ret)
9518       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9519 
9520   // C++11 [basic.stc.dynamic.allocation]p4:
9521   //   If an allocation function declared with a non-throwing
9522   //   exception-specification fails to allocate storage, it shall return
9523   //   a null pointer. Any other allocation function that fails to allocate
9524   //   storage shall indicate failure only by throwing an exception [...]
9525   if (FD) {
9526     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9527     if (Op == OO_New || Op == OO_Array_New) {
9528       const FunctionProtoType *Proto
9529         = FD->getType()->castAs<FunctionProtoType>();
9530       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9531           CheckNonNullExpr(*this, RetValExp))
9532         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9533           << FD << getLangOpts().CPlusPlus11;
9534     }
9535   }
9536 }
9537 
9538 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9539 
9540 /// Check for comparisons of floating point operands using != and ==.
9541 /// Issue a warning if these are no self-comparisons, as they are not likely
9542 /// to do what the programmer intended.
9543 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9544   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9545   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9546 
9547   // Special case: check for x == x (which is OK).
9548   // Do not emit warnings for such cases.
9549   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9550     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9551       if (DRL->getDecl() == DRR->getDecl())
9552         return;
9553 
9554   // Special case: check for comparisons against literals that can be exactly
9555   //  represented by APFloat.  In such cases, do not emit a warning.  This
9556   //  is a heuristic: often comparison against such literals are used to
9557   //  detect if a value in a variable has not changed.  This clearly can
9558   //  lead to false negatives.
9559   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9560     if (FLL->isExact())
9561       return;
9562   } else
9563     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9564       if (FLR->isExact())
9565         return;
9566 
9567   // Check for comparisons with builtin types.
9568   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9569     if (CL->getBuiltinCallee())
9570       return;
9571 
9572   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9573     if (CR->getBuiltinCallee())
9574       return;
9575 
9576   // Emit the diagnostic.
9577   Diag(Loc, diag::warn_floatingpoint_eq)
9578     << LHS->getSourceRange() << RHS->getSourceRange();
9579 }
9580 
9581 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9582 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9583 
9584 namespace {
9585 
9586 /// Structure recording the 'active' range of an integer-valued
9587 /// expression.
9588 struct IntRange {
9589   /// The number of bits active in the int.
9590   unsigned Width;
9591 
9592   /// True if the int is known not to have negative values.
9593   bool NonNegative;
9594 
9595   IntRange(unsigned Width, bool NonNegative)
9596       : Width(Width), NonNegative(NonNegative) {}
9597 
9598   /// Returns the range of the bool type.
9599   static IntRange forBoolType() {
9600     return IntRange(1, true);
9601   }
9602 
9603   /// Returns the range of an opaque value of the given integral type.
9604   static IntRange forValueOfType(ASTContext &C, QualType T) {
9605     return forValueOfCanonicalType(C,
9606                           T->getCanonicalTypeInternal().getTypePtr());
9607   }
9608 
9609   /// Returns the range of an opaque value of a canonical integral type.
9610   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9611     assert(T->isCanonicalUnqualified());
9612 
9613     if (const VectorType *VT = dyn_cast<VectorType>(T))
9614       T = VT->getElementType().getTypePtr();
9615     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9616       T = CT->getElementType().getTypePtr();
9617     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9618       T = AT->getValueType().getTypePtr();
9619 
9620     if (!C.getLangOpts().CPlusPlus) {
9621       // For enum types in C code, use the underlying datatype.
9622       if (const EnumType *ET = dyn_cast<EnumType>(T))
9623         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9624     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9625       // For enum types in C++, use the known bit width of the enumerators.
9626       EnumDecl *Enum = ET->getDecl();
9627       // In C++11, enums can have a fixed underlying type. Use this type to
9628       // compute the range.
9629       if (Enum->isFixed()) {
9630         return IntRange(C.getIntWidth(QualType(T, 0)),
9631                         !ET->isSignedIntegerOrEnumerationType());
9632       }
9633 
9634       unsigned NumPositive = Enum->getNumPositiveBits();
9635       unsigned NumNegative = Enum->getNumNegativeBits();
9636 
9637       if (NumNegative == 0)
9638         return IntRange(NumPositive, true/*NonNegative*/);
9639       else
9640         return IntRange(std::max(NumPositive + 1, NumNegative),
9641                         false/*NonNegative*/);
9642     }
9643 
9644     const BuiltinType *BT = cast<BuiltinType>(T);
9645     assert(BT->isInteger());
9646 
9647     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9648   }
9649 
9650   /// Returns the "target" range of a canonical integral type, i.e.
9651   /// the range of values expressible in the type.
9652   ///
9653   /// This matches forValueOfCanonicalType except that enums have the
9654   /// full range of their type, not the range of their enumerators.
9655   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9656     assert(T->isCanonicalUnqualified());
9657 
9658     if (const VectorType *VT = dyn_cast<VectorType>(T))
9659       T = VT->getElementType().getTypePtr();
9660     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9661       T = CT->getElementType().getTypePtr();
9662     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9663       T = AT->getValueType().getTypePtr();
9664     if (const EnumType *ET = dyn_cast<EnumType>(T))
9665       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9666 
9667     const BuiltinType *BT = cast<BuiltinType>(T);
9668     assert(BT->isInteger());
9669 
9670     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9671   }
9672 
9673   /// Returns the supremum of two ranges: i.e. their conservative merge.
9674   static IntRange join(IntRange L, IntRange R) {
9675     return IntRange(std::max(L.Width, R.Width),
9676                     L.NonNegative && R.NonNegative);
9677   }
9678 
9679   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9680   static IntRange meet(IntRange L, IntRange R) {
9681     return IntRange(std::min(L.Width, R.Width),
9682                     L.NonNegative || R.NonNegative);
9683   }
9684 };
9685 
9686 } // namespace
9687 
9688 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9689                               unsigned MaxWidth) {
9690   if (value.isSigned() && value.isNegative())
9691     return IntRange(value.getMinSignedBits(), false);
9692 
9693   if (value.getBitWidth() > MaxWidth)
9694     value = value.trunc(MaxWidth);
9695 
9696   // isNonNegative() just checks the sign bit without considering
9697   // signedness.
9698   return IntRange(value.getActiveBits(), true);
9699 }
9700 
9701 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9702                               unsigned MaxWidth) {
9703   if (result.isInt())
9704     return GetValueRange(C, result.getInt(), MaxWidth);
9705 
9706   if (result.isVector()) {
9707     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9708     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9709       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9710       R = IntRange::join(R, El);
9711     }
9712     return R;
9713   }
9714 
9715   if (result.isComplexInt()) {
9716     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9717     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9718     return IntRange::join(R, I);
9719   }
9720 
9721   // This can happen with lossless casts to intptr_t of "based" lvalues.
9722   // Assume it might use arbitrary bits.
9723   // FIXME: The only reason we need to pass the type in here is to get
9724   // the sign right on this one case.  It would be nice if APValue
9725   // preserved this.
9726   assert(result.isLValue() || result.isAddrLabelDiff());
9727   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9728 }
9729 
9730 static QualType GetExprType(const Expr *E) {
9731   QualType Ty = E->getType();
9732   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9733     Ty = AtomicRHS->getValueType();
9734   return Ty;
9735 }
9736 
9737 /// Pseudo-evaluate the given integer expression, estimating the
9738 /// range of values it might take.
9739 ///
9740 /// \param MaxWidth - the width to which the value will be truncated
9741 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9742   E = E->IgnoreParens();
9743 
9744   // Try a full evaluation first.
9745   Expr::EvalResult result;
9746   if (E->EvaluateAsRValue(result, C))
9747     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9748 
9749   // I think we only want to look through implicit casts here; if the
9750   // user has an explicit widening cast, we should treat the value as
9751   // being of the new, wider type.
9752   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9753     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9754       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9755 
9756     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9757 
9758     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9759                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9760 
9761     // Assume that non-integer casts can span the full range of the type.
9762     if (!isIntegerCast)
9763       return OutputTypeRange;
9764 
9765     IntRange SubRange
9766       = GetExprRange(C, CE->getSubExpr(),
9767                      std::min(MaxWidth, OutputTypeRange.Width));
9768 
9769     // Bail out if the subexpr's range is as wide as the cast type.
9770     if (SubRange.Width >= OutputTypeRange.Width)
9771       return OutputTypeRange;
9772 
9773     // Otherwise, we take the smaller width, and we're non-negative if
9774     // either the output type or the subexpr is.
9775     return IntRange(SubRange.Width,
9776                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9777   }
9778 
9779   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9780     // If we can fold the condition, just take that operand.
9781     bool CondResult;
9782     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9783       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9784                                         : CO->getFalseExpr(),
9785                           MaxWidth);
9786 
9787     // Otherwise, conservatively merge.
9788     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9789     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9790     return IntRange::join(L, R);
9791   }
9792 
9793   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9794     switch (BO->getOpcode()) {
9795     case BO_Cmp:
9796       llvm_unreachable("builtin <=> should have class type");
9797 
9798     // Boolean-valued operations are single-bit and positive.
9799     case BO_LAnd:
9800     case BO_LOr:
9801     case BO_LT:
9802     case BO_GT:
9803     case BO_LE:
9804     case BO_GE:
9805     case BO_EQ:
9806     case BO_NE:
9807       return IntRange::forBoolType();
9808 
9809     // The type of the assignments is the type of the LHS, so the RHS
9810     // is not necessarily the same type.
9811     case BO_MulAssign:
9812     case BO_DivAssign:
9813     case BO_RemAssign:
9814     case BO_AddAssign:
9815     case BO_SubAssign:
9816     case BO_XorAssign:
9817     case BO_OrAssign:
9818       // TODO: bitfields?
9819       return IntRange::forValueOfType(C, GetExprType(E));
9820 
9821     // Simple assignments just pass through the RHS, which will have
9822     // been coerced to the LHS type.
9823     case BO_Assign:
9824       // TODO: bitfields?
9825       return GetExprRange(C, BO->getRHS(), MaxWidth);
9826 
9827     // Operations with opaque sources are black-listed.
9828     case BO_PtrMemD:
9829     case BO_PtrMemI:
9830       return IntRange::forValueOfType(C, GetExprType(E));
9831 
9832     // Bitwise-and uses the *infinum* of the two source ranges.
9833     case BO_And:
9834     case BO_AndAssign:
9835       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9836                             GetExprRange(C, BO->getRHS(), MaxWidth));
9837 
9838     // Left shift gets black-listed based on a judgement call.
9839     case BO_Shl:
9840       // ...except that we want to treat '1 << (blah)' as logically
9841       // positive.  It's an important idiom.
9842       if (IntegerLiteral *I
9843             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9844         if (I->getValue() == 1) {
9845           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9846           return IntRange(R.Width, /*NonNegative*/ true);
9847         }
9848       }
9849       LLVM_FALLTHROUGH;
9850 
9851     case BO_ShlAssign:
9852       return IntRange::forValueOfType(C, GetExprType(E));
9853 
9854     // Right shift by a constant can narrow its left argument.
9855     case BO_Shr:
9856     case BO_ShrAssign: {
9857       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9858 
9859       // If the shift amount is a positive constant, drop the width by
9860       // that much.
9861       llvm::APSInt shift;
9862       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9863           shift.isNonNegative()) {
9864         unsigned zext = shift.getZExtValue();
9865         if (zext >= L.Width)
9866           L.Width = (L.NonNegative ? 0 : 1);
9867         else
9868           L.Width -= zext;
9869       }
9870 
9871       return L;
9872     }
9873 
9874     // Comma acts as its right operand.
9875     case BO_Comma:
9876       return GetExprRange(C, BO->getRHS(), MaxWidth);
9877 
9878     // Black-list pointer subtractions.
9879     case BO_Sub:
9880       if (BO->getLHS()->getType()->isPointerType())
9881         return IntRange::forValueOfType(C, GetExprType(E));
9882       break;
9883 
9884     // The width of a division result is mostly determined by the size
9885     // of the LHS.
9886     case BO_Div: {
9887       // Don't 'pre-truncate' the operands.
9888       unsigned opWidth = C.getIntWidth(GetExprType(E));
9889       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9890 
9891       // If the divisor is constant, use that.
9892       llvm::APSInt divisor;
9893       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9894         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9895         if (log2 >= L.Width)
9896           L.Width = (L.NonNegative ? 0 : 1);
9897         else
9898           L.Width = std::min(L.Width - log2, MaxWidth);
9899         return L;
9900       }
9901 
9902       // Otherwise, just use the LHS's width.
9903       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9904       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9905     }
9906 
9907     // The result of a remainder can't be larger than the result of
9908     // either side.
9909     case BO_Rem: {
9910       // Don't 'pre-truncate' the operands.
9911       unsigned opWidth = C.getIntWidth(GetExprType(E));
9912       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9913       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9914 
9915       IntRange meet = IntRange::meet(L, R);
9916       meet.Width = std::min(meet.Width, MaxWidth);
9917       return meet;
9918     }
9919 
9920     // The default behavior is okay for these.
9921     case BO_Mul:
9922     case BO_Add:
9923     case BO_Xor:
9924     case BO_Or:
9925       break;
9926     }
9927 
9928     // The default case is to treat the operation as if it were closed
9929     // on the narrowest type that encompasses both operands.
9930     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9931     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9932     return IntRange::join(L, R);
9933   }
9934 
9935   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9936     switch (UO->getOpcode()) {
9937     // Boolean-valued operations are white-listed.
9938     case UO_LNot:
9939       return IntRange::forBoolType();
9940 
9941     // Operations with opaque sources are black-listed.
9942     case UO_Deref:
9943     case UO_AddrOf: // should be impossible
9944       return IntRange::forValueOfType(C, GetExprType(E));
9945 
9946     default:
9947       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9948     }
9949   }
9950 
9951   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9952     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9953 
9954   if (const auto *BitField = E->getSourceBitField())
9955     return IntRange(BitField->getBitWidthValue(C),
9956                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9957 
9958   return IntRange::forValueOfType(C, GetExprType(E));
9959 }
9960 
9961 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9962   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9963 }
9964 
9965 /// Checks whether the given value, which currently has the given
9966 /// source semantics, has the same value when coerced through the
9967 /// target semantics.
9968 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9969                                  const llvm::fltSemantics &Src,
9970                                  const llvm::fltSemantics &Tgt) {
9971   llvm::APFloat truncated = value;
9972 
9973   bool ignored;
9974   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9975   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9976 
9977   return truncated.bitwiseIsEqual(value);
9978 }
9979 
9980 /// Checks whether the given value, which currently has the given
9981 /// source semantics, has the same value when coerced through the
9982 /// target semantics.
9983 ///
9984 /// The value might be a vector of floats (or a complex number).
9985 static bool IsSameFloatAfterCast(const APValue &value,
9986                                  const llvm::fltSemantics &Src,
9987                                  const llvm::fltSemantics &Tgt) {
9988   if (value.isFloat())
9989     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9990 
9991   if (value.isVector()) {
9992     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9993       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9994         return false;
9995     return true;
9996   }
9997 
9998   assert(value.isComplexFloat());
9999   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10000           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10001 }
10002 
10003 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
10004 
10005 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10006   // Suppress cases where we are comparing against an enum constant.
10007   if (const DeclRefExpr *DR =
10008       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10009     if (isa<EnumConstantDecl>(DR->getDecl()))
10010       return true;
10011 
10012   // Suppress cases where the '0' value is expanded from a macro.
10013   if (E->getBeginLoc().isMacroID())
10014     return true;
10015 
10016   return false;
10017 }
10018 
10019 static bool isKnownToHaveUnsignedValue(Expr *E) {
10020   return E->getType()->isIntegerType() &&
10021          (!E->getType()->isSignedIntegerType() ||
10022           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10023 }
10024 
10025 namespace {
10026 /// The promoted range of values of a type. In general this has the
10027 /// following structure:
10028 ///
10029 ///     |-----------| . . . |-----------|
10030 ///     ^           ^       ^           ^
10031 ///    Min       HoleMin  HoleMax      Max
10032 ///
10033 /// ... where there is only a hole if a signed type is promoted to unsigned
10034 /// (in which case Min and Max are the smallest and largest representable
10035 /// values).
10036 struct PromotedRange {
10037   // Min, or HoleMax if there is a hole.
10038   llvm::APSInt PromotedMin;
10039   // Max, or HoleMin if there is a hole.
10040   llvm::APSInt PromotedMax;
10041 
10042   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10043     if (R.Width == 0)
10044       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10045     else if (R.Width >= BitWidth && !Unsigned) {
10046       // Promotion made the type *narrower*. This happens when promoting
10047       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10048       // Treat all values of 'signed int' as being in range for now.
10049       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10050       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10051     } else {
10052       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10053                         .extOrTrunc(BitWidth);
10054       PromotedMin.setIsUnsigned(Unsigned);
10055 
10056       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10057                         .extOrTrunc(BitWidth);
10058       PromotedMax.setIsUnsigned(Unsigned);
10059     }
10060   }
10061 
10062   // Determine whether this range is contiguous (has no hole).
10063   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10064 
10065   // Where a constant value is within the range.
10066   enum ComparisonResult {
10067     LT = 0x1,
10068     LE = 0x2,
10069     GT = 0x4,
10070     GE = 0x8,
10071     EQ = 0x10,
10072     NE = 0x20,
10073     InRangeFlag = 0x40,
10074 
10075     Less = LE | LT | NE,
10076     Min = LE | InRangeFlag,
10077     InRange = InRangeFlag,
10078     Max = GE | InRangeFlag,
10079     Greater = GE | GT | NE,
10080 
10081     OnlyValue = LE | GE | EQ | InRangeFlag,
10082     InHole = NE
10083   };
10084 
10085   ComparisonResult compare(const llvm::APSInt &Value) const {
10086     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10087            Value.isUnsigned() == PromotedMin.isUnsigned());
10088     if (!isContiguous()) {
10089       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10090       if (Value.isMinValue()) return Min;
10091       if (Value.isMaxValue()) return Max;
10092       if (Value >= PromotedMin) return InRange;
10093       if (Value <= PromotedMax) return InRange;
10094       return InHole;
10095     }
10096 
10097     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10098     case -1: return Less;
10099     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10100     case 1:
10101       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10102       case -1: return InRange;
10103       case 0: return Max;
10104       case 1: return Greater;
10105       }
10106     }
10107 
10108     llvm_unreachable("impossible compare result");
10109   }
10110 
10111   static llvm::Optional<StringRef>
10112   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10113     if (Op == BO_Cmp) {
10114       ComparisonResult LTFlag = LT, GTFlag = GT;
10115       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10116 
10117       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10118       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10119       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10120       return llvm::None;
10121     }
10122 
10123     ComparisonResult TrueFlag, FalseFlag;
10124     if (Op == BO_EQ) {
10125       TrueFlag = EQ;
10126       FalseFlag = NE;
10127     } else if (Op == BO_NE) {
10128       TrueFlag = NE;
10129       FalseFlag = EQ;
10130     } else {
10131       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10132         TrueFlag = LT;
10133         FalseFlag = GE;
10134       } else {
10135         TrueFlag = GT;
10136         FalseFlag = LE;
10137       }
10138       if (Op == BO_GE || Op == BO_LE)
10139         std::swap(TrueFlag, FalseFlag);
10140     }
10141     if (R & TrueFlag)
10142       return StringRef("true");
10143     if (R & FalseFlag)
10144       return StringRef("false");
10145     return llvm::None;
10146   }
10147 };
10148 }
10149 
10150 static bool HasEnumType(Expr *E) {
10151   // Strip off implicit integral promotions.
10152   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10153     if (ICE->getCastKind() != CK_IntegralCast &&
10154         ICE->getCastKind() != CK_NoOp)
10155       break;
10156     E = ICE->getSubExpr();
10157   }
10158 
10159   return E->getType()->isEnumeralType();
10160 }
10161 
10162 static int classifyConstantValue(Expr *Constant) {
10163   // The values of this enumeration are used in the diagnostics
10164   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10165   enum ConstantValueKind {
10166     Miscellaneous = 0,
10167     LiteralTrue,
10168     LiteralFalse
10169   };
10170   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10171     return BL->getValue() ? ConstantValueKind::LiteralTrue
10172                           : ConstantValueKind::LiteralFalse;
10173   return ConstantValueKind::Miscellaneous;
10174 }
10175 
10176 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10177                                         Expr *Constant, Expr *Other,
10178                                         const llvm::APSInt &Value,
10179                                         bool RhsConstant) {
10180   if (S.inTemplateInstantiation())
10181     return false;
10182 
10183   Expr *OriginalOther = Other;
10184 
10185   Constant = Constant->IgnoreParenImpCasts();
10186   Other = Other->IgnoreParenImpCasts();
10187 
10188   // Suppress warnings on tautological comparisons between values of the same
10189   // enumeration type. There are only two ways we could warn on this:
10190   //  - If the constant is outside the range of representable values of
10191   //    the enumeration. In such a case, we should warn about the cast
10192   //    to enumeration type, not about the comparison.
10193   //  - If the constant is the maximum / minimum in-range value. For an
10194   //    enumeratin type, such comparisons can be meaningful and useful.
10195   if (Constant->getType()->isEnumeralType() &&
10196       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10197     return false;
10198 
10199   // TODO: Investigate using GetExprRange() to get tighter bounds
10200   // on the bit ranges.
10201   QualType OtherT = Other->getType();
10202   if (const auto *AT = OtherT->getAs<AtomicType>())
10203     OtherT = AT->getValueType();
10204   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10205 
10206   // Whether we're treating Other as being a bool because of the form of
10207   // expression despite it having another type (typically 'int' in C).
10208   bool OtherIsBooleanDespiteType =
10209       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10210   if (OtherIsBooleanDespiteType)
10211     OtherRange = IntRange::forBoolType();
10212 
10213   // Determine the promoted range of the other type and see if a comparison of
10214   // the constant against that range is tautological.
10215   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10216                                    Value.isUnsigned());
10217   auto Cmp = OtherPromotedRange.compare(Value);
10218   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10219   if (!Result)
10220     return false;
10221 
10222   // Suppress the diagnostic for an in-range comparison if the constant comes
10223   // from a macro or enumerator. We don't want to diagnose
10224   //
10225   //   some_long_value <= INT_MAX
10226   //
10227   // when sizeof(int) == sizeof(long).
10228   bool InRange = Cmp & PromotedRange::InRangeFlag;
10229   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10230     return false;
10231 
10232   // If this is a comparison to an enum constant, include that
10233   // constant in the diagnostic.
10234   const EnumConstantDecl *ED = nullptr;
10235   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10236     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10237 
10238   // Should be enough for uint128 (39 decimal digits)
10239   SmallString<64> PrettySourceValue;
10240   llvm::raw_svector_ostream OS(PrettySourceValue);
10241   if (ED)
10242     OS << '\'' << *ED << "' (" << Value << ")";
10243   else
10244     OS << Value;
10245 
10246   // FIXME: We use a somewhat different formatting for the in-range cases and
10247   // cases involving boolean values for historical reasons. We should pick a
10248   // consistent way of presenting these diagnostics.
10249   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10250     S.DiagRuntimeBehavior(
10251       E->getOperatorLoc(), E,
10252       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10253                        : diag::warn_tautological_bool_compare)
10254           << OS.str() << classifyConstantValue(Constant)
10255           << OtherT << OtherIsBooleanDespiteType << *Result
10256           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10257   } else {
10258     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10259                         ? (HasEnumType(OriginalOther)
10260                                ? diag::warn_unsigned_enum_always_true_comparison
10261                                : diag::warn_unsigned_always_true_comparison)
10262                         : diag::warn_tautological_constant_compare;
10263 
10264     S.Diag(E->getOperatorLoc(), Diag)
10265         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10266         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10267   }
10268 
10269   return true;
10270 }
10271 
10272 /// Analyze the operands of the given comparison.  Implements the
10273 /// fallback case from AnalyzeComparison.
10274 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10275   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10276   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10277 }
10278 
10279 /// Implements -Wsign-compare.
10280 ///
10281 /// \param E the binary operator to check for warnings
10282 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10283   // The type the comparison is being performed in.
10284   QualType T = E->getLHS()->getType();
10285 
10286   // Only analyze comparison operators where both sides have been converted to
10287   // the same type.
10288   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10289     return AnalyzeImpConvsInComparison(S, E);
10290 
10291   // Don't analyze value-dependent comparisons directly.
10292   if (E->isValueDependent())
10293     return AnalyzeImpConvsInComparison(S, E);
10294 
10295   Expr *LHS = E->getLHS();
10296   Expr *RHS = E->getRHS();
10297 
10298   if (T->isIntegralType(S.Context)) {
10299     llvm::APSInt RHSValue;
10300     llvm::APSInt LHSValue;
10301 
10302     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10303     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10304 
10305     // We don't care about expressions whose result is a constant.
10306     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10307       return AnalyzeImpConvsInComparison(S, E);
10308 
10309     // We only care about expressions where just one side is literal
10310     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10311       // Is the constant on the RHS or LHS?
10312       const bool RhsConstant = IsRHSIntegralLiteral;
10313       Expr *Const = RhsConstant ? RHS : LHS;
10314       Expr *Other = RhsConstant ? LHS : RHS;
10315       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10316 
10317       // Check whether an integer constant comparison results in a value
10318       // of 'true' or 'false'.
10319       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10320         return AnalyzeImpConvsInComparison(S, E);
10321     }
10322   }
10323 
10324   if (!T->hasUnsignedIntegerRepresentation()) {
10325     // We don't do anything special if this isn't an unsigned integral
10326     // comparison:  we're only interested in integral comparisons, and
10327     // signed comparisons only happen in cases we don't care to warn about.
10328     return AnalyzeImpConvsInComparison(S, E);
10329   }
10330 
10331   LHS = LHS->IgnoreParenImpCasts();
10332   RHS = RHS->IgnoreParenImpCasts();
10333 
10334   if (!S.getLangOpts().CPlusPlus) {
10335     // Avoid warning about comparison of integers with different signs when
10336     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10337     // the type of `E`.
10338     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10339       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10340     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10341       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10342   }
10343 
10344   // Check to see if one of the (unmodified) operands is of different
10345   // signedness.
10346   Expr *signedOperand, *unsignedOperand;
10347   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10348     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10349            "unsigned comparison between two signed integer expressions?");
10350     signedOperand = LHS;
10351     unsignedOperand = RHS;
10352   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10353     signedOperand = RHS;
10354     unsignedOperand = LHS;
10355   } else {
10356     return AnalyzeImpConvsInComparison(S, E);
10357   }
10358 
10359   // Otherwise, calculate the effective range of the signed operand.
10360   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10361 
10362   // Go ahead and analyze implicit conversions in the operands.  Note
10363   // that we skip the implicit conversions on both sides.
10364   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10365   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10366 
10367   // If the signed range is non-negative, -Wsign-compare won't fire.
10368   if (signedRange.NonNegative)
10369     return;
10370 
10371   // For (in)equality comparisons, if the unsigned operand is a
10372   // constant which cannot collide with a overflowed signed operand,
10373   // then reinterpreting the signed operand as unsigned will not
10374   // change the result of the comparison.
10375   if (E->isEqualityOp()) {
10376     unsigned comparisonWidth = S.Context.getIntWidth(T);
10377     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10378 
10379     // We should never be unable to prove that the unsigned operand is
10380     // non-negative.
10381     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10382 
10383     if (unsignedRange.Width < comparisonWidth)
10384       return;
10385   }
10386 
10387   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10388     S.PDiag(diag::warn_mixed_sign_comparison)
10389       << LHS->getType() << RHS->getType()
10390       << LHS->getSourceRange() << RHS->getSourceRange());
10391 }
10392 
10393 /// Analyzes an attempt to assign the given value to a bitfield.
10394 ///
10395 /// Returns true if there was something fishy about the attempt.
10396 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10397                                       SourceLocation InitLoc) {
10398   assert(Bitfield->isBitField());
10399   if (Bitfield->isInvalidDecl())
10400     return false;
10401 
10402   // White-list bool bitfields.
10403   QualType BitfieldType = Bitfield->getType();
10404   if (BitfieldType->isBooleanType())
10405      return false;
10406 
10407   if (BitfieldType->isEnumeralType()) {
10408     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10409     // If the underlying enum type was not explicitly specified as an unsigned
10410     // type and the enum contain only positive values, MSVC++ will cause an
10411     // inconsistency by storing this as a signed type.
10412     if (S.getLangOpts().CPlusPlus11 &&
10413         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10414         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10415         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10416       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10417         << BitfieldEnumDecl->getNameAsString();
10418     }
10419   }
10420 
10421   if (Bitfield->getType()->isBooleanType())
10422     return false;
10423 
10424   // Ignore value- or type-dependent expressions.
10425   if (Bitfield->getBitWidth()->isValueDependent() ||
10426       Bitfield->getBitWidth()->isTypeDependent() ||
10427       Init->isValueDependent() ||
10428       Init->isTypeDependent())
10429     return false;
10430 
10431   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10432   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10433 
10434   Expr::EvalResult Result;
10435   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10436                                    Expr::SE_AllowSideEffects)) {
10437     // The RHS is not constant.  If the RHS has an enum type, make sure the
10438     // bitfield is wide enough to hold all the values of the enum without
10439     // truncation.
10440     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10441       EnumDecl *ED = EnumTy->getDecl();
10442       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10443 
10444       // Enum types are implicitly signed on Windows, so check if there are any
10445       // negative enumerators to see if the enum was intended to be signed or
10446       // not.
10447       bool SignedEnum = ED->getNumNegativeBits() > 0;
10448 
10449       // Check for surprising sign changes when assigning enum values to a
10450       // bitfield of different signedness.  If the bitfield is signed and we
10451       // have exactly the right number of bits to store this unsigned enum,
10452       // suggest changing the enum to an unsigned type. This typically happens
10453       // on Windows where unfixed enums always use an underlying type of 'int'.
10454       unsigned DiagID = 0;
10455       if (SignedEnum && !SignedBitfield) {
10456         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10457       } else if (SignedBitfield && !SignedEnum &&
10458                  ED->getNumPositiveBits() == FieldWidth) {
10459         DiagID = diag::warn_signed_bitfield_enum_conversion;
10460       }
10461 
10462       if (DiagID) {
10463         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10464         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10465         SourceRange TypeRange =
10466             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10467         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10468             << SignedEnum << TypeRange;
10469       }
10470 
10471       // Compute the required bitwidth. If the enum has negative values, we need
10472       // one more bit than the normal number of positive bits to represent the
10473       // sign bit.
10474       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10475                                                   ED->getNumNegativeBits())
10476                                        : ED->getNumPositiveBits();
10477 
10478       // Check the bitwidth.
10479       if (BitsNeeded > FieldWidth) {
10480         Expr *WidthExpr = Bitfield->getBitWidth();
10481         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10482             << Bitfield << ED;
10483         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10484             << BitsNeeded << ED << WidthExpr->getSourceRange();
10485       }
10486     }
10487 
10488     return false;
10489   }
10490 
10491   llvm::APSInt Value = Result.Val.getInt();
10492 
10493   unsigned OriginalWidth = Value.getBitWidth();
10494 
10495   if (!Value.isSigned() || Value.isNegative())
10496     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10497       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10498         OriginalWidth = Value.getMinSignedBits();
10499 
10500   if (OriginalWidth <= FieldWidth)
10501     return false;
10502 
10503   // Compute the value which the bitfield will contain.
10504   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10505   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10506 
10507   // Check whether the stored value is equal to the original value.
10508   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10509   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10510     return false;
10511 
10512   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10513   // therefore don't strictly fit into a signed bitfield of width 1.
10514   if (FieldWidth == 1 && Value == 1)
10515     return false;
10516 
10517   std::string PrettyValue = Value.toString(10);
10518   std::string PrettyTrunc = TruncatedValue.toString(10);
10519 
10520   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10521     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10522     << Init->getSourceRange();
10523 
10524   return true;
10525 }
10526 
10527 /// Analyze the given simple or compound assignment for warning-worthy
10528 /// operations.
10529 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10530   // Just recurse on the LHS.
10531   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10532 
10533   // We want to recurse on the RHS as normal unless we're assigning to
10534   // a bitfield.
10535   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10536     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10537                                   E->getOperatorLoc())) {
10538       // Recurse, ignoring any implicit conversions on the RHS.
10539       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10540                                         E->getOperatorLoc());
10541     }
10542   }
10543 
10544   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10545 
10546   // Diagnose implicitly sequentially-consistent atomic assignment.
10547   if (E->getLHS()->getType()->isAtomicType())
10548     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10549 }
10550 
10551 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10552 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10553                             SourceLocation CContext, unsigned diag,
10554                             bool pruneControlFlow = false) {
10555   if (pruneControlFlow) {
10556     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10557                           S.PDiag(diag)
10558                             << SourceType << T << E->getSourceRange()
10559                             << SourceRange(CContext));
10560     return;
10561   }
10562   S.Diag(E->getExprLoc(), diag)
10563     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10564 }
10565 
10566 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10567 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10568                             SourceLocation CContext,
10569                             unsigned diag, bool pruneControlFlow = false) {
10570   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10571 }
10572 
10573 /// Diagnose an implicit cast from a floating point value to an integer value.
10574 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10575                                     SourceLocation CContext) {
10576   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10577   const bool PruneWarnings = S.inTemplateInstantiation();
10578 
10579   Expr *InnerE = E->IgnoreParenImpCasts();
10580   // We also want to warn on, e.g., "int i = -1.234"
10581   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10582     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10583       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10584 
10585   const bool IsLiteral =
10586       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10587 
10588   llvm::APFloat Value(0.0);
10589   bool IsConstant =
10590     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10591   if (!IsConstant) {
10592     return DiagnoseImpCast(S, E, T, CContext,
10593                            diag::warn_impcast_float_integer, PruneWarnings);
10594   }
10595 
10596   bool isExact = false;
10597 
10598   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10599                             T->hasUnsignedIntegerRepresentation());
10600   llvm::APFloat::opStatus Result = Value.convertToInteger(
10601       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10602 
10603   if (Result == llvm::APFloat::opOK && isExact) {
10604     if (IsLiteral) return;
10605     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10606                            PruneWarnings);
10607   }
10608 
10609   // Conversion of a floating-point value to a non-bool integer where the
10610   // integral part cannot be represented by the integer type is undefined.
10611   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10612     return DiagnoseImpCast(
10613         S, E, T, CContext,
10614         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10615                   : diag::warn_impcast_float_to_integer_out_of_range,
10616         PruneWarnings);
10617 
10618   unsigned DiagID = 0;
10619   if (IsLiteral) {
10620     // Warn on floating point literal to integer.
10621     DiagID = diag::warn_impcast_literal_float_to_integer;
10622   } else if (IntegerValue == 0) {
10623     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10624       return DiagnoseImpCast(S, E, T, CContext,
10625                              diag::warn_impcast_float_integer, PruneWarnings);
10626     }
10627     // Warn on non-zero to zero conversion.
10628     DiagID = diag::warn_impcast_float_to_integer_zero;
10629   } else {
10630     if (IntegerValue.isUnsigned()) {
10631       if (!IntegerValue.isMaxValue()) {
10632         return DiagnoseImpCast(S, E, T, CContext,
10633                                diag::warn_impcast_float_integer, PruneWarnings);
10634       }
10635     } else {  // IntegerValue.isSigned()
10636       if (!IntegerValue.isMaxSignedValue() &&
10637           !IntegerValue.isMinSignedValue()) {
10638         return DiagnoseImpCast(S, E, T, CContext,
10639                                diag::warn_impcast_float_integer, PruneWarnings);
10640       }
10641     }
10642     // Warn on evaluatable floating point expression to integer conversion.
10643     DiagID = diag::warn_impcast_float_to_integer;
10644   }
10645 
10646   // FIXME: Force the precision of the source value down so we don't print
10647   // digits which are usually useless (we don't really care here if we
10648   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10649   // would automatically print the shortest representation, but it's a bit
10650   // tricky to implement.
10651   SmallString<16> PrettySourceValue;
10652   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10653   precision = (precision * 59 + 195) / 196;
10654   Value.toString(PrettySourceValue, precision);
10655 
10656   SmallString<16> PrettyTargetValue;
10657   if (IsBool)
10658     PrettyTargetValue = Value.isZero() ? "false" : "true";
10659   else
10660     IntegerValue.toString(PrettyTargetValue);
10661 
10662   if (PruneWarnings) {
10663     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10664                           S.PDiag(DiagID)
10665                               << E->getType() << T.getUnqualifiedType()
10666                               << PrettySourceValue << PrettyTargetValue
10667                               << E->getSourceRange() << SourceRange(CContext));
10668   } else {
10669     S.Diag(E->getExprLoc(), DiagID)
10670         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10671         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10672   }
10673 }
10674 
10675 /// Analyze the given compound assignment for the possible losing of
10676 /// floating-point precision.
10677 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10678   assert(isa<CompoundAssignOperator>(E) &&
10679          "Must be compound assignment operation");
10680   // Recurse on the LHS and RHS in here
10681   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10682   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10683 
10684   if (E->getLHS()->getType()->isAtomicType())
10685     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10686 
10687   // Now check the outermost expression
10688   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10689   const auto *RBT = cast<CompoundAssignOperator>(E)
10690                         ->getComputationResultType()
10691                         ->getAs<BuiltinType>();
10692 
10693   // The below checks assume source is floating point.
10694   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10695 
10696   // If source is floating point but target is an integer.
10697   if (ResultBT->isInteger())
10698     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10699                            E->getExprLoc(), diag::warn_impcast_float_integer);
10700 
10701   if (!ResultBT->isFloatingPoint())
10702     return;
10703 
10704   // If both source and target are floating points, warn about losing precision.
10705   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10706       QualType(ResultBT, 0), QualType(RBT, 0));
10707   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10708     // warn about dropping FP rank.
10709     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10710                     diag::warn_impcast_float_result_precision);
10711 }
10712 
10713 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10714                                       IntRange Range) {
10715   if (!Range.Width) return "0";
10716 
10717   llvm::APSInt ValueInRange = Value;
10718   ValueInRange.setIsSigned(!Range.NonNegative);
10719   ValueInRange = ValueInRange.trunc(Range.Width);
10720   return ValueInRange.toString(10);
10721 }
10722 
10723 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10724   if (!isa<ImplicitCastExpr>(Ex))
10725     return false;
10726 
10727   Expr *InnerE = Ex->IgnoreParenImpCasts();
10728   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10729   const Type *Source =
10730     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10731   if (Target->isDependentType())
10732     return false;
10733 
10734   const BuiltinType *FloatCandidateBT =
10735     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10736   const Type *BoolCandidateType = ToBool ? Target : Source;
10737 
10738   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10739           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10740 }
10741 
10742 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10743                                              SourceLocation CC) {
10744   unsigned NumArgs = TheCall->getNumArgs();
10745   for (unsigned i = 0; i < NumArgs; ++i) {
10746     Expr *CurrA = TheCall->getArg(i);
10747     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10748       continue;
10749 
10750     bool IsSwapped = ((i > 0) &&
10751         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10752     IsSwapped |= ((i < (NumArgs - 1)) &&
10753         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10754     if (IsSwapped) {
10755       // Warn on this floating-point to bool conversion.
10756       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10757                       CurrA->getType(), CC,
10758                       diag::warn_impcast_floating_point_to_bool);
10759     }
10760   }
10761 }
10762 
10763 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10764                                    SourceLocation CC) {
10765   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10766                         E->getExprLoc()))
10767     return;
10768 
10769   // Don't warn on functions which have return type nullptr_t.
10770   if (isa<CallExpr>(E))
10771     return;
10772 
10773   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10774   const Expr::NullPointerConstantKind NullKind =
10775       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10776   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10777     return;
10778 
10779   // Return if target type is a safe conversion.
10780   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10781       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10782     return;
10783 
10784   SourceLocation Loc = E->getSourceRange().getBegin();
10785 
10786   // Venture through the macro stacks to get to the source of macro arguments.
10787   // The new location is a better location than the complete location that was
10788   // passed in.
10789   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10790   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10791 
10792   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10793   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10794     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10795         Loc, S.SourceMgr, S.getLangOpts());
10796     if (MacroName == "NULL")
10797       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10798   }
10799 
10800   // Only warn if the null and context location are in the same macro expansion.
10801   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10802     return;
10803 
10804   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10805       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10806       << FixItHint::CreateReplacement(Loc,
10807                                       S.getFixItZeroLiteralForType(T, Loc));
10808 }
10809 
10810 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10811                                   ObjCArrayLiteral *ArrayLiteral);
10812 
10813 static void
10814 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10815                            ObjCDictionaryLiteral *DictionaryLiteral);
10816 
10817 /// Check a single element within a collection literal against the
10818 /// target element type.
10819 static void checkObjCCollectionLiteralElement(Sema &S,
10820                                               QualType TargetElementType,
10821                                               Expr *Element,
10822                                               unsigned ElementKind) {
10823   // Skip a bitcast to 'id' or qualified 'id'.
10824   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10825     if (ICE->getCastKind() == CK_BitCast &&
10826         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10827       Element = ICE->getSubExpr();
10828   }
10829 
10830   QualType ElementType = Element->getType();
10831   ExprResult ElementResult(Element);
10832   if (ElementType->getAs<ObjCObjectPointerType>() &&
10833       S.CheckSingleAssignmentConstraints(TargetElementType,
10834                                          ElementResult,
10835                                          false, false)
10836         != Sema::Compatible) {
10837     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10838         << ElementType << ElementKind << TargetElementType
10839         << Element->getSourceRange();
10840   }
10841 
10842   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10843     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10844   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10845     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10846 }
10847 
10848 /// Check an Objective-C array literal being converted to the given
10849 /// target type.
10850 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10851                                   ObjCArrayLiteral *ArrayLiteral) {
10852   if (!S.NSArrayDecl)
10853     return;
10854 
10855   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10856   if (!TargetObjCPtr)
10857     return;
10858 
10859   if (TargetObjCPtr->isUnspecialized() ||
10860       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10861         != S.NSArrayDecl->getCanonicalDecl())
10862     return;
10863 
10864   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10865   if (TypeArgs.size() != 1)
10866     return;
10867 
10868   QualType TargetElementType = TypeArgs[0];
10869   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10870     checkObjCCollectionLiteralElement(S, TargetElementType,
10871                                       ArrayLiteral->getElement(I),
10872                                       0);
10873   }
10874 }
10875 
10876 /// Check an Objective-C dictionary literal being converted to the given
10877 /// target type.
10878 static void
10879 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10880                            ObjCDictionaryLiteral *DictionaryLiteral) {
10881   if (!S.NSDictionaryDecl)
10882     return;
10883 
10884   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10885   if (!TargetObjCPtr)
10886     return;
10887 
10888   if (TargetObjCPtr->isUnspecialized() ||
10889       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10890         != S.NSDictionaryDecl->getCanonicalDecl())
10891     return;
10892 
10893   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10894   if (TypeArgs.size() != 2)
10895     return;
10896 
10897   QualType TargetKeyType = TypeArgs[0];
10898   QualType TargetObjectType = TypeArgs[1];
10899   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10900     auto Element = DictionaryLiteral->getKeyValueElement(I);
10901     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10902     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10903   }
10904 }
10905 
10906 // Helper function to filter out cases for constant width constant conversion.
10907 // Don't warn on char array initialization or for non-decimal values.
10908 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10909                                           SourceLocation CC) {
10910   // If initializing from a constant, and the constant starts with '0',
10911   // then it is a binary, octal, or hexadecimal.  Allow these constants
10912   // to fill all the bits, even if there is a sign change.
10913   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10914     const char FirstLiteralCharacter =
10915         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10916     if (FirstLiteralCharacter == '0')
10917       return false;
10918   }
10919 
10920   // If the CC location points to a '{', and the type is char, then assume
10921   // assume it is an array initialization.
10922   if (CC.isValid() && T->isCharType()) {
10923     const char FirstContextCharacter =
10924         S.getSourceManager().getCharacterData(CC)[0];
10925     if (FirstContextCharacter == '{')
10926       return false;
10927   }
10928 
10929   return true;
10930 }
10931 
10932 static void
10933 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10934                         bool *ICContext = nullptr) {
10935   if (E->isTypeDependent() || E->isValueDependent()) return;
10936 
10937   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10938   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10939   if (Source == Target) return;
10940   if (Target->isDependentType()) return;
10941 
10942   // If the conversion context location is invalid don't complain. We also
10943   // don't want to emit a warning if the issue occurs from the expansion of
10944   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10945   // delay this check as long as possible. Once we detect we are in that
10946   // scenario, we just return.
10947   if (CC.isInvalid())
10948     return;
10949 
10950   if (Source->isAtomicType())
10951     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10952 
10953   // Diagnose implicit casts to bool.
10954   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10955     if (isa<StringLiteral>(E))
10956       // Warn on string literal to bool.  Checks for string literals in logical
10957       // and expressions, for instance, assert(0 && "error here"), are
10958       // prevented by a check in AnalyzeImplicitConversions().
10959       return DiagnoseImpCast(S, E, T, CC,
10960                              diag::warn_impcast_string_literal_to_bool);
10961     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10962         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10963       // This covers the literal expressions that evaluate to Objective-C
10964       // objects.
10965       return DiagnoseImpCast(S, E, T, CC,
10966                              diag::warn_impcast_objective_c_literal_to_bool);
10967     }
10968     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10969       // Warn on pointer to bool conversion that is always true.
10970       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10971                                      SourceRange(CC));
10972     }
10973   }
10974 
10975   // Check implicit casts from Objective-C collection literals to specialized
10976   // collection types, e.g., NSArray<NSString *> *.
10977   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10978     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10979   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10980     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10981 
10982   // Strip vector types.
10983   if (isa<VectorType>(Source)) {
10984     if (!isa<VectorType>(Target)) {
10985       if (S.SourceMgr.isInSystemMacro(CC))
10986         return;
10987       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10988     }
10989 
10990     // If the vector cast is cast between two vectors of the same size, it is
10991     // a bitcast, not a conversion.
10992     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10993       return;
10994 
10995     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10996     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10997   }
10998   if (auto VecTy = dyn_cast<VectorType>(Target))
10999     Target = VecTy->getElementType().getTypePtr();
11000 
11001   // Strip complex types.
11002   if (isa<ComplexType>(Source)) {
11003     if (!isa<ComplexType>(Target)) {
11004       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11005         return;
11006 
11007       return DiagnoseImpCast(S, E, T, CC,
11008                              S.getLangOpts().CPlusPlus
11009                                  ? diag::err_impcast_complex_scalar
11010                                  : diag::warn_impcast_complex_scalar);
11011     }
11012 
11013     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11014     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11015   }
11016 
11017   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11018   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11019 
11020   // If the source is floating point...
11021   if (SourceBT && SourceBT->isFloatingPoint()) {
11022     // ...and the target is floating point...
11023     if (TargetBT && TargetBT->isFloatingPoint()) {
11024       // ...then warn if we're dropping FP rank.
11025 
11026       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11027           QualType(SourceBT, 0), QualType(TargetBT, 0));
11028       if (Order > 0) {
11029         // Don't warn about float constants that are precisely
11030         // representable in the target type.
11031         Expr::EvalResult result;
11032         if (E->EvaluateAsRValue(result, S.Context)) {
11033           // Value might be a float, a float vector, or a float complex.
11034           if (IsSameFloatAfterCast(result.Val,
11035                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11036                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11037             return;
11038         }
11039 
11040         if (S.SourceMgr.isInSystemMacro(CC))
11041           return;
11042 
11043         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11044       }
11045       // ... or possibly if we're increasing rank, too
11046       else if (Order < 0) {
11047         if (S.SourceMgr.isInSystemMacro(CC))
11048           return;
11049 
11050         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11051       }
11052       return;
11053     }
11054 
11055     // If the target is integral, always warn.
11056     if (TargetBT && TargetBT->isInteger()) {
11057       if (S.SourceMgr.isInSystemMacro(CC))
11058         return;
11059 
11060       DiagnoseFloatingImpCast(S, E, T, CC);
11061     }
11062 
11063     // Detect the case where a call result is converted from floating-point to
11064     // to bool, and the final argument to the call is converted from bool, to
11065     // discover this typo:
11066     //
11067     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11068     //
11069     // FIXME: This is an incredibly special case; is there some more general
11070     // way to detect this class of misplaced-parentheses bug?
11071     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11072       // Check last argument of function call to see if it is an
11073       // implicit cast from a type matching the type the result
11074       // is being cast to.
11075       CallExpr *CEx = cast<CallExpr>(E);
11076       if (unsigned NumArgs = CEx->getNumArgs()) {
11077         Expr *LastA = CEx->getArg(NumArgs - 1);
11078         Expr *InnerE = LastA->IgnoreParenImpCasts();
11079         if (isa<ImplicitCastExpr>(LastA) &&
11080             InnerE->getType()->isBooleanType()) {
11081           // Warn on this floating-point to bool conversion
11082           DiagnoseImpCast(S, E, T, CC,
11083                           diag::warn_impcast_floating_point_to_bool);
11084         }
11085       }
11086     }
11087     return;
11088   }
11089 
11090   // Valid casts involving fixed point types should be accounted for here.
11091   if (Source->isFixedPointType()) {
11092     if (Target->isUnsaturatedFixedPointType()) {
11093       Expr::EvalResult Result;
11094       if (E->EvaluateAsFixedPoint(Result, S.Context,
11095                                   Expr::SE_AllowSideEffects)) {
11096         APFixedPoint Value = Result.Val.getFixedPoint();
11097         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11098         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11099         if (Value > MaxVal || Value < MinVal) {
11100           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11101                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11102                                     << Value.toString() << T
11103                                     << E->getSourceRange()
11104                                     << clang::SourceRange(CC));
11105           return;
11106         }
11107       }
11108     } else if (Target->isIntegerType()) {
11109       Expr::EvalResult Result;
11110       if (E->EvaluateAsFixedPoint(Result, S.Context,
11111                                   Expr::SE_AllowSideEffects)) {
11112         APFixedPoint FXResult = Result.Val.getFixedPoint();
11113 
11114         bool Overflowed;
11115         llvm::APSInt IntResult = FXResult.convertToInt(
11116             S.Context.getIntWidth(T),
11117             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11118 
11119         if (Overflowed) {
11120           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11121                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11122                                     << FXResult.toString() << T
11123                                     << E->getSourceRange()
11124                                     << clang::SourceRange(CC));
11125           return;
11126         }
11127       }
11128     }
11129   } else if (Target->isUnsaturatedFixedPointType()) {
11130     if (Source->isIntegerType()) {
11131       Expr::EvalResult Result;
11132       if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11133         llvm::APSInt Value = Result.Val.getInt();
11134 
11135         bool Overflowed;
11136         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11137             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11138 
11139         if (Overflowed) {
11140           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11141                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11142                                     << Value.toString(/*radix=*/10) << T
11143                                     << E->getSourceRange()
11144                                     << clang::SourceRange(CC));
11145           return;
11146         }
11147       }
11148     }
11149   }
11150 
11151   DiagnoseNullConversion(S, E, T, CC);
11152 
11153   S.DiscardMisalignedMemberAddress(Target, E);
11154 
11155   if (!Source->isIntegerType() || !Target->isIntegerType())
11156     return;
11157 
11158   // TODO: remove this early return once the false positives for constant->bool
11159   // in templates, macros, etc, are reduced or removed.
11160   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11161     return;
11162 
11163   IntRange SourceRange = GetExprRange(S.Context, E);
11164   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11165 
11166   if (SourceRange.Width > TargetRange.Width) {
11167     // If the source is a constant, use a default-on diagnostic.
11168     // TODO: this should happen for bitfield stores, too.
11169     Expr::EvalResult Result;
11170     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11171       llvm::APSInt Value(32);
11172       Value = Result.Val.getInt();
11173 
11174       if (S.SourceMgr.isInSystemMacro(CC))
11175         return;
11176 
11177       std::string PrettySourceValue = Value.toString(10);
11178       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11179 
11180       S.DiagRuntimeBehavior(E->getExprLoc(), E,
11181         S.PDiag(diag::warn_impcast_integer_precision_constant)
11182             << PrettySourceValue << PrettyTargetValue
11183             << E->getType() << T << E->getSourceRange()
11184             << clang::SourceRange(CC));
11185       return;
11186     }
11187 
11188     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11189     if (S.SourceMgr.isInSystemMacro(CC))
11190       return;
11191 
11192     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11193       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11194                              /* pruneControlFlow */ true);
11195     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11196   }
11197 
11198   if (TargetRange.Width > SourceRange.Width) {
11199     if (auto *UO = dyn_cast<UnaryOperator>(E))
11200       if (UO->getOpcode() == UO_Minus)
11201         if (Source->isUnsignedIntegerType()) {
11202           if (Target->isUnsignedIntegerType())
11203             return DiagnoseImpCast(S, E, T, CC,
11204                                    diag::warn_impcast_high_order_zero_bits);
11205           if (Target->isSignedIntegerType())
11206             return DiagnoseImpCast(S, E, T, CC,
11207                                    diag::warn_impcast_nonnegative_result);
11208         }
11209   }
11210 
11211   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11212       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11213     // Warn when doing a signed to signed conversion, warn if the positive
11214     // source value is exactly the width of the target type, which will
11215     // cause a negative value to be stored.
11216 
11217     Expr::EvalResult Result;
11218     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11219         !S.SourceMgr.isInSystemMacro(CC)) {
11220       llvm::APSInt Value = Result.Val.getInt();
11221       if (isSameWidthConstantConversion(S, E, T, CC)) {
11222         std::string PrettySourceValue = Value.toString(10);
11223         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11224 
11225         S.DiagRuntimeBehavior(
11226             E->getExprLoc(), E,
11227             S.PDiag(diag::warn_impcast_integer_precision_constant)
11228                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11229                 << E->getSourceRange() << clang::SourceRange(CC));
11230         return;
11231       }
11232     }
11233 
11234     // Fall through for non-constants to give a sign conversion warning.
11235   }
11236 
11237   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11238       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11239        SourceRange.Width == TargetRange.Width)) {
11240     if (S.SourceMgr.isInSystemMacro(CC))
11241       return;
11242 
11243     unsigned DiagID = diag::warn_impcast_integer_sign;
11244 
11245     // Traditionally, gcc has warned about this under -Wsign-compare.
11246     // We also want to warn about it in -Wconversion.
11247     // So if -Wconversion is off, use a completely identical diagnostic
11248     // in the sign-compare group.
11249     // The conditional-checking code will
11250     if (ICContext) {
11251       DiagID = diag::warn_impcast_integer_sign_conditional;
11252       *ICContext = true;
11253     }
11254 
11255     return DiagnoseImpCast(S, E, T, CC, DiagID);
11256   }
11257 
11258   // Diagnose conversions between different enumeration types.
11259   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11260   // type, to give us better diagnostics.
11261   QualType SourceType = E->getType();
11262   if (!S.getLangOpts().CPlusPlus) {
11263     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11264       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11265         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11266         SourceType = S.Context.getTypeDeclType(Enum);
11267         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11268       }
11269   }
11270 
11271   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11272     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11273       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11274           TargetEnum->getDecl()->hasNameForLinkage() &&
11275           SourceEnum != TargetEnum) {
11276         if (S.SourceMgr.isInSystemMacro(CC))
11277           return;
11278 
11279         return DiagnoseImpCast(S, E, SourceType, T, CC,
11280                                diag::warn_impcast_different_enum_types);
11281       }
11282 }
11283 
11284 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11285                                      SourceLocation CC, QualType T);
11286 
11287 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11288                                     SourceLocation CC, bool &ICContext) {
11289   E = E->IgnoreParenImpCasts();
11290 
11291   if (isa<ConditionalOperator>(E))
11292     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11293 
11294   AnalyzeImplicitConversions(S, E, CC);
11295   if (E->getType() != T)
11296     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11297 }
11298 
11299 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11300                                      SourceLocation CC, QualType T) {
11301   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11302 
11303   bool Suspicious = false;
11304   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11305   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11306 
11307   // If -Wconversion would have warned about either of the candidates
11308   // for a signedness conversion to the context type...
11309   if (!Suspicious) return;
11310 
11311   // ...but it's currently ignored...
11312   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11313     return;
11314 
11315   // ...then check whether it would have warned about either of the
11316   // candidates for a signedness conversion to the condition type.
11317   if (E->getType() == T) return;
11318 
11319   Suspicious = false;
11320   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11321                           E->getType(), CC, &Suspicious);
11322   if (!Suspicious)
11323     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11324                             E->getType(), CC, &Suspicious);
11325 }
11326 
11327 /// Check conversion of given expression to boolean.
11328 /// Input argument E is a logical expression.
11329 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11330   if (S.getLangOpts().Bool)
11331     return;
11332   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11333     return;
11334   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11335 }
11336 
11337 /// AnalyzeImplicitConversions - Find and report any interesting
11338 /// implicit conversions in the given expression.  There are a couple
11339 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11340 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11341                                        SourceLocation CC) {
11342   QualType T = OrigE->getType();
11343   Expr *E = OrigE->IgnoreParenImpCasts();
11344 
11345   if (E->isTypeDependent() || E->isValueDependent())
11346     return;
11347 
11348   // For conditional operators, we analyze the arguments as if they
11349   // were being fed directly into the output.
11350   if (isa<ConditionalOperator>(E)) {
11351     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11352     CheckConditionalOperator(S, CO, CC, T);
11353     return;
11354   }
11355 
11356   // Check implicit argument conversions for function calls.
11357   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11358     CheckImplicitArgumentConversions(S, Call, CC);
11359 
11360   // Go ahead and check any implicit conversions we might have skipped.
11361   // The non-canonical typecheck is just an optimization;
11362   // CheckImplicitConversion will filter out dead implicit conversions.
11363   if (E->getType() != T)
11364     CheckImplicitConversion(S, E, T, CC);
11365 
11366   // Now continue drilling into this expression.
11367 
11368   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11369     // The bound subexpressions in a PseudoObjectExpr are not reachable
11370     // as transitive children.
11371     // FIXME: Use a more uniform representation for this.
11372     for (auto *SE : POE->semantics())
11373       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11374         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11375   }
11376 
11377   // Skip past explicit casts.
11378   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11379     E = CE->getSubExpr()->IgnoreParenImpCasts();
11380     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11381       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11382     return AnalyzeImplicitConversions(S, E, CC);
11383   }
11384 
11385   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11386     // Do a somewhat different check with comparison operators.
11387     if (BO->isComparisonOp())
11388       return AnalyzeComparison(S, BO);
11389 
11390     // And with simple assignments.
11391     if (BO->getOpcode() == BO_Assign)
11392       return AnalyzeAssignment(S, BO);
11393     // And with compound assignments.
11394     if (BO->isAssignmentOp())
11395       return AnalyzeCompoundAssignment(S, BO);
11396   }
11397 
11398   // These break the otherwise-useful invariant below.  Fortunately,
11399   // we don't really need to recurse into them, because any internal
11400   // expressions should have been analyzed already when they were
11401   // built into statements.
11402   if (isa<StmtExpr>(E)) return;
11403 
11404   // Don't descend into unevaluated contexts.
11405   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11406 
11407   // Now just recurse over the expression's children.
11408   CC = E->getExprLoc();
11409   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11410   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11411   for (Stmt *SubStmt : E->children()) {
11412     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11413     if (!ChildExpr)
11414       continue;
11415 
11416     if (IsLogicalAndOperator &&
11417         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11418       // Ignore checking string literals that are in logical and operators.
11419       // This is a common pattern for asserts.
11420       continue;
11421     AnalyzeImplicitConversions(S, ChildExpr, CC);
11422   }
11423 
11424   if (BO && BO->isLogicalOp()) {
11425     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11426     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11427       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11428 
11429     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11430     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11431       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11432   }
11433 
11434   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11435     if (U->getOpcode() == UO_LNot) {
11436       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11437     } else if (U->getOpcode() != UO_AddrOf) {
11438       if (U->getSubExpr()->getType()->isAtomicType())
11439         S.Diag(U->getSubExpr()->getBeginLoc(),
11440                diag::warn_atomic_implicit_seq_cst);
11441     }
11442   }
11443 }
11444 
11445 /// Diagnose integer type and any valid implicit conversion to it.
11446 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11447   // Taking into account implicit conversions,
11448   // allow any integer.
11449   if (!E->getType()->isIntegerType()) {
11450     S.Diag(E->getBeginLoc(),
11451            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11452     return true;
11453   }
11454   // Potentially emit standard warnings for implicit conversions if enabled
11455   // using -Wconversion.
11456   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11457   return false;
11458 }
11459 
11460 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11461 // Returns true when emitting a warning about taking the address of a reference.
11462 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11463                               const PartialDiagnostic &PD) {
11464   E = E->IgnoreParenImpCasts();
11465 
11466   const FunctionDecl *FD = nullptr;
11467 
11468   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11469     if (!DRE->getDecl()->getType()->isReferenceType())
11470       return false;
11471   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11472     if (!M->getMemberDecl()->getType()->isReferenceType())
11473       return false;
11474   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11475     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11476       return false;
11477     FD = Call->getDirectCallee();
11478   } else {
11479     return false;
11480   }
11481 
11482   SemaRef.Diag(E->getExprLoc(), PD);
11483 
11484   // If possible, point to location of function.
11485   if (FD) {
11486     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11487   }
11488 
11489   return true;
11490 }
11491 
11492 // Returns true if the SourceLocation is expanded from any macro body.
11493 // Returns false if the SourceLocation is invalid, is from not in a macro
11494 // expansion, or is from expanded from a top-level macro argument.
11495 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11496   if (Loc.isInvalid())
11497     return false;
11498 
11499   while (Loc.isMacroID()) {
11500     if (SM.isMacroBodyExpansion(Loc))
11501       return true;
11502     Loc = SM.getImmediateMacroCallerLoc(Loc);
11503   }
11504 
11505   return false;
11506 }
11507 
11508 /// Diagnose pointers that are always non-null.
11509 /// \param E the expression containing the pointer
11510 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11511 /// compared to a null pointer
11512 /// \param IsEqual True when the comparison is equal to a null pointer
11513 /// \param Range Extra SourceRange to highlight in the diagnostic
11514 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11515                                         Expr::NullPointerConstantKind NullKind,
11516                                         bool IsEqual, SourceRange Range) {
11517   if (!E)
11518     return;
11519 
11520   // Don't warn inside macros.
11521   if (E->getExprLoc().isMacroID()) {
11522     const SourceManager &SM = getSourceManager();
11523     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11524         IsInAnyMacroBody(SM, Range.getBegin()))
11525       return;
11526   }
11527   E = E->IgnoreImpCasts();
11528 
11529   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11530 
11531   if (isa<CXXThisExpr>(E)) {
11532     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11533                                 : diag::warn_this_bool_conversion;
11534     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11535     return;
11536   }
11537 
11538   bool IsAddressOf = false;
11539 
11540   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11541     if (UO->getOpcode() != UO_AddrOf)
11542       return;
11543     IsAddressOf = true;
11544     E = UO->getSubExpr();
11545   }
11546 
11547   if (IsAddressOf) {
11548     unsigned DiagID = IsCompare
11549                           ? diag::warn_address_of_reference_null_compare
11550                           : diag::warn_address_of_reference_bool_conversion;
11551     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11552                                          << IsEqual;
11553     if (CheckForReference(*this, E, PD)) {
11554       return;
11555     }
11556   }
11557 
11558   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11559     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11560     std::string Str;
11561     llvm::raw_string_ostream S(Str);
11562     E->printPretty(S, nullptr, getPrintingPolicy());
11563     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11564                                 : diag::warn_cast_nonnull_to_bool;
11565     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11566       << E->getSourceRange() << Range << IsEqual;
11567     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11568   };
11569 
11570   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11571   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11572     if (auto *Callee = Call->getDirectCallee()) {
11573       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11574         ComplainAboutNonnullParamOrCall(A);
11575         return;
11576       }
11577     }
11578   }
11579 
11580   // Expect to find a single Decl.  Skip anything more complicated.
11581   ValueDecl *D = nullptr;
11582   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11583     D = R->getDecl();
11584   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11585     D = M->getMemberDecl();
11586   }
11587 
11588   // Weak Decls can be null.
11589   if (!D || D->isWeak())
11590     return;
11591 
11592   // Check for parameter decl with nonnull attribute
11593   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11594     if (getCurFunction() &&
11595         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11596       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11597         ComplainAboutNonnullParamOrCall(A);
11598         return;
11599       }
11600 
11601       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11602         // Skip function template not specialized yet.
11603         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11604           return;
11605         auto ParamIter = llvm::find(FD->parameters(), PV);
11606         assert(ParamIter != FD->param_end());
11607         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11608 
11609         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11610           if (!NonNull->args_size()) {
11611               ComplainAboutNonnullParamOrCall(NonNull);
11612               return;
11613           }
11614 
11615           for (const ParamIdx &ArgNo : NonNull->args()) {
11616             if (ArgNo.getASTIndex() == ParamNo) {
11617               ComplainAboutNonnullParamOrCall(NonNull);
11618               return;
11619             }
11620           }
11621         }
11622       }
11623     }
11624   }
11625 
11626   QualType T = D->getType();
11627   const bool IsArray = T->isArrayType();
11628   const bool IsFunction = T->isFunctionType();
11629 
11630   // Address of function is used to silence the function warning.
11631   if (IsAddressOf && IsFunction) {
11632     return;
11633   }
11634 
11635   // Found nothing.
11636   if (!IsAddressOf && !IsFunction && !IsArray)
11637     return;
11638 
11639   // Pretty print the expression for the diagnostic.
11640   std::string Str;
11641   llvm::raw_string_ostream S(Str);
11642   E->printPretty(S, nullptr, getPrintingPolicy());
11643 
11644   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11645                               : diag::warn_impcast_pointer_to_bool;
11646   enum {
11647     AddressOf,
11648     FunctionPointer,
11649     ArrayPointer
11650   } DiagType;
11651   if (IsAddressOf)
11652     DiagType = AddressOf;
11653   else if (IsFunction)
11654     DiagType = FunctionPointer;
11655   else if (IsArray)
11656     DiagType = ArrayPointer;
11657   else
11658     llvm_unreachable("Could not determine diagnostic.");
11659   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11660                                 << Range << IsEqual;
11661 
11662   if (!IsFunction)
11663     return;
11664 
11665   // Suggest '&' to silence the function warning.
11666   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11667       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11668 
11669   // Check to see if '()' fixit should be emitted.
11670   QualType ReturnType;
11671   UnresolvedSet<4> NonTemplateOverloads;
11672   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11673   if (ReturnType.isNull())
11674     return;
11675 
11676   if (IsCompare) {
11677     // There are two cases here.  If there is null constant, the only suggest
11678     // for a pointer return type.  If the null is 0, then suggest if the return
11679     // type is a pointer or an integer type.
11680     if (!ReturnType->isPointerType()) {
11681       if (NullKind == Expr::NPCK_ZeroExpression ||
11682           NullKind == Expr::NPCK_ZeroLiteral) {
11683         if (!ReturnType->isIntegerType())
11684           return;
11685       } else {
11686         return;
11687       }
11688     }
11689   } else { // !IsCompare
11690     // For function to bool, only suggest if the function pointer has bool
11691     // return type.
11692     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11693       return;
11694   }
11695   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11696       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11697 }
11698 
11699 /// Diagnoses "dangerous" implicit conversions within the given
11700 /// expression (which is a full expression).  Implements -Wconversion
11701 /// and -Wsign-compare.
11702 ///
11703 /// \param CC the "context" location of the implicit conversion, i.e.
11704 ///   the most location of the syntactic entity requiring the implicit
11705 ///   conversion
11706 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11707   // Don't diagnose in unevaluated contexts.
11708   if (isUnevaluatedContext())
11709     return;
11710 
11711   // Don't diagnose for value- or type-dependent expressions.
11712   if (E->isTypeDependent() || E->isValueDependent())
11713     return;
11714 
11715   // Check for array bounds violations in cases where the check isn't triggered
11716   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11717   // ArraySubscriptExpr is on the RHS of a variable initialization.
11718   CheckArrayAccess(E);
11719 
11720   // This is not the right CC for (e.g.) a variable initialization.
11721   AnalyzeImplicitConversions(*this, E, CC);
11722 }
11723 
11724 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11725 /// Input argument E is a logical expression.
11726 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11727   ::CheckBoolLikeConversion(*this, E, CC);
11728 }
11729 
11730 /// Diagnose when expression is an integer constant expression and its evaluation
11731 /// results in integer overflow
11732 void Sema::CheckForIntOverflow (Expr *E) {
11733   // Use a work list to deal with nested struct initializers.
11734   SmallVector<Expr *, 2> Exprs(1, E);
11735 
11736   do {
11737     Expr *OriginalE = Exprs.pop_back_val();
11738     Expr *E = OriginalE->IgnoreParenCasts();
11739 
11740     if (isa<BinaryOperator>(E)) {
11741       E->EvaluateForOverflow(Context);
11742       continue;
11743     }
11744 
11745     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11746       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11747     else if (isa<ObjCBoxedExpr>(OriginalE))
11748       E->EvaluateForOverflow(Context);
11749     else if (auto Call = dyn_cast<CallExpr>(E))
11750       Exprs.append(Call->arg_begin(), Call->arg_end());
11751     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11752       Exprs.append(Message->arg_begin(), Message->arg_end());
11753   } while (!Exprs.empty());
11754 }
11755 
11756 namespace {
11757 
11758 /// Visitor for expressions which looks for unsequenced operations on the
11759 /// same object.
11760 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11761   using Base = EvaluatedExprVisitor<SequenceChecker>;
11762 
11763   /// A tree of sequenced regions within an expression. Two regions are
11764   /// unsequenced if one is an ancestor or a descendent of the other. When we
11765   /// finish processing an expression with sequencing, such as a comma
11766   /// expression, we fold its tree nodes into its parent, since they are
11767   /// unsequenced with respect to nodes we will visit later.
11768   class SequenceTree {
11769     struct Value {
11770       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11771       unsigned Parent : 31;
11772       unsigned Merged : 1;
11773     };
11774     SmallVector<Value, 8> Values;
11775 
11776   public:
11777     /// A region within an expression which may be sequenced with respect
11778     /// to some other region.
11779     class Seq {
11780       friend class SequenceTree;
11781 
11782       unsigned Index;
11783 
11784       explicit Seq(unsigned N) : Index(N) {}
11785 
11786     public:
11787       Seq() : Index(0) {}
11788     };
11789 
11790     SequenceTree() { Values.push_back(Value(0)); }
11791     Seq root() const { return Seq(0); }
11792 
11793     /// Create a new sequence of operations, which is an unsequenced
11794     /// subset of \p Parent. This sequence of operations is sequenced with
11795     /// respect to other children of \p Parent.
11796     Seq allocate(Seq Parent) {
11797       Values.push_back(Value(Parent.Index));
11798       return Seq(Values.size() - 1);
11799     }
11800 
11801     /// Merge a sequence of operations into its parent.
11802     void merge(Seq S) {
11803       Values[S.Index].Merged = true;
11804     }
11805 
11806     /// Determine whether two operations are unsequenced. This operation
11807     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11808     /// should have been merged into its parent as appropriate.
11809     bool isUnsequenced(Seq Cur, Seq Old) {
11810       unsigned C = representative(Cur.Index);
11811       unsigned Target = representative(Old.Index);
11812       while (C >= Target) {
11813         if (C == Target)
11814           return true;
11815         C = Values[C].Parent;
11816       }
11817       return false;
11818     }
11819 
11820   private:
11821     /// Pick a representative for a sequence.
11822     unsigned representative(unsigned K) {
11823       if (Values[K].Merged)
11824         // Perform path compression as we go.
11825         return Values[K].Parent = representative(Values[K].Parent);
11826       return K;
11827     }
11828   };
11829 
11830   /// An object for which we can track unsequenced uses.
11831   using Object = NamedDecl *;
11832 
11833   /// Different flavors of object usage which we track. We only track the
11834   /// least-sequenced usage of each kind.
11835   enum UsageKind {
11836     /// A read of an object. Multiple unsequenced reads are OK.
11837     UK_Use,
11838 
11839     /// A modification of an object which is sequenced before the value
11840     /// computation of the expression, such as ++n in C++.
11841     UK_ModAsValue,
11842 
11843     /// A modification of an object which is not sequenced before the value
11844     /// computation of the expression, such as n++.
11845     UK_ModAsSideEffect,
11846 
11847     UK_Count = UK_ModAsSideEffect + 1
11848   };
11849 
11850   struct Usage {
11851     Expr *Use;
11852     SequenceTree::Seq Seq;
11853 
11854     Usage() : Use(nullptr), Seq() {}
11855   };
11856 
11857   struct UsageInfo {
11858     Usage Uses[UK_Count];
11859 
11860     /// Have we issued a diagnostic for this variable already?
11861     bool Diagnosed;
11862 
11863     UsageInfo() : Uses(), Diagnosed(false) {}
11864   };
11865   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11866 
11867   Sema &SemaRef;
11868 
11869   /// Sequenced regions within the expression.
11870   SequenceTree Tree;
11871 
11872   /// Declaration modifications and references which we have seen.
11873   UsageInfoMap UsageMap;
11874 
11875   /// The region we are currently within.
11876   SequenceTree::Seq Region;
11877 
11878   /// Filled in with declarations which were modified as a side-effect
11879   /// (that is, post-increment operations).
11880   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11881 
11882   /// Expressions to check later. We defer checking these to reduce
11883   /// stack usage.
11884   SmallVectorImpl<Expr *> &WorkList;
11885 
11886   /// RAII object wrapping the visitation of a sequenced subexpression of an
11887   /// expression. At the end of this process, the side-effects of the evaluation
11888   /// become sequenced with respect to the value computation of the result, so
11889   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11890   /// UK_ModAsValue.
11891   struct SequencedSubexpression {
11892     SequencedSubexpression(SequenceChecker &Self)
11893       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11894       Self.ModAsSideEffect = &ModAsSideEffect;
11895     }
11896 
11897     ~SequencedSubexpression() {
11898       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11899         UsageInfo &U = Self.UsageMap[M.first];
11900         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11901         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11902         SideEffectUsage = M.second;
11903       }
11904       Self.ModAsSideEffect = OldModAsSideEffect;
11905     }
11906 
11907     SequenceChecker &Self;
11908     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11909     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11910   };
11911 
11912   /// RAII object wrapping the visitation of a subexpression which we might
11913   /// choose to evaluate as a constant. If any subexpression is evaluated and
11914   /// found to be non-constant, this allows us to suppress the evaluation of
11915   /// the outer expression.
11916   class EvaluationTracker {
11917   public:
11918     EvaluationTracker(SequenceChecker &Self)
11919         : Self(Self), Prev(Self.EvalTracker) {
11920       Self.EvalTracker = this;
11921     }
11922 
11923     ~EvaluationTracker() {
11924       Self.EvalTracker = Prev;
11925       if (Prev)
11926         Prev->EvalOK &= EvalOK;
11927     }
11928 
11929     bool evaluate(const Expr *E, bool &Result) {
11930       if (!EvalOK || E->isValueDependent())
11931         return false;
11932       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11933       return EvalOK;
11934     }
11935 
11936   private:
11937     SequenceChecker &Self;
11938     EvaluationTracker *Prev;
11939     bool EvalOK = true;
11940   } *EvalTracker = nullptr;
11941 
11942   /// Find the object which is produced by the specified expression,
11943   /// if any.
11944   Object getObject(Expr *E, bool Mod) const {
11945     E = E->IgnoreParenCasts();
11946     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11947       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11948         return getObject(UO->getSubExpr(), Mod);
11949     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11950       if (BO->getOpcode() == BO_Comma)
11951         return getObject(BO->getRHS(), Mod);
11952       if (Mod && BO->isAssignmentOp())
11953         return getObject(BO->getLHS(), Mod);
11954     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11955       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11956       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11957         return ME->getMemberDecl();
11958     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11959       // FIXME: If this is a reference, map through to its value.
11960       return DRE->getDecl();
11961     return nullptr;
11962   }
11963 
11964   /// Note that an object was modified or used by an expression.
11965   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11966     Usage &U = UI.Uses[UK];
11967     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11968       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11969         ModAsSideEffect->push_back(std::make_pair(O, U));
11970       U.Use = Ref;
11971       U.Seq = Region;
11972     }
11973   }
11974 
11975   /// Check whether a modification or use conflicts with a prior usage.
11976   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11977                   bool IsModMod) {
11978     if (UI.Diagnosed)
11979       return;
11980 
11981     const Usage &U = UI.Uses[OtherKind];
11982     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11983       return;
11984 
11985     Expr *Mod = U.Use;
11986     Expr *ModOrUse = Ref;
11987     if (OtherKind == UK_Use)
11988       std::swap(Mod, ModOrUse);
11989 
11990     SemaRef.Diag(Mod->getExprLoc(),
11991                  IsModMod ? diag::warn_unsequenced_mod_mod
11992                           : diag::warn_unsequenced_mod_use)
11993       << O << SourceRange(ModOrUse->getExprLoc());
11994     UI.Diagnosed = true;
11995   }
11996 
11997   void notePreUse(Object O, Expr *Use) {
11998     UsageInfo &U = UsageMap[O];
11999     // Uses conflict with other modifications.
12000     checkUsage(O, U, Use, UK_ModAsValue, false);
12001   }
12002 
12003   void notePostUse(Object O, Expr *Use) {
12004     UsageInfo &U = UsageMap[O];
12005     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12006     addUsage(U, O, Use, UK_Use);
12007   }
12008 
12009   void notePreMod(Object O, Expr *Mod) {
12010     UsageInfo &U = UsageMap[O];
12011     // Modifications conflict with other modifications and with uses.
12012     checkUsage(O, U, Mod, UK_ModAsValue, true);
12013     checkUsage(O, U, Mod, UK_Use, false);
12014   }
12015 
12016   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12017     UsageInfo &U = UsageMap[O];
12018     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12019     addUsage(U, O, Use, UK);
12020   }
12021 
12022 public:
12023   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12024       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12025     Visit(E);
12026   }
12027 
12028   void VisitStmt(Stmt *S) {
12029     // Skip all statements which aren't expressions for now.
12030   }
12031 
12032   void VisitExpr(Expr *E) {
12033     // By default, just recurse to evaluated subexpressions.
12034     Base::VisitStmt(E);
12035   }
12036 
12037   void VisitCastExpr(CastExpr *E) {
12038     Object O = Object();
12039     if (E->getCastKind() == CK_LValueToRValue)
12040       O = getObject(E->getSubExpr(), false);
12041 
12042     if (O)
12043       notePreUse(O, E);
12044     VisitExpr(E);
12045     if (O)
12046       notePostUse(O, E);
12047   }
12048 
12049   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12050     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12051     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12052     SequenceTree::Seq OldRegion = Region;
12053 
12054     {
12055       SequencedSubexpression SeqBefore(*this);
12056       Region = BeforeRegion;
12057       Visit(SequencedBefore);
12058     }
12059 
12060     Region = AfterRegion;
12061     Visit(SequencedAfter);
12062 
12063     Region = OldRegion;
12064 
12065     Tree.merge(BeforeRegion);
12066     Tree.merge(AfterRegion);
12067   }
12068 
12069   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12070     // C++17 [expr.sub]p1:
12071     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12072     //   expression E1 is sequenced before the expression E2.
12073     if (SemaRef.getLangOpts().CPlusPlus17)
12074       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12075     else
12076       Base::VisitStmt(ASE);
12077   }
12078 
12079   void VisitBinComma(BinaryOperator *BO) {
12080     // C++11 [expr.comma]p1:
12081     //   Every value computation and side effect associated with the left
12082     //   expression is sequenced before every value computation and side
12083     //   effect associated with the right expression.
12084     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12085   }
12086 
12087   void VisitBinAssign(BinaryOperator *BO) {
12088     // The modification is sequenced after the value computation of the LHS
12089     // and RHS, so check it before inspecting the operands and update the
12090     // map afterwards.
12091     Object O = getObject(BO->getLHS(), true);
12092     if (!O)
12093       return VisitExpr(BO);
12094 
12095     notePreMod(O, BO);
12096 
12097     // C++11 [expr.ass]p7:
12098     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12099     //   only once.
12100     //
12101     // Therefore, for a compound assignment operator, O is considered used
12102     // everywhere except within the evaluation of E1 itself.
12103     if (isa<CompoundAssignOperator>(BO))
12104       notePreUse(O, BO);
12105 
12106     Visit(BO->getLHS());
12107 
12108     if (isa<CompoundAssignOperator>(BO))
12109       notePostUse(O, BO);
12110 
12111     Visit(BO->getRHS());
12112 
12113     // C++11 [expr.ass]p1:
12114     //   the assignment is sequenced [...] before the value computation of the
12115     //   assignment expression.
12116     // C11 6.5.16/3 has no such rule.
12117     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12118                                                        : UK_ModAsSideEffect);
12119   }
12120 
12121   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12122     VisitBinAssign(CAO);
12123   }
12124 
12125   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12126   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12127   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12128     Object O = getObject(UO->getSubExpr(), true);
12129     if (!O)
12130       return VisitExpr(UO);
12131 
12132     notePreMod(O, UO);
12133     Visit(UO->getSubExpr());
12134     // C++11 [expr.pre.incr]p1:
12135     //   the expression ++x is equivalent to x+=1
12136     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12137                                                        : UK_ModAsSideEffect);
12138   }
12139 
12140   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12141   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12142   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12143     Object O = getObject(UO->getSubExpr(), true);
12144     if (!O)
12145       return VisitExpr(UO);
12146 
12147     notePreMod(O, UO);
12148     Visit(UO->getSubExpr());
12149     notePostMod(O, UO, UK_ModAsSideEffect);
12150   }
12151 
12152   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12153   void VisitBinLOr(BinaryOperator *BO) {
12154     // The side-effects of the LHS of an '&&' are sequenced before the
12155     // value computation of the RHS, and hence before the value computation
12156     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12157     // as if they were unconditionally sequenced.
12158     EvaluationTracker Eval(*this);
12159     {
12160       SequencedSubexpression Sequenced(*this);
12161       Visit(BO->getLHS());
12162     }
12163 
12164     bool Result;
12165     if (Eval.evaluate(BO->getLHS(), Result)) {
12166       if (!Result)
12167         Visit(BO->getRHS());
12168     } else {
12169       // Check for unsequenced operations in the RHS, treating it as an
12170       // entirely separate evaluation.
12171       //
12172       // FIXME: If there are operations in the RHS which are unsequenced
12173       // with respect to operations outside the RHS, and those operations
12174       // are unconditionally evaluated, diagnose them.
12175       WorkList.push_back(BO->getRHS());
12176     }
12177   }
12178   void VisitBinLAnd(BinaryOperator *BO) {
12179     EvaluationTracker Eval(*this);
12180     {
12181       SequencedSubexpression Sequenced(*this);
12182       Visit(BO->getLHS());
12183     }
12184 
12185     bool Result;
12186     if (Eval.evaluate(BO->getLHS(), Result)) {
12187       if (Result)
12188         Visit(BO->getRHS());
12189     } else {
12190       WorkList.push_back(BO->getRHS());
12191     }
12192   }
12193 
12194   // Only visit the condition, unless we can be sure which subexpression will
12195   // be chosen.
12196   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12197     EvaluationTracker Eval(*this);
12198     {
12199       SequencedSubexpression Sequenced(*this);
12200       Visit(CO->getCond());
12201     }
12202 
12203     bool Result;
12204     if (Eval.evaluate(CO->getCond(), Result))
12205       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12206     else {
12207       WorkList.push_back(CO->getTrueExpr());
12208       WorkList.push_back(CO->getFalseExpr());
12209     }
12210   }
12211 
12212   void VisitCallExpr(CallExpr *CE) {
12213     // C++11 [intro.execution]p15:
12214     //   When calling a function [...], every value computation and side effect
12215     //   associated with any argument expression, or with the postfix expression
12216     //   designating the called function, is sequenced before execution of every
12217     //   expression or statement in the body of the function [and thus before
12218     //   the value computation of its result].
12219     SequencedSubexpression Sequenced(*this);
12220     Base::VisitCallExpr(CE);
12221 
12222     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12223   }
12224 
12225   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12226     // This is a call, so all subexpressions are sequenced before the result.
12227     SequencedSubexpression Sequenced(*this);
12228 
12229     if (!CCE->isListInitialization())
12230       return VisitExpr(CCE);
12231 
12232     // In C++11, list initializations are sequenced.
12233     SmallVector<SequenceTree::Seq, 32> Elts;
12234     SequenceTree::Seq Parent = Region;
12235     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12236                                         E = CCE->arg_end();
12237          I != E; ++I) {
12238       Region = Tree.allocate(Parent);
12239       Elts.push_back(Region);
12240       Visit(*I);
12241     }
12242 
12243     // Forget that the initializers are sequenced.
12244     Region = Parent;
12245     for (unsigned I = 0; I < Elts.size(); ++I)
12246       Tree.merge(Elts[I]);
12247   }
12248 
12249   void VisitInitListExpr(InitListExpr *ILE) {
12250     if (!SemaRef.getLangOpts().CPlusPlus11)
12251       return VisitExpr(ILE);
12252 
12253     // In C++11, list initializations are sequenced.
12254     SmallVector<SequenceTree::Seq, 32> Elts;
12255     SequenceTree::Seq Parent = Region;
12256     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12257       Expr *E = ILE->getInit(I);
12258       if (!E) continue;
12259       Region = Tree.allocate(Parent);
12260       Elts.push_back(Region);
12261       Visit(E);
12262     }
12263 
12264     // Forget that the initializers are sequenced.
12265     Region = Parent;
12266     for (unsigned I = 0; I < Elts.size(); ++I)
12267       Tree.merge(Elts[I]);
12268   }
12269 };
12270 
12271 } // namespace
12272 
12273 void Sema::CheckUnsequencedOperations(Expr *E) {
12274   SmallVector<Expr *, 8> WorkList;
12275   WorkList.push_back(E);
12276   while (!WorkList.empty()) {
12277     Expr *Item = WorkList.pop_back_val();
12278     SequenceChecker(*this, Item, WorkList);
12279   }
12280 }
12281 
12282 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12283                               bool IsConstexpr) {
12284   CheckImplicitConversions(E, CheckLoc);
12285   if (!E->isInstantiationDependent())
12286     CheckUnsequencedOperations(E);
12287   if (!IsConstexpr && !E->isValueDependent())
12288     CheckForIntOverflow(E);
12289   DiagnoseMisalignedMembers();
12290 }
12291 
12292 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12293                                        FieldDecl *BitField,
12294                                        Expr *Init) {
12295   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12296 }
12297 
12298 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12299                                          SourceLocation Loc) {
12300   if (!PType->isVariablyModifiedType())
12301     return;
12302   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12303     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12304     return;
12305   }
12306   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12307     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12308     return;
12309   }
12310   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12311     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12312     return;
12313   }
12314 
12315   const ArrayType *AT = S.Context.getAsArrayType(PType);
12316   if (!AT)
12317     return;
12318 
12319   if (AT->getSizeModifier() != ArrayType::Star) {
12320     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12321     return;
12322   }
12323 
12324   S.Diag(Loc, diag::err_array_star_in_function_definition);
12325 }
12326 
12327 /// CheckParmsForFunctionDef - Check that the parameters of the given
12328 /// function are appropriate for the definition of a function. This
12329 /// takes care of any checks that cannot be performed on the
12330 /// declaration itself, e.g., that the types of each of the function
12331 /// parameters are complete.
12332 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12333                                     bool CheckParameterNames) {
12334   bool HasInvalidParm = false;
12335   for (ParmVarDecl *Param : Parameters) {
12336     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12337     // function declarator that is part of a function definition of
12338     // that function shall not have incomplete type.
12339     //
12340     // This is also C++ [dcl.fct]p6.
12341     if (!Param->isInvalidDecl() &&
12342         RequireCompleteType(Param->getLocation(), Param->getType(),
12343                             diag::err_typecheck_decl_incomplete_type)) {
12344       Param->setInvalidDecl();
12345       HasInvalidParm = true;
12346     }
12347 
12348     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12349     // declaration of each parameter shall include an identifier.
12350     if (CheckParameterNames &&
12351         Param->getIdentifier() == nullptr &&
12352         !Param->isImplicit() &&
12353         !getLangOpts().CPlusPlus)
12354       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12355 
12356     // C99 6.7.5.3p12:
12357     //   If the function declarator is not part of a definition of that
12358     //   function, parameters may have incomplete type and may use the [*]
12359     //   notation in their sequences of declarator specifiers to specify
12360     //   variable length array types.
12361     QualType PType = Param->getOriginalType();
12362     // FIXME: This diagnostic should point the '[*]' if source-location
12363     // information is added for it.
12364     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12365 
12366     // If the parameter is a c++ class type and it has to be destructed in the
12367     // callee function, declare the destructor so that it can be called by the
12368     // callee function. Do not perform any direct access check on the dtor here.
12369     if (!Param->isInvalidDecl()) {
12370       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12371         if (!ClassDecl->isInvalidDecl() &&
12372             !ClassDecl->hasIrrelevantDestructor() &&
12373             !ClassDecl->isDependentContext() &&
12374             ClassDecl->isParamDestroyedInCallee()) {
12375           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12376           MarkFunctionReferenced(Param->getLocation(), Destructor);
12377           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12378         }
12379       }
12380     }
12381 
12382     // Parameters with the pass_object_size attribute only need to be marked
12383     // constant at function definitions. Because we lack information about
12384     // whether we're on a declaration or definition when we're instantiating the
12385     // attribute, we need to check for constness here.
12386     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12387       if (!Param->getType().isConstQualified())
12388         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12389             << Attr->getSpelling() << 1;
12390 
12391     // Check for parameter names shadowing fields from the class.
12392     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12393       // The owning context for the parameter should be the function, but we
12394       // want to see if this function's declaration context is a record.
12395       DeclContext *DC = Param->getDeclContext();
12396       if (DC && DC->isFunctionOrMethod()) {
12397         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12398           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12399                                      RD, /*DeclIsField*/ false);
12400       }
12401     }
12402   }
12403 
12404   return HasInvalidParm;
12405 }
12406 
12407 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12408 /// or MemberExpr.
12409 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12410                               ASTContext &Context) {
12411   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12412     return Context.getDeclAlign(DRE->getDecl());
12413 
12414   if (const auto *ME = dyn_cast<MemberExpr>(E))
12415     return Context.getDeclAlign(ME->getMemberDecl());
12416 
12417   return TypeAlign;
12418 }
12419 
12420 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12421 /// pointer cast increases the alignment requirements.
12422 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12423   // This is actually a lot of work to potentially be doing on every
12424   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12425   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12426     return;
12427 
12428   // Ignore dependent types.
12429   if (T->isDependentType() || Op->getType()->isDependentType())
12430     return;
12431 
12432   // Require that the destination be a pointer type.
12433   const PointerType *DestPtr = T->getAs<PointerType>();
12434   if (!DestPtr) return;
12435 
12436   // If the destination has alignment 1, we're done.
12437   QualType DestPointee = DestPtr->getPointeeType();
12438   if (DestPointee->isIncompleteType()) return;
12439   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12440   if (DestAlign.isOne()) return;
12441 
12442   // Require that the source be a pointer type.
12443   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12444   if (!SrcPtr) return;
12445   QualType SrcPointee = SrcPtr->getPointeeType();
12446 
12447   // Whitelist casts from cv void*.  We already implicitly
12448   // whitelisted casts to cv void*, since they have alignment 1.
12449   // Also whitelist casts involving incomplete types, which implicitly
12450   // includes 'void'.
12451   if (SrcPointee->isIncompleteType()) return;
12452 
12453   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12454 
12455   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12456     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12457       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12458   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12459     if (UO->getOpcode() == UO_AddrOf)
12460       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12461   }
12462 
12463   if (SrcAlign >= DestAlign) return;
12464 
12465   Diag(TRange.getBegin(), diag::warn_cast_align)
12466     << Op->getType() << T
12467     << static_cast<unsigned>(SrcAlign.getQuantity())
12468     << static_cast<unsigned>(DestAlign.getQuantity())
12469     << TRange << Op->getSourceRange();
12470 }
12471 
12472 /// Check whether this array fits the idiom of a size-one tail padded
12473 /// array member of a struct.
12474 ///
12475 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12476 /// commonly used to emulate flexible arrays in C89 code.
12477 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12478                                     const NamedDecl *ND) {
12479   if (Size != 1 || !ND) return false;
12480 
12481   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12482   if (!FD) return false;
12483 
12484   // Don't consider sizes resulting from macro expansions or template argument
12485   // substitution to form C89 tail-padded arrays.
12486 
12487   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12488   while (TInfo) {
12489     TypeLoc TL = TInfo->getTypeLoc();
12490     // Look through typedefs.
12491     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12492       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12493       TInfo = TDL->getTypeSourceInfo();
12494       continue;
12495     }
12496     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12497       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12498       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12499         return false;
12500     }
12501     break;
12502   }
12503 
12504   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12505   if (!RD) return false;
12506   if (RD->isUnion()) return false;
12507   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12508     if (!CRD->isStandardLayout()) return false;
12509   }
12510 
12511   // See if this is the last field decl in the record.
12512   const Decl *D = FD;
12513   while ((D = D->getNextDeclInContext()))
12514     if (isa<FieldDecl>(D))
12515       return false;
12516   return true;
12517 }
12518 
12519 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12520                             const ArraySubscriptExpr *ASE,
12521                             bool AllowOnePastEnd, bool IndexNegated) {
12522   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12523   if (IndexExpr->isValueDependent())
12524     return;
12525 
12526   const Type *EffectiveType =
12527       BaseExpr->getType()->getPointeeOrArrayElementType();
12528   BaseExpr = BaseExpr->IgnoreParenCasts();
12529   const ConstantArrayType *ArrayTy =
12530       Context.getAsConstantArrayType(BaseExpr->getType());
12531 
12532   if (!ArrayTy)
12533     return;
12534 
12535   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12536   if (EffectiveType->isDependentType() || BaseType->isDependentType())
12537     return;
12538 
12539   Expr::EvalResult Result;
12540   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12541     return;
12542 
12543   llvm::APSInt index = Result.Val.getInt();
12544   if (IndexNegated)
12545     index = -index;
12546 
12547   const NamedDecl *ND = nullptr;
12548   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12549     ND = DRE->getDecl();
12550   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12551     ND = ME->getMemberDecl();
12552 
12553   if (index.isUnsigned() || !index.isNegative()) {
12554     // It is possible that the type of the base expression after
12555     // IgnoreParenCasts is incomplete, even though the type of the base
12556     // expression before IgnoreParenCasts is complete (see PR39746 for an
12557     // example). In this case we have no information about whether the array
12558     // access exceeds the array bounds. However we can still diagnose an array
12559     // access which precedes the array bounds.
12560     if (BaseType->isIncompleteType())
12561       return;
12562 
12563     llvm::APInt size = ArrayTy->getSize();
12564     if (!size.isStrictlyPositive())
12565       return;
12566 
12567     if (BaseType != EffectiveType) {
12568       // Make sure we're comparing apples to apples when comparing index to size
12569       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12570       uint64_t array_typesize = Context.getTypeSize(BaseType);
12571       // Handle ptrarith_typesize being zero, such as when casting to void*
12572       if (!ptrarith_typesize) ptrarith_typesize = 1;
12573       if (ptrarith_typesize != array_typesize) {
12574         // There's a cast to a different size type involved
12575         uint64_t ratio = array_typesize / ptrarith_typesize;
12576         // TODO: Be smarter about handling cases where array_typesize is not a
12577         // multiple of ptrarith_typesize
12578         if (ptrarith_typesize * ratio == array_typesize)
12579           size *= llvm::APInt(size.getBitWidth(), ratio);
12580       }
12581     }
12582 
12583     if (size.getBitWidth() > index.getBitWidth())
12584       index = index.zext(size.getBitWidth());
12585     else if (size.getBitWidth() < index.getBitWidth())
12586       size = size.zext(index.getBitWidth());
12587 
12588     // For array subscripting the index must be less than size, but for pointer
12589     // arithmetic also allow the index (offset) to be equal to size since
12590     // computing the next address after the end of the array is legal and
12591     // commonly done e.g. in C++ iterators and range-based for loops.
12592     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12593       return;
12594 
12595     // Also don't warn for arrays of size 1 which are members of some
12596     // structure. These are often used to approximate flexible arrays in C89
12597     // code.
12598     if (IsTailPaddedMemberArray(*this, size, ND))
12599       return;
12600 
12601     // Suppress the warning if the subscript expression (as identified by the
12602     // ']' location) and the index expression are both from macro expansions
12603     // within a system header.
12604     if (ASE) {
12605       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12606           ASE->getRBracketLoc());
12607       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12608         SourceLocation IndexLoc =
12609             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12610         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12611           return;
12612       }
12613     }
12614 
12615     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12616     if (ASE)
12617       DiagID = diag::warn_array_index_exceeds_bounds;
12618 
12619     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12620                         PDiag(DiagID) << index.toString(10, true)
12621                                       << size.toString(10, true)
12622                                       << (unsigned)size.getLimitedValue(~0U)
12623                                       << IndexExpr->getSourceRange());
12624   } else {
12625     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12626     if (!ASE) {
12627       DiagID = diag::warn_ptr_arith_precedes_bounds;
12628       if (index.isNegative()) index = -index;
12629     }
12630 
12631     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12632                         PDiag(DiagID) << index.toString(10, true)
12633                                       << IndexExpr->getSourceRange());
12634   }
12635 
12636   if (!ND) {
12637     // Try harder to find a NamedDecl to point at in the note.
12638     while (const ArraySubscriptExpr *ASE =
12639            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12640       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12641     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12642       ND = DRE->getDecl();
12643     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12644       ND = ME->getMemberDecl();
12645   }
12646 
12647   if (ND)
12648     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12649                         PDiag(diag::note_array_index_out_of_bounds)
12650                             << ND->getDeclName());
12651 }
12652 
12653 void Sema::CheckArrayAccess(const Expr *expr) {
12654   int AllowOnePastEnd = 0;
12655   while (expr) {
12656     expr = expr->IgnoreParenImpCasts();
12657     switch (expr->getStmtClass()) {
12658       case Stmt::ArraySubscriptExprClass: {
12659         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12660         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12661                          AllowOnePastEnd > 0);
12662         expr = ASE->getBase();
12663         break;
12664       }
12665       case Stmt::MemberExprClass: {
12666         expr = cast<MemberExpr>(expr)->getBase();
12667         break;
12668       }
12669       case Stmt::OMPArraySectionExprClass: {
12670         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12671         if (ASE->getLowerBound())
12672           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12673                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12674         return;
12675       }
12676       case Stmt::UnaryOperatorClass: {
12677         // Only unwrap the * and & unary operators
12678         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12679         expr = UO->getSubExpr();
12680         switch (UO->getOpcode()) {
12681           case UO_AddrOf:
12682             AllowOnePastEnd++;
12683             break;
12684           case UO_Deref:
12685             AllowOnePastEnd--;
12686             break;
12687           default:
12688             return;
12689         }
12690         break;
12691       }
12692       case Stmt::ConditionalOperatorClass: {
12693         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12694         if (const Expr *lhs = cond->getLHS())
12695           CheckArrayAccess(lhs);
12696         if (const Expr *rhs = cond->getRHS())
12697           CheckArrayAccess(rhs);
12698         return;
12699       }
12700       case Stmt::CXXOperatorCallExprClass: {
12701         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12702         for (const auto *Arg : OCE->arguments())
12703           CheckArrayAccess(Arg);
12704         return;
12705       }
12706       default:
12707         return;
12708     }
12709   }
12710 }
12711 
12712 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12713 
12714 namespace {
12715 
12716 struct RetainCycleOwner {
12717   VarDecl *Variable = nullptr;
12718   SourceRange Range;
12719   SourceLocation Loc;
12720   bool Indirect = false;
12721 
12722   RetainCycleOwner() = default;
12723 
12724   void setLocsFrom(Expr *e) {
12725     Loc = e->getExprLoc();
12726     Range = e->getSourceRange();
12727   }
12728 };
12729 
12730 } // namespace
12731 
12732 /// Consider whether capturing the given variable can possibly lead to
12733 /// a retain cycle.
12734 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12735   // In ARC, it's captured strongly iff the variable has __strong
12736   // lifetime.  In MRR, it's captured strongly if the variable is
12737   // __block and has an appropriate type.
12738   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12739     return false;
12740 
12741   owner.Variable = var;
12742   if (ref)
12743     owner.setLocsFrom(ref);
12744   return true;
12745 }
12746 
12747 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12748   while (true) {
12749     e = e->IgnoreParens();
12750     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12751       switch (cast->getCastKind()) {
12752       case CK_BitCast:
12753       case CK_LValueBitCast:
12754       case CK_LValueToRValue:
12755       case CK_ARCReclaimReturnedObject:
12756         e = cast->getSubExpr();
12757         continue;
12758 
12759       default:
12760         return false;
12761       }
12762     }
12763 
12764     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12765       ObjCIvarDecl *ivar = ref->getDecl();
12766       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12767         return false;
12768 
12769       // Try to find a retain cycle in the base.
12770       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12771         return false;
12772 
12773       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12774       owner.Indirect = true;
12775       return true;
12776     }
12777 
12778     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12779       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12780       if (!var) return false;
12781       return considerVariable(var, ref, owner);
12782     }
12783 
12784     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12785       if (member->isArrow()) return false;
12786 
12787       // Don't count this as an indirect ownership.
12788       e = member->getBase();
12789       continue;
12790     }
12791 
12792     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12793       // Only pay attention to pseudo-objects on property references.
12794       ObjCPropertyRefExpr *pre
12795         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12796                                               ->IgnoreParens());
12797       if (!pre) return false;
12798       if (pre->isImplicitProperty()) return false;
12799       ObjCPropertyDecl *property = pre->getExplicitProperty();
12800       if (!property->isRetaining() &&
12801           !(property->getPropertyIvarDecl() &&
12802             property->getPropertyIvarDecl()->getType()
12803               .getObjCLifetime() == Qualifiers::OCL_Strong))
12804           return false;
12805 
12806       owner.Indirect = true;
12807       if (pre->isSuperReceiver()) {
12808         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12809         if (!owner.Variable)
12810           return false;
12811         owner.Loc = pre->getLocation();
12812         owner.Range = pre->getSourceRange();
12813         return true;
12814       }
12815       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12816                               ->getSourceExpr());
12817       continue;
12818     }
12819 
12820     // Array ivars?
12821 
12822     return false;
12823   }
12824 }
12825 
12826 namespace {
12827 
12828   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12829     ASTContext &Context;
12830     VarDecl *Variable;
12831     Expr *Capturer = nullptr;
12832     bool VarWillBeReased = false;
12833 
12834     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12835         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12836           Context(Context), Variable(variable) {}
12837 
12838     void VisitDeclRefExpr(DeclRefExpr *ref) {
12839       if (ref->getDecl() == Variable && !Capturer)
12840         Capturer = ref;
12841     }
12842 
12843     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12844       if (Capturer) return;
12845       Visit(ref->getBase());
12846       if (Capturer && ref->isFreeIvar())
12847         Capturer = ref;
12848     }
12849 
12850     void VisitBlockExpr(BlockExpr *block) {
12851       // Look inside nested blocks
12852       if (block->getBlockDecl()->capturesVariable(Variable))
12853         Visit(block->getBlockDecl()->getBody());
12854     }
12855 
12856     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12857       if (Capturer) return;
12858       if (OVE->getSourceExpr())
12859         Visit(OVE->getSourceExpr());
12860     }
12861 
12862     void VisitBinaryOperator(BinaryOperator *BinOp) {
12863       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12864         return;
12865       Expr *LHS = BinOp->getLHS();
12866       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12867         if (DRE->getDecl() != Variable)
12868           return;
12869         if (Expr *RHS = BinOp->getRHS()) {
12870           RHS = RHS->IgnoreParenCasts();
12871           llvm::APSInt Value;
12872           VarWillBeReased =
12873             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12874         }
12875       }
12876     }
12877   };
12878 
12879 } // namespace
12880 
12881 /// Check whether the given argument is a block which captures a
12882 /// variable.
12883 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12884   assert(owner.Variable && owner.Loc.isValid());
12885 
12886   e = e->IgnoreParenCasts();
12887 
12888   // Look through [^{...} copy] and Block_copy(^{...}).
12889   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12890     Selector Cmd = ME->getSelector();
12891     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12892       e = ME->getInstanceReceiver();
12893       if (!e)
12894         return nullptr;
12895       e = e->IgnoreParenCasts();
12896     }
12897   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12898     if (CE->getNumArgs() == 1) {
12899       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12900       if (Fn) {
12901         const IdentifierInfo *FnI = Fn->getIdentifier();
12902         if (FnI && FnI->isStr("_Block_copy")) {
12903           e = CE->getArg(0)->IgnoreParenCasts();
12904         }
12905       }
12906     }
12907   }
12908 
12909   BlockExpr *block = dyn_cast<BlockExpr>(e);
12910   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12911     return nullptr;
12912 
12913   FindCaptureVisitor visitor(S.Context, owner.Variable);
12914   visitor.Visit(block->getBlockDecl()->getBody());
12915   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12916 }
12917 
12918 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12919                                 RetainCycleOwner &owner) {
12920   assert(capturer);
12921   assert(owner.Variable && owner.Loc.isValid());
12922 
12923   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12924     << owner.Variable << capturer->getSourceRange();
12925   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12926     << owner.Indirect << owner.Range;
12927 }
12928 
12929 /// Check for a keyword selector that starts with the word 'add' or
12930 /// 'set'.
12931 static bool isSetterLikeSelector(Selector sel) {
12932   if (sel.isUnarySelector()) return false;
12933 
12934   StringRef str = sel.getNameForSlot(0);
12935   while (!str.empty() && str.front() == '_') str = str.substr(1);
12936   if (str.startswith("set"))
12937     str = str.substr(3);
12938   else if (str.startswith("add")) {
12939     // Specially whitelist 'addOperationWithBlock:'.
12940     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12941       return false;
12942     str = str.substr(3);
12943   }
12944   else
12945     return false;
12946 
12947   if (str.empty()) return true;
12948   return !isLowercase(str.front());
12949 }
12950 
12951 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12952                                                     ObjCMessageExpr *Message) {
12953   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12954                                                 Message->getReceiverInterface(),
12955                                                 NSAPI::ClassId_NSMutableArray);
12956   if (!IsMutableArray) {
12957     return None;
12958   }
12959 
12960   Selector Sel = Message->getSelector();
12961 
12962   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12963     S.NSAPIObj->getNSArrayMethodKind(Sel);
12964   if (!MKOpt) {
12965     return None;
12966   }
12967 
12968   NSAPI::NSArrayMethodKind MK = *MKOpt;
12969 
12970   switch (MK) {
12971     case NSAPI::NSMutableArr_addObject:
12972     case NSAPI::NSMutableArr_insertObjectAtIndex:
12973     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12974       return 0;
12975     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12976       return 1;
12977 
12978     default:
12979       return None;
12980   }
12981 
12982   return None;
12983 }
12984 
12985 static
12986 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12987                                                   ObjCMessageExpr *Message) {
12988   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12989                                             Message->getReceiverInterface(),
12990                                             NSAPI::ClassId_NSMutableDictionary);
12991   if (!IsMutableDictionary) {
12992     return None;
12993   }
12994 
12995   Selector Sel = Message->getSelector();
12996 
12997   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12998     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12999   if (!MKOpt) {
13000     return None;
13001   }
13002 
13003   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13004 
13005   switch (MK) {
13006     case NSAPI::NSMutableDict_setObjectForKey:
13007     case NSAPI::NSMutableDict_setValueForKey:
13008     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13009       return 0;
13010 
13011     default:
13012       return None;
13013   }
13014 
13015   return None;
13016 }
13017 
13018 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13019   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13020                                                 Message->getReceiverInterface(),
13021                                                 NSAPI::ClassId_NSMutableSet);
13022 
13023   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13024                                             Message->getReceiverInterface(),
13025                                             NSAPI::ClassId_NSMutableOrderedSet);
13026   if (!IsMutableSet && !IsMutableOrderedSet) {
13027     return None;
13028   }
13029 
13030   Selector Sel = Message->getSelector();
13031 
13032   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13033   if (!MKOpt) {
13034     return None;
13035   }
13036 
13037   NSAPI::NSSetMethodKind MK = *MKOpt;
13038 
13039   switch (MK) {
13040     case NSAPI::NSMutableSet_addObject:
13041     case NSAPI::NSOrderedSet_setObjectAtIndex:
13042     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13043     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13044       return 0;
13045     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13046       return 1;
13047   }
13048 
13049   return None;
13050 }
13051 
13052 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13053   if (!Message->isInstanceMessage()) {
13054     return;
13055   }
13056 
13057   Optional<int> ArgOpt;
13058 
13059   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13060       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13061       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13062     return;
13063   }
13064 
13065   int ArgIndex = *ArgOpt;
13066 
13067   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13068   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13069     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13070   }
13071 
13072   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13073     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13074       if (ArgRE->isObjCSelfExpr()) {
13075         Diag(Message->getSourceRange().getBegin(),
13076              diag::warn_objc_circular_container)
13077           << ArgRE->getDecl() << StringRef("'super'");
13078       }
13079     }
13080   } else {
13081     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13082 
13083     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13084       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13085     }
13086 
13087     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13088       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13089         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13090           ValueDecl *Decl = ReceiverRE->getDecl();
13091           Diag(Message->getSourceRange().getBegin(),
13092                diag::warn_objc_circular_container)
13093             << Decl << Decl;
13094           if (!ArgRE->isObjCSelfExpr()) {
13095             Diag(Decl->getLocation(),
13096                  diag::note_objc_circular_container_declared_here)
13097               << Decl;
13098           }
13099         }
13100       }
13101     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13102       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13103         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13104           ObjCIvarDecl *Decl = IvarRE->getDecl();
13105           Diag(Message->getSourceRange().getBegin(),
13106                diag::warn_objc_circular_container)
13107             << Decl << Decl;
13108           Diag(Decl->getLocation(),
13109                diag::note_objc_circular_container_declared_here)
13110             << Decl;
13111         }
13112       }
13113     }
13114   }
13115 }
13116 
13117 /// Check a message send to see if it's likely to cause a retain cycle.
13118 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13119   // Only check instance methods whose selector looks like a setter.
13120   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13121     return;
13122 
13123   // Try to find a variable that the receiver is strongly owned by.
13124   RetainCycleOwner owner;
13125   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13126     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13127       return;
13128   } else {
13129     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13130     owner.Variable = getCurMethodDecl()->getSelfDecl();
13131     owner.Loc = msg->getSuperLoc();
13132     owner.Range = msg->getSuperLoc();
13133   }
13134 
13135   // Check whether the receiver is captured by any of the arguments.
13136   const ObjCMethodDecl *MD = msg->getMethodDecl();
13137   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13138     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13139       // noescape blocks should not be retained by the method.
13140       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13141         continue;
13142       return diagnoseRetainCycle(*this, capturer, owner);
13143     }
13144   }
13145 }
13146 
13147 /// Check a property assign to see if it's likely to cause a retain cycle.
13148 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13149   RetainCycleOwner owner;
13150   if (!findRetainCycleOwner(*this, receiver, owner))
13151     return;
13152 
13153   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13154     diagnoseRetainCycle(*this, capturer, owner);
13155 }
13156 
13157 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13158   RetainCycleOwner Owner;
13159   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13160     return;
13161 
13162   // Because we don't have an expression for the variable, we have to set the
13163   // location explicitly here.
13164   Owner.Loc = Var->getLocation();
13165   Owner.Range = Var->getSourceRange();
13166 
13167   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13168     diagnoseRetainCycle(*this, Capturer, Owner);
13169 }
13170 
13171 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13172                                      Expr *RHS, bool isProperty) {
13173   // Check if RHS is an Objective-C object literal, which also can get
13174   // immediately zapped in a weak reference.  Note that we explicitly
13175   // allow ObjCStringLiterals, since those are designed to never really die.
13176   RHS = RHS->IgnoreParenImpCasts();
13177 
13178   // This enum needs to match with the 'select' in
13179   // warn_objc_arc_literal_assign (off-by-1).
13180   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13181   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13182     return false;
13183 
13184   S.Diag(Loc, diag::warn_arc_literal_assign)
13185     << (unsigned) Kind
13186     << (isProperty ? 0 : 1)
13187     << RHS->getSourceRange();
13188 
13189   return true;
13190 }
13191 
13192 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13193                                     Qualifiers::ObjCLifetime LT,
13194                                     Expr *RHS, bool isProperty) {
13195   // Strip off any implicit cast added to get to the one ARC-specific.
13196   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13197     if (cast->getCastKind() == CK_ARCConsumeObject) {
13198       S.Diag(Loc, diag::warn_arc_retained_assign)
13199         << (LT == Qualifiers::OCL_ExplicitNone)
13200         << (isProperty ? 0 : 1)
13201         << RHS->getSourceRange();
13202       return true;
13203     }
13204     RHS = cast->getSubExpr();
13205   }
13206 
13207   if (LT == Qualifiers::OCL_Weak &&
13208       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13209     return true;
13210 
13211   return false;
13212 }
13213 
13214 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13215                               QualType LHS, Expr *RHS) {
13216   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13217 
13218   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13219     return false;
13220 
13221   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13222     return true;
13223 
13224   return false;
13225 }
13226 
13227 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13228                               Expr *LHS, Expr *RHS) {
13229   QualType LHSType;
13230   // PropertyRef on LHS type need be directly obtained from
13231   // its declaration as it has a PseudoType.
13232   ObjCPropertyRefExpr *PRE
13233     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13234   if (PRE && !PRE->isImplicitProperty()) {
13235     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13236     if (PD)
13237       LHSType = PD->getType();
13238   }
13239 
13240   if (LHSType.isNull())
13241     LHSType = LHS->getType();
13242 
13243   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13244 
13245   if (LT == Qualifiers::OCL_Weak) {
13246     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13247       getCurFunction()->markSafeWeakUse(LHS);
13248   }
13249 
13250   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13251     return;
13252 
13253   // FIXME. Check for other life times.
13254   if (LT != Qualifiers::OCL_None)
13255     return;
13256 
13257   if (PRE) {
13258     if (PRE->isImplicitProperty())
13259       return;
13260     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13261     if (!PD)
13262       return;
13263 
13264     unsigned Attributes = PD->getPropertyAttributes();
13265     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13266       // when 'assign' attribute was not explicitly specified
13267       // by user, ignore it and rely on property type itself
13268       // for lifetime info.
13269       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13270       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13271           LHSType->isObjCRetainableType())
13272         return;
13273 
13274       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13275         if (cast->getCastKind() == CK_ARCConsumeObject) {
13276           Diag(Loc, diag::warn_arc_retained_property_assign)
13277           << RHS->getSourceRange();
13278           return;
13279         }
13280         RHS = cast->getSubExpr();
13281       }
13282     }
13283     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13284       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13285         return;
13286     }
13287   }
13288 }
13289 
13290 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13291 
13292 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13293                                         SourceLocation StmtLoc,
13294                                         const NullStmt *Body) {
13295   // Do not warn if the body is a macro that expands to nothing, e.g:
13296   //
13297   // #define CALL(x)
13298   // if (condition)
13299   //   CALL(0);
13300   if (Body->hasLeadingEmptyMacro())
13301     return false;
13302 
13303   // Get line numbers of statement and body.
13304   bool StmtLineInvalid;
13305   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13306                                                       &StmtLineInvalid);
13307   if (StmtLineInvalid)
13308     return false;
13309 
13310   bool BodyLineInvalid;
13311   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13312                                                       &BodyLineInvalid);
13313   if (BodyLineInvalid)
13314     return false;
13315 
13316   // Warn if null statement and body are on the same line.
13317   if (StmtLine != BodyLine)
13318     return false;
13319 
13320   return true;
13321 }
13322 
13323 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13324                                  const Stmt *Body,
13325                                  unsigned DiagID) {
13326   // Since this is a syntactic check, don't emit diagnostic for template
13327   // instantiations, this just adds noise.
13328   if (CurrentInstantiationScope)
13329     return;
13330 
13331   // The body should be a null statement.
13332   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13333   if (!NBody)
13334     return;
13335 
13336   // Do the usual checks.
13337   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13338     return;
13339 
13340   Diag(NBody->getSemiLoc(), DiagID);
13341   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13342 }
13343 
13344 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13345                                  const Stmt *PossibleBody) {
13346   assert(!CurrentInstantiationScope); // Ensured by caller
13347 
13348   SourceLocation StmtLoc;
13349   const Stmt *Body;
13350   unsigned DiagID;
13351   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13352     StmtLoc = FS->getRParenLoc();
13353     Body = FS->getBody();
13354     DiagID = diag::warn_empty_for_body;
13355   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13356     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13357     Body = WS->getBody();
13358     DiagID = diag::warn_empty_while_body;
13359   } else
13360     return; // Neither `for' nor `while'.
13361 
13362   // The body should be a null statement.
13363   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13364   if (!NBody)
13365     return;
13366 
13367   // Skip expensive checks if diagnostic is disabled.
13368   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13369     return;
13370 
13371   // Do the usual checks.
13372   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13373     return;
13374 
13375   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13376   // noise level low, emit diagnostics only if for/while is followed by a
13377   // CompoundStmt, e.g.:
13378   //    for (int i = 0; i < n; i++);
13379   //    {
13380   //      a(i);
13381   //    }
13382   // or if for/while is followed by a statement with more indentation
13383   // than for/while itself:
13384   //    for (int i = 0; i < n; i++);
13385   //      a(i);
13386   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13387   if (!ProbableTypo) {
13388     bool BodyColInvalid;
13389     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13390         PossibleBody->getBeginLoc(), &BodyColInvalid);
13391     if (BodyColInvalid)
13392       return;
13393 
13394     bool StmtColInvalid;
13395     unsigned StmtCol =
13396         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13397     if (StmtColInvalid)
13398       return;
13399 
13400     if (BodyCol > StmtCol)
13401       ProbableTypo = true;
13402   }
13403 
13404   if (ProbableTypo) {
13405     Diag(NBody->getSemiLoc(), DiagID);
13406     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13407   }
13408 }
13409 
13410 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13411 
13412 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13413 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13414                              SourceLocation OpLoc) {
13415   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13416     return;
13417 
13418   if (inTemplateInstantiation())
13419     return;
13420 
13421   // Strip parens and casts away.
13422   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13423   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13424 
13425   // Check for a call expression
13426   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13427   if (!CE || CE->getNumArgs() != 1)
13428     return;
13429 
13430   // Check for a call to std::move
13431   if (!CE->isCallToStdMove())
13432     return;
13433 
13434   // Get argument from std::move
13435   RHSExpr = CE->getArg(0);
13436 
13437   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13438   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13439 
13440   // Two DeclRefExpr's, check that the decls are the same.
13441   if (LHSDeclRef && RHSDeclRef) {
13442     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13443       return;
13444     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13445         RHSDeclRef->getDecl()->getCanonicalDecl())
13446       return;
13447 
13448     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13449                                         << LHSExpr->getSourceRange()
13450                                         << RHSExpr->getSourceRange();
13451     return;
13452   }
13453 
13454   // Member variables require a different approach to check for self moves.
13455   // MemberExpr's are the same if every nested MemberExpr refers to the same
13456   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13457   // the base Expr's are CXXThisExpr's.
13458   const Expr *LHSBase = LHSExpr;
13459   const Expr *RHSBase = RHSExpr;
13460   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13461   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13462   if (!LHSME || !RHSME)
13463     return;
13464 
13465   while (LHSME && RHSME) {
13466     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13467         RHSME->getMemberDecl()->getCanonicalDecl())
13468       return;
13469 
13470     LHSBase = LHSME->getBase();
13471     RHSBase = RHSME->getBase();
13472     LHSME = dyn_cast<MemberExpr>(LHSBase);
13473     RHSME = dyn_cast<MemberExpr>(RHSBase);
13474   }
13475 
13476   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13477   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13478   if (LHSDeclRef && RHSDeclRef) {
13479     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13480       return;
13481     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13482         RHSDeclRef->getDecl()->getCanonicalDecl())
13483       return;
13484 
13485     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13486                                         << LHSExpr->getSourceRange()
13487                                         << RHSExpr->getSourceRange();
13488     return;
13489   }
13490 
13491   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13492     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13493                                         << LHSExpr->getSourceRange()
13494                                         << RHSExpr->getSourceRange();
13495 }
13496 
13497 //===--- Layout compatibility ----------------------------------------------//
13498 
13499 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13500 
13501 /// Check if two enumeration types are layout-compatible.
13502 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13503   // C++11 [dcl.enum] p8:
13504   // Two enumeration types are layout-compatible if they have the same
13505   // underlying type.
13506   return ED1->isComplete() && ED2->isComplete() &&
13507          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13508 }
13509 
13510 /// Check if two fields are layout-compatible.
13511 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13512                                FieldDecl *Field2) {
13513   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13514     return false;
13515 
13516   if (Field1->isBitField() != Field2->isBitField())
13517     return false;
13518 
13519   if (Field1->isBitField()) {
13520     // Make sure that the bit-fields are the same length.
13521     unsigned Bits1 = Field1->getBitWidthValue(C);
13522     unsigned Bits2 = Field2->getBitWidthValue(C);
13523 
13524     if (Bits1 != Bits2)
13525       return false;
13526   }
13527 
13528   return true;
13529 }
13530 
13531 /// Check if two standard-layout structs are layout-compatible.
13532 /// (C++11 [class.mem] p17)
13533 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13534                                      RecordDecl *RD2) {
13535   // If both records are C++ classes, check that base classes match.
13536   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13537     // If one of records is a CXXRecordDecl we are in C++ mode,
13538     // thus the other one is a CXXRecordDecl, too.
13539     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13540     // Check number of base classes.
13541     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13542       return false;
13543 
13544     // Check the base classes.
13545     for (CXXRecordDecl::base_class_const_iterator
13546                Base1 = D1CXX->bases_begin(),
13547            BaseEnd1 = D1CXX->bases_end(),
13548               Base2 = D2CXX->bases_begin();
13549          Base1 != BaseEnd1;
13550          ++Base1, ++Base2) {
13551       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13552         return false;
13553     }
13554   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13555     // If only RD2 is a C++ class, it should have zero base classes.
13556     if (D2CXX->getNumBases() > 0)
13557       return false;
13558   }
13559 
13560   // Check the fields.
13561   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13562                              Field2End = RD2->field_end(),
13563                              Field1 = RD1->field_begin(),
13564                              Field1End = RD1->field_end();
13565   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13566     if (!isLayoutCompatible(C, *Field1, *Field2))
13567       return false;
13568   }
13569   if (Field1 != Field1End || Field2 != Field2End)
13570     return false;
13571 
13572   return true;
13573 }
13574 
13575 /// Check if two standard-layout unions are layout-compatible.
13576 /// (C++11 [class.mem] p18)
13577 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13578                                     RecordDecl *RD2) {
13579   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13580   for (auto *Field2 : RD2->fields())
13581     UnmatchedFields.insert(Field2);
13582 
13583   for (auto *Field1 : RD1->fields()) {
13584     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13585         I = UnmatchedFields.begin(),
13586         E = UnmatchedFields.end();
13587 
13588     for ( ; I != E; ++I) {
13589       if (isLayoutCompatible(C, Field1, *I)) {
13590         bool Result = UnmatchedFields.erase(*I);
13591         (void) Result;
13592         assert(Result);
13593         break;
13594       }
13595     }
13596     if (I == E)
13597       return false;
13598   }
13599 
13600   return UnmatchedFields.empty();
13601 }
13602 
13603 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13604                                RecordDecl *RD2) {
13605   if (RD1->isUnion() != RD2->isUnion())
13606     return false;
13607 
13608   if (RD1->isUnion())
13609     return isLayoutCompatibleUnion(C, RD1, RD2);
13610   else
13611     return isLayoutCompatibleStruct(C, RD1, RD2);
13612 }
13613 
13614 /// Check if two types are layout-compatible in C++11 sense.
13615 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13616   if (T1.isNull() || T2.isNull())
13617     return false;
13618 
13619   // C++11 [basic.types] p11:
13620   // If two types T1 and T2 are the same type, then T1 and T2 are
13621   // layout-compatible types.
13622   if (C.hasSameType(T1, T2))
13623     return true;
13624 
13625   T1 = T1.getCanonicalType().getUnqualifiedType();
13626   T2 = T2.getCanonicalType().getUnqualifiedType();
13627 
13628   const Type::TypeClass TC1 = T1->getTypeClass();
13629   const Type::TypeClass TC2 = T2->getTypeClass();
13630 
13631   if (TC1 != TC2)
13632     return false;
13633 
13634   if (TC1 == Type::Enum) {
13635     return isLayoutCompatible(C,
13636                               cast<EnumType>(T1)->getDecl(),
13637                               cast<EnumType>(T2)->getDecl());
13638   } else if (TC1 == Type::Record) {
13639     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13640       return false;
13641 
13642     return isLayoutCompatible(C,
13643                               cast<RecordType>(T1)->getDecl(),
13644                               cast<RecordType>(T2)->getDecl());
13645   }
13646 
13647   return false;
13648 }
13649 
13650 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13651 
13652 /// Given a type tag expression find the type tag itself.
13653 ///
13654 /// \param TypeExpr Type tag expression, as it appears in user's code.
13655 ///
13656 /// \param VD Declaration of an identifier that appears in a type tag.
13657 ///
13658 /// \param MagicValue Type tag magic value.
13659 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13660                             const ValueDecl **VD, uint64_t *MagicValue) {
13661   while(true) {
13662     if (!TypeExpr)
13663       return false;
13664 
13665     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13666 
13667     switch (TypeExpr->getStmtClass()) {
13668     case Stmt::UnaryOperatorClass: {
13669       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13670       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13671         TypeExpr = UO->getSubExpr();
13672         continue;
13673       }
13674       return false;
13675     }
13676 
13677     case Stmt::DeclRefExprClass: {
13678       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13679       *VD = DRE->getDecl();
13680       return true;
13681     }
13682 
13683     case Stmt::IntegerLiteralClass: {
13684       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13685       llvm::APInt MagicValueAPInt = IL->getValue();
13686       if (MagicValueAPInt.getActiveBits() <= 64) {
13687         *MagicValue = MagicValueAPInt.getZExtValue();
13688         return true;
13689       } else
13690         return false;
13691     }
13692 
13693     case Stmt::BinaryConditionalOperatorClass:
13694     case Stmt::ConditionalOperatorClass: {
13695       const AbstractConditionalOperator *ACO =
13696           cast<AbstractConditionalOperator>(TypeExpr);
13697       bool Result;
13698       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13699         if (Result)
13700           TypeExpr = ACO->getTrueExpr();
13701         else
13702           TypeExpr = ACO->getFalseExpr();
13703         continue;
13704       }
13705       return false;
13706     }
13707 
13708     case Stmt::BinaryOperatorClass: {
13709       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13710       if (BO->getOpcode() == BO_Comma) {
13711         TypeExpr = BO->getRHS();
13712         continue;
13713       }
13714       return false;
13715     }
13716 
13717     default:
13718       return false;
13719     }
13720   }
13721 }
13722 
13723 /// Retrieve the C type corresponding to type tag TypeExpr.
13724 ///
13725 /// \param TypeExpr Expression that specifies a type tag.
13726 ///
13727 /// \param MagicValues Registered magic values.
13728 ///
13729 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13730 ///        kind.
13731 ///
13732 /// \param TypeInfo Information about the corresponding C type.
13733 ///
13734 /// \returns true if the corresponding C type was found.
13735 static bool GetMatchingCType(
13736         const IdentifierInfo *ArgumentKind,
13737         const Expr *TypeExpr, const ASTContext &Ctx,
13738         const llvm::DenseMap<Sema::TypeTagMagicValue,
13739                              Sema::TypeTagData> *MagicValues,
13740         bool &FoundWrongKind,
13741         Sema::TypeTagData &TypeInfo) {
13742   FoundWrongKind = false;
13743 
13744   // Variable declaration that has type_tag_for_datatype attribute.
13745   const ValueDecl *VD = nullptr;
13746 
13747   uint64_t MagicValue;
13748 
13749   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13750     return false;
13751 
13752   if (VD) {
13753     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13754       if (I->getArgumentKind() != ArgumentKind) {
13755         FoundWrongKind = true;
13756         return false;
13757       }
13758       TypeInfo.Type = I->getMatchingCType();
13759       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13760       TypeInfo.MustBeNull = I->getMustBeNull();
13761       return true;
13762     }
13763     return false;
13764   }
13765 
13766   if (!MagicValues)
13767     return false;
13768 
13769   llvm::DenseMap<Sema::TypeTagMagicValue,
13770                  Sema::TypeTagData>::const_iterator I =
13771       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13772   if (I == MagicValues->end())
13773     return false;
13774 
13775   TypeInfo = I->second;
13776   return true;
13777 }
13778 
13779 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13780                                       uint64_t MagicValue, QualType Type,
13781                                       bool LayoutCompatible,
13782                                       bool MustBeNull) {
13783   if (!TypeTagForDatatypeMagicValues)
13784     TypeTagForDatatypeMagicValues.reset(
13785         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13786 
13787   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13788   (*TypeTagForDatatypeMagicValues)[Magic] =
13789       TypeTagData(Type, LayoutCompatible, MustBeNull);
13790 }
13791 
13792 static bool IsSameCharType(QualType T1, QualType T2) {
13793   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13794   if (!BT1)
13795     return false;
13796 
13797   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13798   if (!BT2)
13799     return false;
13800 
13801   BuiltinType::Kind T1Kind = BT1->getKind();
13802   BuiltinType::Kind T2Kind = BT2->getKind();
13803 
13804   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13805          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13806          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13807          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13808 }
13809 
13810 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13811                                     const ArrayRef<const Expr *> ExprArgs,
13812                                     SourceLocation CallSiteLoc) {
13813   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13814   bool IsPointerAttr = Attr->getIsPointer();
13815 
13816   // Retrieve the argument representing the 'type_tag'.
13817   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13818   if (TypeTagIdxAST >= ExprArgs.size()) {
13819     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13820         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13821     return;
13822   }
13823   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13824   bool FoundWrongKind;
13825   TypeTagData TypeInfo;
13826   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13827                         TypeTagForDatatypeMagicValues.get(),
13828                         FoundWrongKind, TypeInfo)) {
13829     if (FoundWrongKind)
13830       Diag(TypeTagExpr->getExprLoc(),
13831            diag::warn_type_tag_for_datatype_wrong_kind)
13832         << TypeTagExpr->getSourceRange();
13833     return;
13834   }
13835 
13836   // Retrieve the argument representing the 'arg_idx'.
13837   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13838   if (ArgumentIdxAST >= ExprArgs.size()) {
13839     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13840         << 1 << Attr->getArgumentIdx().getSourceIndex();
13841     return;
13842   }
13843   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
13844   if (IsPointerAttr) {
13845     // Skip implicit cast of pointer to `void *' (as a function argument).
13846     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
13847       if (ICE->getType()->isVoidPointerType() &&
13848           ICE->getCastKind() == CK_BitCast)
13849         ArgumentExpr = ICE->getSubExpr();
13850   }
13851   QualType ArgumentType = ArgumentExpr->getType();
13852 
13853   // Passing a `void*' pointer shouldn't trigger a warning.
13854   if (IsPointerAttr && ArgumentType->isVoidPointerType())
13855     return;
13856 
13857   if (TypeInfo.MustBeNull) {
13858     // Type tag with matching void type requires a null pointer.
13859     if (!ArgumentExpr->isNullPointerConstant(Context,
13860                                              Expr::NPC_ValueDependentIsNotNull)) {
13861       Diag(ArgumentExpr->getExprLoc(),
13862            diag::warn_type_safety_null_pointer_required)
13863           << ArgumentKind->getName()
13864           << ArgumentExpr->getSourceRange()
13865           << TypeTagExpr->getSourceRange();
13866     }
13867     return;
13868   }
13869 
13870   QualType RequiredType = TypeInfo.Type;
13871   if (IsPointerAttr)
13872     RequiredType = Context.getPointerType(RequiredType);
13873 
13874   bool mismatch = false;
13875   if (!TypeInfo.LayoutCompatible) {
13876     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13877 
13878     // C++11 [basic.fundamental] p1:
13879     // Plain char, signed char, and unsigned char are three distinct types.
13880     //
13881     // But we treat plain `char' as equivalent to `signed char' or `unsigned
13882     // char' depending on the current char signedness mode.
13883     if (mismatch)
13884       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13885                                            RequiredType->getPointeeType())) ||
13886           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13887         mismatch = false;
13888   } else
13889     if (IsPointerAttr)
13890       mismatch = !isLayoutCompatible(Context,
13891                                      ArgumentType->getPointeeType(),
13892                                      RequiredType->getPointeeType());
13893     else
13894       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13895 
13896   if (mismatch)
13897     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13898         << ArgumentType << ArgumentKind
13899         << TypeInfo.LayoutCompatible << RequiredType
13900         << ArgumentExpr->getSourceRange()
13901         << TypeTagExpr->getSourceRange();
13902 }
13903 
13904 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13905                                          CharUnits Alignment) {
13906   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13907 }
13908 
13909 void Sema::DiagnoseMisalignedMembers() {
13910   for (MisalignedMember &m : MisalignedMembers) {
13911     const NamedDecl *ND = m.RD;
13912     if (ND->getName().empty()) {
13913       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13914         ND = TD;
13915     }
13916     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
13917         << m.MD << ND << m.E->getSourceRange();
13918   }
13919   MisalignedMembers.clear();
13920 }
13921 
13922 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13923   E = E->IgnoreParens();
13924   if (!T->isPointerType() && !T->isIntegerType())
13925     return;
13926   if (isa<UnaryOperator>(E) &&
13927       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13928     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13929     if (isa<MemberExpr>(Op)) {
13930       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
13931       if (MA != MisalignedMembers.end() &&
13932           (T->isIntegerType() ||
13933            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13934                                    Context.getTypeAlignInChars(
13935                                        T->getPointeeType()) <= MA->Alignment))))
13936         MisalignedMembers.erase(MA);
13937     }
13938   }
13939 }
13940 
13941 void Sema::RefersToMemberWithReducedAlignment(
13942     Expr *E,
13943     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13944         Action) {
13945   const auto *ME = dyn_cast<MemberExpr>(E);
13946   if (!ME)
13947     return;
13948 
13949   // No need to check expressions with an __unaligned-qualified type.
13950   if (E->getType().getQualifiers().hasUnaligned())
13951     return;
13952 
13953   // For a chain of MemberExpr like "a.b.c.d" this list
13954   // will keep FieldDecl's like [d, c, b].
13955   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13956   const MemberExpr *TopME = nullptr;
13957   bool AnyIsPacked = false;
13958   do {
13959     QualType BaseType = ME->getBase()->getType();
13960     if (ME->isArrow())
13961       BaseType = BaseType->getPointeeType();
13962     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13963     if (RD->isInvalidDecl())
13964       return;
13965 
13966     ValueDecl *MD = ME->getMemberDecl();
13967     auto *FD = dyn_cast<FieldDecl>(MD);
13968     // We do not care about non-data members.
13969     if (!FD || FD->isInvalidDecl())
13970       return;
13971 
13972     AnyIsPacked =
13973         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13974     ReverseMemberChain.push_back(FD);
13975 
13976     TopME = ME;
13977     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13978   } while (ME);
13979   assert(TopME && "We did not compute a topmost MemberExpr!");
13980 
13981   // Not the scope of this diagnostic.
13982   if (!AnyIsPacked)
13983     return;
13984 
13985   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13986   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13987   // TODO: The innermost base of the member expression may be too complicated.
13988   // For now, just disregard these cases. This is left for future
13989   // improvement.
13990   if (!DRE && !isa<CXXThisExpr>(TopBase))
13991       return;
13992 
13993   // Alignment expected by the whole expression.
13994   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13995 
13996   // No need to do anything else with this case.
13997   if (ExpectedAlignment.isOne())
13998     return;
13999 
14000   // Synthesize offset of the whole access.
14001   CharUnits Offset;
14002   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14003        I++) {
14004     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14005   }
14006 
14007   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14008   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14009       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14010 
14011   // The base expression of the innermost MemberExpr may give
14012   // stronger guarantees than the class containing the member.
14013   if (DRE && !TopME->isArrow()) {
14014     const ValueDecl *VD = DRE->getDecl();
14015     if (!VD->getType()->isReferenceType())
14016       CompleteObjectAlignment =
14017           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14018   }
14019 
14020   // Check if the synthesized offset fulfills the alignment.
14021   if (Offset % ExpectedAlignment != 0 ||
14022       // It may fulfill the offset it but the effective alignment may still be
14023       // lower than the expected expression alignment.
14024       CompleteObjectAlignment < ExpectedAlignment) {
14025     // If this happens, we want to determine a sensible culprit of this.
14026     // Intuitively, watching the chain of member expressions from right to
14027     // left, we start with the required alignment (as required by the field
14028     // type) but some packed attribute in that chain has reduced the alignment.
14029     // It may happen that another packed structure increases it again. But if
14030     // we are here such increase has not been enough. So pointing the first
14031     // FieldDecl that either is packed or else its RecordDecl is,
14032     // seems reasonable.
14033     FieldDecl *FD = nullptr;
14034     CharUnits Alignment;
14035     for (FieldDecl *FDI : ReverseMemberChain) {
14036       if (FDI->hasAttr<PackedAttr>() ||
14037           FDI->getParent()->hasAttr<PackedAttr>()) {
14038         FD = FDI;
14039         Alignment = std::min(
14040             Context.getTypeAlignInChars(FD->getType()),
14041             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14042         break;
14043       }
14044     }
14045     assert(FD && "We did not find a packed FieldDecl!");
14046     Action(E, FD->getParent(), FD, Alignment);
14047   }
14048 }
14049 
14050 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14051   using namespace std::placeholders;
14052 
14053   RefersToMemberWithReducedAlignment(
14054       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14055                      _2, _3, _4));
14056 }
14057