1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/SaveAndRestore.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116            << 0 /*function call*/ << desiredArgCount << argCount
117            << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121                     call->getArg(argCount - 1)->getEndLoc());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139         << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148         << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 /// Check the number of arguments and set the result type to
195 /// the argument type.
196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197   if (checkArgCount(S, TheCall, 1))
198     return true;
199 
200   TheCall->setType(TheCall->getArg(0)->getType());
201   return false;
202 }
203 
204 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
205   if (checkArgCount(S, TheCall, 3))
206     return true;
207 
208   // First two arguments should be integers.
209   for (unsigned I = 0; I < 2; ++I) {
210     ExprResult Arg = TheCall->getArg(I);
211     QualType Ty = Arg.get()->getType();
212     if (!Ty->isIntegerType()) {
213       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
214           << Ty << Arg.get()->getSourceRange();
215       return true;
216     }
217     InitializedEntity Entity = InitializedEntity::InitializeParameter(
218         S.getASTContext(), Ty, /*consume*/ false);
219     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
220     if (Arg.isInvalid())
221       return true;
222     TheCall->setArg(I, Arg.get());
223   }
224 
225   // Third argument should be a pointer to a non-const integer.
226   // IRGen correctly handles volatile, restrict, and address spaces, and
227   // the other qualifiers aren't possible.
228   {
229     ExprResult Arg = TheCall->getArg(2);
230     QualType Ty = Arg.get()->getType();
231     const auto *PtrTy = Ty->getAs<PointerType>();
232     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
233           !PtrTy->getPointeeType().isConstQualified())) {
234       S.Diag(Arg.get()->getBeginLoc(),
235              diag::err_overflow_builtin_must_be_ptr_int)
236           << Ty << Arg.get()->getSourceRange();
237       return true;
238     }
239     InitializedEntity Entity = InitializedEntity::InitializeParameter(
240         S.getASTContext(), Ty, /*consume*/ false);
241     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
242     if (Arg.isInvalid())
243       return true;
244     TheCall->setArg(2, Arg.get());
245   }
246   return false;
247 }
248 
249 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
250   if (checkArgCount(S, BuiltinCall, 2))
251     return true;
252 
253   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
254   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
255   Expr *Call = BuiltinCall->getArg(0);
256   Expr *Chain = BuiltinCall->getArg(1);
257 
258   if (Call->getStmtClass() != Stmt::CallExprClass) {
259     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
260         << Call->getSourceRange();
261     return true;
262   }
263 
264   auto CE = cast<CallExpr>(Call);
265   if (CE->getCallee()->getType()->isBlockPointerType()) {
266     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
267         << Call->getSourceRange();
268     return true;
269   }
270 
271   const Decl *TargetDecl = CE->getCalleeDecl();
272   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
273     if (FD->getBuiltinID()) {
274       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
275           << Call->getSourceRange();
276       return true;
277     }
278 
279   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
280     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
281         << Call->getSourceRange();
282     return true;
283   }
284 
285   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
286   if (ChainResult.isInvalid())
287     return true;
288   if (!ChainResult.get()->getType()->isPointerType()) {
289     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
290         << Chain->getSourceRange();
291     return true;
292   }
293 
294   QualType ReturnTy = CE->getCallReturnType(S.Context);
295   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
296   QualType BuiltinTy = S.Context.getFunctionType(
297       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
298   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
299 
300   Builtin =
301       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
302 
303   BuiltinCall->setType(CE->getType());
304   BuiltinCall->setValueKind(CE->getValueKind());
305   BuiltinCall->setObjectKind(CE->getObjectKind());
306   BuiltinCall->setCallee(Builtin);
307   BuiltinCall->setArg(1, ChainResult.get());
308 
309   return false;
310 }
311 
312 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
313 /// __builtin_*_chk function, then use the object size argument specified in the
314 /// source. Otherwise, infer the object size using __builtin_object_size.
315 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
316                                                CallExpr *TheCall) {
317   // FIXME: There are some more useful checks we could be doing here:
318   //  - Analyze the format string of sprintf to see how much of buffer is used.
319   //  - Evaluate strlen of strcpy arguments, use as object size.
320 
321   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
322       isConstantEvaluated())
323     return;
324 
325   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
326   if (!BuiltinID)
327     return;
328 
329   unsigned DiagID = 0;
330   bool IsChkVariant = false;
331   unsigned SizeIndex, ObjectIndex;
332   switch (BuiltinID) {
333   default:
334     return;
335   case Builtin::BI__builtin___memcpy_chk:
336   case Builtin::BI__builtin___memmove_chk:
337   case Builtin::BI__builtin___memset_chk:
338   case Builtin::BI__builtin___strlcat_chk:
339   case Builtin::BI__builtin___strlcpy_chk:
340   case Builtin::BI__builtin___strncat_chk:
341   case Builtin::BI__builtin___strncpy_chk:
342   case Builtin::BI__builtin___stpncpy_chk:
343   case Builtin::BI__builtin___memccpy_chk: {
344     DiagID = diag::warn_builtin_chk_overflow;
345     IsChkVariant = true;
346     SizeIndex = TheCall->getNumArgs() - 2;
347     ObjectIndex = TheCall->getNumArgs() - 1;
348     break;
349   }
350 
351   case Builtin::BI__builtin___snprintf_chk:
352   case Builtin::BI__builtin___vsnprintf_chk: {
353     DiagID = diag::warn_builtin_chk_overflow;
354     IsChkVariant = true;
355     SizeIndex = 1;
356     ObjectIndex = 3;
357     break;
358   }
359 
360   case Builtin::BIstrncat:
361   case Builtin::BI__builtin_strncat:
362   case Builtin::BIstrncpy:
363   case Builtin::BI__builtin_strncpy:
364   case Builtin::BIstpncpy:
365   case Builtin::BI__builtin_stpncpy: {
366     // Whether these functions overflow depends on the runtime strlen of the
367     // string, not just the buffer size, so emitting the "always overflow"
368     // diagnostic isn't quite right. We should still diagnose passing a buffer
369     // size larger than the destination buffer though; this is a runtime abort
370     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
371     DiagID = diag::warn_fortify_source_size_mismatch;
372     SizeIndex = TheCall->getNumArgs() - 1;
373     ObjectIndex = 0;
374     break;
375   }
376 
377   case Builtin::BImemcpy:
378   case Builtin::BI__builtin_memcpy:
379   case Builtin::BImemmove:
380   case Builtin::BI__builtin_memmove:
381   case Builtin::BImemset:
382   case Builtin::BI__builtin_memset: {
383     DiagID = diag::warn_fortify_source_overflow;
384     SizeIndex = TheCall->getNumArgs() - 1;
385     ObjectIndex = 0;
386     break;
387   }
388   case Builtin::BIsnprintf:
389   case Builtin::BI__builtin_snprintf:
390   case Builtin::BIvsnprintf:
391   case Builtin::BI__builtin_vsnprintf: {
392     DiagID = diag::warn_fortify_source_size_mismatch;
393     SizeIndex = 1;
394     ObjectIndex = 0;
395     break;
396   }
397   }
398 
399   llvm::APSInt ObjectSize;
400   // For __builtin___*_chk, the object size is explicitly provided by the caller
401   // (usually using __builtin_object_size). Use that value to check this call.
402   if (IsChkVariant) {
403     Expr::EvalResult Result;
404     Expr *SizeArg = TheCall->getArg(ObjectIndex);
405     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
406       return;
407     ObjectSize = Result.Val.getInt();
408 
409   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
410   } else {
411     // If the parameter has a pass_object_size attribute, then we should use its
412     // (potentially) more strict checking mode. Otherwise, conservatively assume
413     // type 0.
414     int BOSType = 0;
415     if (const auto *POS =
416             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
417       BOSType = POS->getType();
418 
419     Expr *ObjArg = TheCall->getArg(ObjectIndex);
420     uint64_t Result;
421     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
422       return;
423     // Get the object size in the target's size_t width.
424     const TargetInfo &TI = getASTContext().getTargetInfo();
425     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
426     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
427   }
428 
429   // Evaluate the number of bytes of the object that this call will use.
430   Expr::EvalResult Result;
431   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
432   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
433     return;
434   llvm::APSInt UsedSize = Result.Val.getInt();
435 
436   if (UsedSize.ule(ObjectSize))
437     return;
438 
439   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
440   // Skim off the details of whichever builtin was called to produce a better
441   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
442   if (IsChkVariant) {
443     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
444     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
445   } else if (FunctionName.startswith("__builtin_")) {
446     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
447   }
448 
449   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
450                       PDiag(DiagID)
451                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
452                           << UsedSize.toString(/*Radix=*/10));
453 }
454 
455 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
456                                      Scope::ScopeFlags NeededScopeFlags,
457                                      unsigned DiagID) {
458   // Scopes aren't available during instantiation. Fortunately, builtin
459   // functions cannot be template args so they cannot be formed through template
460   // instantiation. Therefore checking once during the parse is sufficient.
461   if (SemaRef.inTemplateInstantiation())
462     return false;
463 
464   Scope *S = SemaRef.getCurScope();
465   while (S && !S->isSEHExceptScope())
466     S = S->getParent();
467   if (!S || !(S->getFlags() & NeededScopeFlags)) {
468     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
469     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
470         << DRE->getDecl()->getIdentifier();
471     return true;
472   }
473 
474   return false;
475 }
476 
477 static inline bool isBlockPointer(Expr *Arg) {
478   return Arg->getType()->isBlockPointerType();
479 }
480 
481 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
482 /// void*, which is a requirement of device side enqueue.
483 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
484   const BlockPointerType *BPT =
485       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
486   ArrayRef<QualType> Params =
487       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
488   unsigned ArgCounter = 0;
489   bool IllegalParams = false;
490   // Iterate through the block parameters until either one is found that is not
491   // a local void*, or the block is valid.
492   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
493        I != E; ++I, ++ArgCounter) {
494     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
495         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
496             LangAS::opencl_local) {
497       // Get the location of the error. If a block literal has been passed
498       // (BlockExpr) then we can point straight to the offending argument,
499       // else we just point to the variable reference.
500       SourceLocation ErrorLoc;
501       if (isa<BlockExpr>(BlockArg)) {
502         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
503         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
504       } else if (isa<DeclRefExpr>(BlockArg)) {
505         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
506       }
507       S.Diag(ErrorLoc,
508              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
509       IllegalParams = true;
510     }
511   }
512 
513   return IllegalParams;
514 }
515 
516 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
517   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
518     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
519         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
520     return true;
521   }
522   return false;
523 }
524 
525 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
526   if (checkArgCount(S, TheCall, 2))
527     return true;
528 
529   if (checkOpenCLSubgroupExt(S, TheCall))
530     return true;
531 
532   // First argument is an ndrange_t type.
533   Expr *NDRangeArg = TheCall->getArg(0);
534   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
535     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
536         << TheCall->getDirectCallee() << "'ndrange_t'";
537     return true;
538   }
539 
540   Expr *BlockArg = TheCall->getArg(1);
541   if (!isBlockPointer(BlockArg)) {
542     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
543         << TheCall->getDirectCallee() << "block";
544     return true;
545   }
546   return checkOpenCLBlockArgs(S, BlockArg);
547 }
548 
549 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
550 /// get_kernel_work_group_size
551 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
552 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
553   if (checkArgCount(S, TheCall, 1))
554     return true;
555 
556   Expr *BlockArg = TheCall->getArg(0);
557   if (!isBlockPointer(BlockArg)) {
558     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
559         << TheCall->getDirectCallee() << "block";
560     return true;
561   }
562   return checkOpenCLBlockArgs(S, BlockArg);
563 }
564 
565 /// Diagnose integer type and any valid implicit conversion to it.
566 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
567                                       const QualType &IntType);
568 
569 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
570                                             unsigned Start, unsigned End) {
571   bool IllegalParams = false;
572   for (unsigned I = Start; I <= End; ++I)
573     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
574                                               S.Context.getSizeType());
575   return IllegalParams;
576 }
577 
578 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
579 /// 'local void*' parameter of passed block.
580 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
581                                            Expr *BlockArg,
582                                            unsigned NumNonVarArgs) {
583   const BlockPointerType *BPT =
584       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
585   unsigned NumBlockParams =
586       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
587   unsigned TotalNumArgs = TheCall->getNumArgs();
588 
589   // For each argument passed to the block, a corresponding uint needs to
590   // be passed to describe the size of the local memory.
591   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
592     S.Diag(TheCall->getBeginLoc(),
593            diag::err_opencl_enqueue_kernel_local_size_args);
594     return true;
595   }
596 
597   // Check that the sizes of the local memory are specified by integers.
598   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
599                                          TotalNumArgs - 1);
600 }
601 
602 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
603 /// overload formats specified in Table 6.13.17.1.
604 /// int enqueue_kernel(queue_t queue,
605 ///                    kernel_enqueue_flags_t flags,
606 ///                    const ndrange_t ndrange,
607 ///                    void (^block)(void))
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)(void))
615 /// int enqueue_kernel(queue_t queue,
616 ///                    kernel_enqueue_flags_t flags,
617 ///                    const ndrange_t ndrange,
618 ///                    void (^block)(local void*, ...),
619 ///                    uint size0, ...)
620 /// int enqueue_kernel(queue_t queue,
621 ///                    kernel_enqueue_flags_t flags,
622 ///                    const ndrange_t ndrange,
623 ///                    uint num_events_in_wait_list,
624 ///                    clk_event_t *event_wait_list,
625 ///                    clk_event_t *event_ret,
626 ///                    void (^block)(local void*, ...),
627 ///                    uint size0, ...)
628 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
629   unsigned NumArgs = TheCall->getNumArgs();
630 
631   if (NumArgs < 4) {
632     S.Diag(TheCall->getBeginLoc(),
633            diag::err_typecheck_call_too_few_args_at_least)
634         << 0 << 4 << NumArgs;
635     return true;
636   }
637 
638   Expr *Arg0 = TheCall->getArg(0);
639   Expr *Arg1 = TheCall->getArg(1);
640   Expr *Arg2 = TheCall->getArg(2);
641   Expr *Arg3 = TheCall->getArg(3);
642 
643   // First argument always needs to be a queue_t type.
644   if (!Arg0->getType()->isQueueT()) {
645     S.Diag(TheCall->getArg(0)->getBeginLoc(),
646            diag::err_opencl_builtin_expected_type)
647         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
648     return true;
649   }
650 
651   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
652   if (!Arg1->getType()->isIntegerType()) {
653     S.Diag(TheCall->getArg(1)->getBeginLoc(),
654            diag::err_opencl_builtin_expected_type)
655         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
656     return true;
657   }
658 
659   // Third argument is always an ndrange_t type.
660   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
661     S.Diag(TheCall->getArg(2)->getBeginLoc(),
662            diag::err_opencl_builtin_expected_type)
663         << TheCall->getDirectCallee() << "'ndrange_t'";
664     return true;
665   }
666 
667   // With four arguments, there is only one form that the function could be
668   // called in: no events and no variable arguments.
669   if (NumArgs == 4) {
670     // check that the last argument is the right block type.
671     if (!isBlockPointer(Arg3)) {
672       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
673           << TheCall->getDirectCallee() << "block";
674       return true;
675     }
676     // we have a block type, check the prototype
677     const BlockPointerType *BPT =
678         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
679     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
680       S.Diag(Arg3->getBeginLoc(),
681              diag::err_opencl_enqueue_kernel_blocks_no_args);
682       return true;
683     }
684     return false;
685   }
686   // we can have block + varargs.
687   if (isBlockPointer(Arg3))
688     return (checkOpenCLBlockArgs(S, Arg3) ||
689             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
690   // last two cases with either exactly 7 args or 7 args and varargs.
691   if (NumArgs >= 7) {
692     // check common block argument.
693     Expr *Arg6 = TheCall->getArg(6);
694     if (!isBlockPointer(Arg6)) {
695       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
696           << TheCall->getDirectCallee() << "block";
697       return true;
698     }
699     if (checkOpenCLBlockArgs(S, Arg6))
700       return true;
701 
702     // Forth argument has to be any integer type.
703     if (!Arg3->getType()->isIntegerType()) {
704       S.Diag(TheCall->getArg(3)->getBeginLoc(),
705              diag::err_opencl_builtin_expected_type)
706           << TheCall->getDirectCallee() << "integer";
707       return true;
708     }
709     // check remaining common arguments.
710     Expr *Arg4 = TheCall->getArg(4);
711     Expr *Arg5 = TheCall->getArg(5);
712 
713     // Fifth argument is always passed as a pointer to clk_event_t.
714     if (!Arg4->isNullPointerConstant(S.Context,
715                                      Expr::NPC_ValueDependentIsNotNull) &&
716         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
717       S.Diag(TheCall->getArg(4)->getBeginLoc(),
718              diag::err_opencl_builtin_expected_type)
719           << TheCall->getDirectCallee()
720           << S.Context.getPointerType(S.Context.OCLClkEventTy);
721       return true;
722     }
723 
724     // Sixth argument is always passed as a pointer to clk_event_t.
725     if (!Arg5->isNullPointerConstant(S.Context,
726                                      Expr::NPC_ValueDependentIsNotNull) &&
727         !(Arg5->getType()->isPointerType() &&
728           Arg5->getType()->getPointeeType()->isClkEventT())) {
729       S.Diag(TheCall->getArg(5)->getBeginLoc(),
730              diag::err_opencl_builtin_expected_type)
731           << TheCall->getDirectCallee()
732           << S.Context.getPointerType(S.Context.OCLClkEventTy);
733       return true;
734     }
735 
736     if (NumArgs == 7)
737       return false;
738 
739     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
740   }
741 
742   // None of the specific case has been detected, give generic error
743   S.Diag(TheCall->getBeginLoc(),
744          diag::err_opencl_enqueue_kernel_incorrect_args);
745   return true;
746 }
747 
748 /// Returns OpenCL access qual.
749 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
750     return D->getAttr<OpenCLAccessAttr>();
751 }
752 
753 /// Returns true if pipe element type is different from the pointer.
754 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
755   const Expr *Arg0 = Call->getArg(0);
756   // First argument type should always be pipe.
757   if (!Arg0->getType()->isPipeType()) {
758     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
759         << Call->getDirectCallee() << Arg0->getSourceRange();
760     return true;
761   }
762   OpenCLAccessAttr *AccessQual =
763       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
764   // Validates the access qualifier is compatible with the call.
765   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
766   // read_only and write_only, and assumed to be read_only if no qualifier is
767   // specified.
768   switch (Call->getDirectCallee()->getBuiltinID()) {
769   case Builtin::BIread_pipe:
770   case Builtin::BIreserve_read_pipe:
771   case Builtin::BIcommit_read_pipe:
772   case Builtin::BIwork_group_reserve_read_pipe:
773   case Builtin::BIsub_group_reserve_read_pipe:
774   case Builtin::BIwork_group_commit_read_pipe:
775   case Builtin::BIsub_group_commit_read_pipe:
776     if (!(!AccessQual || AccessQual->isReadOnly())) {
777       S.Diag(Arg0->getBeginLoc(),
778              diag::err_opencl_builtin_pipe_invalid_access_modifier)
779           << "read_only" << Arg0->getSourceRange();
780       return true;
781     }
782     break;
783   case Builtin::BIwrite_pipe:
784   case Builtin::BIreserve_write_pipe:
785   case Builtin::BIcommit_write_pipe:
786   case Builtin::BIwork_group_reserve_write_pipe:
787   case Builtin::BIsub_group_reserve_write_pipe:
788   case Builtin::BIwork_group_commit_write_pipe:
789   case Builtin::BIsub_group_commit_write_pipe:
790     if (!(AccessQual && AccessQual->isWriteOnly())) {
791       S.Diag(Arg0->getBeginLoc(),
792              diag::err_opencl_builtin_pipe_invalid_access_modifier)
793           << "write_only" << Arg0->getSourceRange();
794       return true;
795     }
796     break;
797   default:
798     break;
799   }
800   return false;
801 }
802 
803 /// Returns true if pipe element type is different from the pointer.
804 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
805   const Expr *Arg0 = Call->getArg(0);
806   const Expr *ArgIdx = Call->getArg(Idx);
807   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
808   const QualType EltTy = PipeTy->getElementType();
809   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
810   // The Idx argument should be a pointer and the type of the pointer and
811   // the type of pipe element should also be the same.
812   if (!ArgTy ||
813       !S.Context.hasSameType(
814           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
815     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
816         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
817         << ArgIdx->getType() << ArgIdx->getSourceRange();
818     return true;
819   }
820   return false;
821 }
822 
823 // Performs semantic analysis for the read/write_pipe call.
824 // \param S Reference to the semantic analyzer.
825 // \param Call A pointer to the builtin call.
826 // \return True if a semantic error has been found, false otherwise.
827 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
828   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
829   // functions have two forms.
830   switch (Call->getNumArgs()) {
831   case 2:
832     if (checkOpenCLPipeArg(S, Call))
833       return true;
834     // The call with 2 arguments should be
835     // read/write_pipe(pipe T, T*).
836     // Check packet type T.
837     if (checkOpenCLPipePacketType(S, Call, 1))
838       return true;
839     break;
840 
841   case 4: {
842     if (checkOpenCLPipeArg(S, Call))
843       return true;
844     // The call with 4 arguments should be
845     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
846     // Check reserve_id_t.
847     if (!Call->getArg(1)->getType()->isReserveIDT()) {
848       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
849           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
850           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
851       return true;
852     }
853 
854     // Check the index.
855     const Expr *Arg2 = Call->getArg(2);
856     if (!Arg2->getType()->isIntegerType() &&
857         !Arg2->getType()->isUnsignedIntegerType()) {
858       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
859           << Call->getDirectCallee() << S.Context.UnsignedIntTy
860           << Arg2->getType() << Arg2->getSourceRange();
861       return true;
862     }
863 
864     // Check packet type T.
865     if (checkOpenCLPipePacketType(S, Call, 3))
866       return true;
867   } break;
868   default:
869     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
870         << Call->getDirectCallee() << Call->getSourceRange();
871     return true;
872   }
873 
874   return false;
875 }
876 
877 // Performs a semantic analysis on the {work_group_/sub_group_
878 //        /_}reserve_{read/write}_pipe
879 // \param S Reference to the semantic analyzer.
880 // \param Call The call to the builtin function to be analyzed.
881 // \return True if a semantic error was found, false otherwise.
882 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
883   if (checkArgCount(S, Call, 2))
884     return true;
885 
886   if (checkOpenCLPipeArg(S, Call))
887     return true;
888 
889   // Check the reserve size.
890   if (!Call->getArg(1)->getType()->isIntegerType() &&
891       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
892     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
893         << Call->getDirectCallee() << S.Context.UnsignedIntTy
894         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
895     return true;
896   }
897 
898   // Since return type of reserve_read/write_pipe built-in function is
899   // reserve_id_t, which is not defined in the builtin def file , we used int
900   // as return type and need to override the return type of these functions.
901   Call->setType(S.Context.OCLReserveIDTy);
902 
903   return false;
904 }
905 
906 // Performs a semantic analysis on {work_group_/sub_group_
907 //        /_}commit_{read/write}_pipe
908 // \param S Reference to the semantic analyzer.
909 // \param Call The call to the builtin function to be analyzed.
910 // \return True if a semantic error was found, false otherwise.
911 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
912   if (checkArgCount(S, Call, 2))
913     return true;
914 
915   if (checkOpenCLPipeArg(S, Call))
916     return true;
917 
918   // Check reserve_id_t.
919   if (!Call->getArg(1)->getType()->isReserveIDT()) {
920     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
921         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
922         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
923     return true;
924   }
925 
926   return false;
927 }
928 
929 // Performs a semantic analysis on the call to built-in Pipe
930 //        Query Functions.
931 // \param S Reference to the semantic analyzer.
932 // \param Call The call to the builtin function to be analyzed.
933 // \return True if a semantic error was found, false otherwise.
934 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
935   if (checkArgCount(S, Call, 1))
936     return true;
937 
938   if (!Call->getArg(0)->getType()->isPipeType()) {
939     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
940         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
941     return true;
942   }
943 
944   return false;
945 }
946 
947 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
948 // Performs semantic analysis for the to_global/local/private call.
949 // \param S Reference to the semantic analyzer.
950 // \param BuiltinID ID of the builtin function.
951 // \param Call A pointer to the builtin call.
952 // \return True if a semantic error has been found, false otherwise.
953 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
954                                     CallExpr *Call) {
955   if (Call->getNumArgs() != 1) {
956     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
957         << Call->getDirectCallee() << Call->getSourceRange();
958     return true;
959   }
960 
961   auto RT = Call->getArg(0)->getType();
962   if (!RT->isPointerType() || RT->getPointeeType()
963       .getAddressSpace() == LangAS::opencl_constant) {
964     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
965         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
966     return true;
967   }
968 
969   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
970     S.Diag(Call->getArg(0)->getBeginLoc(),
971            diag::warn_opencl_generic_address_space_arg)
972         << Call->getDirectCallee()->getNameInfo().getAsString()
973         << Call->getArg(0)->getSourceRange();
974   }
975 
976   RT = RT->getPointeeType();
977   auto Qual = RT.getQualifiers();
978   switch (BuiltinID) {
979   case Builtin::BIto_global:
980     Qual.setAddressSpace(LangAS::opencl_global);
981     break;
982   case Builtin::BIto_local:
983     Qual.setAddressSpace(LangAS::opencl_local);
984     break;
985   case Builtin::BIto_private:
986     Qual.setAddressSpace(LangAS::opencl_private);
987     break;
988   default:
989     llvm_unreachable("Invalid builtin function");
990   }
991   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
992       RT.getUnqualifiedType(), Qual)));
993 
994   return false;
995 }
996 
997 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
998   if (checkArgCount(S, TheCall, 1))
999     return ExprError();
1000 
1001   // Compute __builtin_launder's parameter type from the argument.
1002   // The parameter type is:
1003   //  * The type of the argument if it's not an array or function type,
1004   //  Otherwise,
1005   //  * The decayed argument type.
1006   QualType ParamTy = [&]() {
1007     QualType ArgTy = TheCall->getArg(0)->getType();
1008     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1009       return S.Context.getPointerType(Ty->getElementType());
1010     if (ArgTy->isFunctionType()) {
1011       return S.Context.getPointerType(ArgTy);
1012     }
1013     return ArgTy;
1014   }();
1015 
1016   TheCall->setType(ParamTy);
1017 
1018   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1019     if (!ParamTy->isPointerType())
1020       return 0;
1021     if (ParamTy->isFunctionPointerType())
1022       return 1;
1023     if (ParamTy->isVoidPointerType())
1024       return 2;
1025     return llvm::Optional<unsigned>{};
1026   }();
1027   if (DiagSelect.hasValue()) {
1028     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1029         << DiagSelect.getValue() << TheCall->getSourceRange();
1030     return ExprError();
1031   }
1032 
1033   // We either have an incomplete class type, or we have a class template
1034   // whose instantiation has not been forced. Example:
1035   //
1036   //   template <class T> struct Foo { T value; };
1037   //   Foo<int> *p = nullptr;
1038   //   auto *d = __builtin_launder(p);
1039   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1040                             diag::err_incomplete_type))
1041     return ExprError();
1042 
1043   assert(ParamTy->getPointeeType()->isObjectType() &&
1044          "Unhandled non-object pointer case");
1045 
1046   InitializedEntity Entity =
1047       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1048   ExprResult Arg =
1049       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1050   if (Arg.isInvalid())
1051     return ExprError();
1052   TheCall->setArg(0, Arg.get());
1053 
1054   return TheCall;
1055 }
1056 
1057 // Emit an error and return true if the current architecture is not in the list
1058 // of supported architectures.
1059 static bool
1060 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1061                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1062   llvm::Triple::ArchType CurArch =
1063       S.getASTContext().getTargetInfo().getTriple().getArch();
1064   if (llvm::is_contained(SupportedArchs, CurArch))
1065     return false;
1066   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1067       << TheCall->getSourceRange();
1068   return true;
1069 }
1070 
1071 ExprResult
1072 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1073                                CallExpr *TheCall) {
1074   ExprResult TheCallResult(TheCall);
1075 
1076   // Find out if any arguments are required to be integer constant expressions.
1077   unsigned ICEArguments = 0;
1078   ASTContext::GetBuiltinTypeError Error;
1079   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1080   if (Error != ASTContext::GE_None)
1081     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1082 
1083   // If any arguments are required to be ICE's, check and diagnose.
1084   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1085     // Skip arguments not required to be ICE's.
1086     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1087 
1088     llvm::APSInt Result;
1089     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1090       return true;
1091     ICEArguments &= ~(1 << ArgNo);
1092   }
1093 
1094   switch (BuiltinID) {
1095   case Builtin::BI__builtin___CFStringMakeConstantString:
1096     assert(TheCall->getNumArgs() == 1 &&
1097            "Wrong # arguments to builtin CFStringMakeConstantString");
1098     if (CheckObjCString(TheCall->getArg(0)))
1099       return ExprError();
1100     break;
1101   case Builtin::BI__builtin_ms_va_start:
1102   case Builtin::BI__builtin_stdarg_start:
1103   case Builtin::BI__builtin_va_start:
1104     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1105       return ExprError();
1106     break;
1107   case Builtin::BI__va_start: {
1108     switch (Context.getTargetInfo().getTriple().getArch()) {
1109     case llvm::Triple::aarch64:
1110     case llvm::Triple::arm:
1111     case llvm::Triple::thumb:
1112       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1113         return ExprError();
1114       break;
1115     default:
1116       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1117         return ExprError();
1118       break;
1119     }
1120     break;
1121   }
1122 
1123   // The acquire, release, and no fence variants are ARM and AArch64 only.
1124   case Builtin::BI_interlockedbittestandset_acq:
1125   case Builtin::BI_interlockedbittestandset_rel:
1126   case Builtin::BI_interlockedbittestandset_nf:
1127   case Builtin::BI_interlockedbittestandreset_acq:
1128   case Builtin::BI_interlockedbittestandreset_rel:
1129   case Builtin::BI_interlockedbittestandreset_nf:
1130     if (CheckBuiltinTargetSupport(
1131             *this, BuiltinID, TheCall,
1132             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1133       return ExprError();
1134     break;
1135 
1136   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1137   case Builtin::BI_bittest64:
1138   case Builtin::BI_bittestandcomplement64:
1139   case Builtin::BI_bittestandreset64:
1140   case Builtin::BI_bittestandset64:
1141   case Builtin::BI_interlockedbittestandreset64:
1142   case Builtin::BI_interlockedbittestandset64:
1143     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1144                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1145                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1146       return ExprError();
1147     break;
1148 
1149   case Builtin::BI__builtin_isgreater:
1150   case Builtin::BI__builtin_isgreaterequal:
1151   case Builtin::BI__builtin_isless:
1152   case Builtin::BI__builtin_islessequal:
1153   case Builtin::BI__builtin_islessgreater:
1154   case Builtin::BI__builtin_isunordered:
1155     if (SemaBuiltinUnorderedCompare(TheCall))
1156       return ExprError();
1157     break;
1158   case Builtin::BI__builtin_fpclassify:
1159     if (SemaBuiltinFPClassification(TheCall, 6))
1160       return ExprError();
1161     break;
1162   case Builtin::BI__builtin_isfinite:
1163   case Builtin::BI__builtin_isinf:
1164   case Builtin::BI__builtin_isinf_sign:
1165   case Builtin::BI__builtin_isnan:
1166   case Builtin::BI__builtin_isnormal:
1167   case Builtin::BI__builtin_signbit:
1168   case Builtin::BI__builtin_signbitf:
1169   case Builtin::BI__builtin_signbitl:
1170     if (SemaBuiltinFPClassification(TheCall, 1))
1171       return ExprError();
1172     break;
1173   case Builtin::BI__builtin_shufflevector:
1174     return SemaBuiltinShuffleVector(TheCall);
1175     // TheCall will be freed by the smart pointer here, but that's fine, since
1176     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1177   case Builtin::BI__builtin_prefetch:
1178     if (SemaBuiltinPrefetch(TheCall))
1179       return ExprError();
1180     break;
1181   case Builtin::BI__builtin_alloca_with_align:
1182     if (SemaBuiltinAllocaWithAlign(TheCall))
1183       return ExprError();
1184     LLVM_FALLTHROUGH;
1185   case Builtin::BI__builtin_alloca:
1186     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1187         << TheCall->getDirectCallee();
1188     break;
1189   case Builtin::BI__assume:
1190   case Builtin::BI__builtin_assume:
1191     if (SemaBuiltinAssume(TheCall))
1192       return ExprError();
1193     break;
1194   case Builtin::BI__builtin_assume_aligned:
1195     if (SemaBuiltinAssumeAligned(TheCall))
1196       return ExprError();
1197     break;
1198   case Builtin::BI__builtin_dynamic_object_size:
1199   case Builtin::BI__builtin_object_size:
1200     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1201       return ExprError();
1202     break;
1203   case Builtin::BI__builtin_longjmp:
1204     if (SemaBuiltinLongjmp(TheCall))
1205       return ExprError();
1206     break;
1207   case Builtin::BI__builtin_setjmp:
1208     if (SemaBuiltinSetjmp(TheCall))
1209       return ExprError();
1210     break;
1211   case Builtin::BI_setjmp:
1212   case Builtin::BI_setjmpex:
1213     if (checkArgCount(*this, TheCall, 1))
1214       return true;
1215     break;
1216   case Builtin::BI__builtin_classify_type:
1217     if (checkArgCount(*this, TheCall, 1)) return true;
1218     TheCall->setType(Context.IntTy);
1219     break;
1220   case Builtin::BI__builtin_constant_p: {
1221     if (checkArgCount(*this, TheCall, 1)) return true;
1222     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1223     if (Arg.isInvalid()) return true;
1224     TheCall->setArg(0, Arg.get());
1225     TheCall->setType(Context.IntTy);
1226     break;
1227   }
1228   case Builtin::BI__builtin_launder:
1229     return SemaBuiltinLaunder(*this, TheCall);
1230   case Builtin::BI__sync_fetch_and_add:
1231   case Builtin::BI__sync_fetch_and_add_1:
1232   case Builtin::BI__sync_fetch_and_add_2:
1233   case Builtin::BI__sync_fetch_and_add_4:
1234   case Builtin::BI__sync_fetch_and_add_8:
1235   case Builtin::BI__sync_fetch_and_add_16:
1236   case Builtin::BI__sync_fetch_and_sub:
1237   case Builtin::BI__sync_fetch_and_sub_1:
1238   case Builtin::BI__sync_fetch_and_sub_2:
1239   case Builtin::BI__sync_fetch_and_sub_4:
1240   case Builtin::BI__sync_fetch_and_sub_8:
1241   case Builtin::BI__sync_fetch_and_sub_16:
1242   case Builtin::BI__sync_fetch_and_or:
1243   case Builtin::BI__sync_fetch_and_or_1:
1244   case Builtin::BI__sync_fetch_and_or_2:
1245   case Builtin::BI__sync_fetch_and_or_4:
1246   case Builtin::BI__sync_fetch_and_or_8:
1247   case Builtin::BI__sync_fetch_and_or_16:
1248   case Builtin::BI__sync_fetch_and_and:
1249   case Builtin::BI__sync_fetch_and_and_1:
1250   case Builtin::BI__sync_fetch_and_and_2:
1251   case Builtin::BI__sync_fetch_and_and_4:
1252   case Builtin::BI__sync_fetch_and_and_8:
1253   case Builtin::BI__sync_fetch_and_and_16:
1254   case Builtin::BI__sync_fetch_and_xor:
1255   case Builtin::BI__sync_fetch_and_xor_1:
1256   case Builtin::BI__sync_fetch_and_xor_2:
1257   case Builtin::BI__sync_fetch_and_xor_4:
1258   case Builtin::BI__sync_fetch_and_xor_8:
1259   case Builtin::BI__sync_fetch_and_xor_16:
1260   case Builtin::BI__sync_fetch_and_nand:
1261   case Builtin::BI__sync_fetch_and_nand_1:
1262   case Builtin::BI__sync_fetch_and_nand_2:
1263   case Builtin::BI__sync_fetch_and_nand_4:
1264   case Builtin::BI__sync_fetch_and_nand_8:
1265   case Builtin::BI__sync_fetch_and_nand_16:
1266   case Builtin::BI__sync_add_and_fetch:
1267   case Builtin::BI__sync_add_and_fetch_1:
1268   case Builtin::BI__sync_add_and_fetch_2:
1269   case Builtin::BI__sync_add_and_fetch_4:
1270   case Builtin::BI__sync_add_and_fetch_8:
1271   case Builtin::BI__sync_add_and_fetch_16:
1272   case Builtin::BI__sync_sub_and_fetch:
1273   case Builtin::BI__sync_sub_and_fetch_1:
1274   case Builtin::BI__sync_sub_and_fetch_2:
1275   case Builtin::BI__sync_sub_and_fetch_4:
1276   case Builtin::BI__sync_sub_and_fetch_8:
1277   case Builtin::BI__sync_sub_and_fetch_16:
1278   case Builtin::BI__sync_and_and_fetch:
1279   case Builtin::BI__sync_and_and_fetch_1:
1280   case Builtin::BI__sync_and_and_fetch_2:
1281   case Builtin::BI__sync_and_and_fetch_4:
1282   case Builtin::BI__sync_and_and_fetch_8:
1283   case Builtin::BI__sync_and_and_fetch_16:
1284   case Builtin::BI__sync_or_and_fetch:
1285   case Builtin::BI__sync_or_and_fetch_1:
1286   case Builtin::BI__sync_or_and_fetch_2:
1287   case Builtin::BI__sync_or_and_fetch_4:
1288   case Builtin::BI__sync_or_and_fetch_8:
1289   case Builtin::BI__sync_or_and_fetch_16:
1290   case Builtin::BI__sync_xor_and_fetch:
1291   case Builtin::BI__sync_xor_and_fetch_1:
1292   case Builtin::BI__sync_xor_and_fetch_2:
1293   case Builtin::BI__sync_xor_and_fetch_4:
1294   case Builtin::BI__sync_xor_and_fetch_8:
1295   case Builtin::BI__sync_xor_and_fetch_16:
1296   case Builtin::BI__sync_nand_and_fetch:
1297   case Builtin::BI__sync_nand_and_fetch_1:
1298   case Builtin::BI__sync_nand_and_fetch_2:
1299   case Builtin::BI__sync_nand_and_fetch_4:
1300   case Builtin::BI__sync_nand_and_fetch_8:
1301   case Builtin::BI__sync_nand_and_fetch_16:
1302   case Builtin::BI__sync_val_compare_and_swap:
1303   case Builtin::BI__sync_val_compare_and_swap_1:
1304   case Builtin::BI__sync_val_compare_and_swap_2:
1305   case Builtin::BI__sync_val_compare_and_swap_4:
1306   case Builtin::BI__sync_val_compare_and_swap_8:
1307   case Builtin::BI__sync_val_compare_and_swap_16:
1308   case Builtin::BI__sync_bool_compare_and_swap:
1309   case Builtin::BI__sync_bool_compare_and_swap_1:
1310   case Builtin::BI__sync_bool_compare_and_swap_2:
1311   case Builtin::BI__sync_bool_compare_and_swap_4:
1312   case Builtin::BI__sync_bool_compare_and_swap_8:
1313   case Builtin::BI__sync_bool_compare_and_swap_16:
1314   case Builtin::BI__sync_lock_test_and_set:
1315   case Builtin::BI__sync_lock_test_and_set_1:
1316   case Builtin::BI__sync_lock_test_and_set_2:
1317   case Builtin::BI__sync_lock_test_and_set_4:
1318   case Builtin::BI__sync_lock_test_and_set_8:
1319   case Builtin::BI__sync_lock_test_and_set_16:
1320   case Builtin::BI__sync_lock_release:
1321   case Builtin::BI__sync_lock_release_1:
1322   case Builtin::BI__sync_lock_release_2:
1323   case Builtin::BI__sync_lock_release_4:
1324   case Builtin::BI__sync_lock_release_8:
1325   case Builtin::BI__sync_lock_release_16:
1326   case Builtin::BI__sync_swap:
1327   case Builtin::BI__sync_swap_1:
1328   case Builtin::BI__sync_swap_2:
1329   case Builtin::BI__sync_swap_4:
1330   case Builtin::BI__sync_swap_8:
1331   case Builtin::BI__sync_swap_16:
1332     return SemaBuiltinAtomicOverloaded(TheCallResult);
1333   case Builtin::BI__sync_synchronize:
1334     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1335         << TheCall->getCallee()->getSourceRange();
1336     break;
1337   case Builtin::BI__builtin_nontemporal_load:
1338   case Builtin::BI__builtin_nontemporal_store:
1339     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1340 #define BUILTIN(ID, TYPE, ATTRS)
1341 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1342   case Builtin::BI##ID: \
1343     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1344 #include "clang/Basic/Builtins.def"
1345   case Builtin::BI__annotation:
1346     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1347       return ExprError();
1348     break;
1349   case Builtin::BI__builtin_annotation:
1350     if (SemaBuiltinAnnotation(*this, TheCall))
1351       return ExprError();
1352     break;
1353   case Builtin::BI__builtin_addressof:
1354     if (SemaBuiltinAddressof(*this, TheCall))
1355       return ExprError();
1356     break;
1357   case Builtin::BI__builtin_add_overflow:
1358   case Builtin::BI__builtin_sub_overflow:
1359   case Builtin::BI__builtin_mul_overflow:
1360     if (SemaBuiltinOverflow(*this, TheCall))
1361       return ExprError();
1362     break;
1363   case Builtin::BI__builtin_operator_new:
1364   case Builtin::BI__builtin_operator_delete: {
1365     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1366     ExprResult Res =
1367         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1368     if (Res.isInvalid())
1369       CorrectDelayedTyposInExpr(TheCallResult.get());
1370     return Res;
1371   }
1372   case Builtin::BI__builtin_dump_struct: {
1373     // We first want to ensure we are called with 2 arguments
1374     if (checkArgCount(*this, TheCall, 2))
1375       return ExprError();
1376     // Ensure that the first argument is of type 'struct XX *'
1377     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1378     const QualType PtrArgType = PtrArg->getType();
1379     if (!PtrArgType->isPointerType() ||
1380         !PtrArgType->getPointeeType()->isRecordType()) {
1381       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1382           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1383           << "structure pointer";
1384       return ExprError();
1385     }
1386 
1387     // Ensure that the second argument is of type 'FunctionType'
1388     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1389     const QualType FnPtrArgType = FnPtrArg->getType();
1390     if (!FnPtrArgType->isPointerType()) {
1391       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1392           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1393           << FnPtrArgType << "'int (*)(const char *, ...)'";
1394       return ExprError();
1395     }
1396 
1397     const auto *FuncType =
1398         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1399 
1400     if (!FuncType) {
1401       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1402           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1403           << FnPtrArgType << "'int (*)(const char *, ...)'";
1404       return ExprError();
1405     }
1406 
1407     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1408       if (!FT->getNumParams()) {
1409         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1410             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1411             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1412         return ExprError();
1413       }
1414       QualType PT = FT->getParamType(0);
1415       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1416           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1417           !PT->getPointeeType().isConstQualified()) {
1418         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1419             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1420             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1421         return ExprError();
1422       }
1423     }
1424 
1425     TheCall->setType(Context.IntTy);
1426     break;
1427   }
1428   case Builtin::BI__builtin_preserve_access_index:
1429     if (SemaBuiltinPreserveAI(*this, TheCall))
1430       return ExprError();
1431     break;
1432   case Builtin::BI__builtin_call_with_static_chain:
1433     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1434       return ExprError();
1435     break;
1436   case Builtin::BI__exception_code:
1437   case Builtin::BI_exception_code:
1438     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1439                                  diag::err_seh___except_block))
1440       return ExprError();
1441     break;
1442   case Builtin::BI__exception_info:
1443   case Builtin::BI_exception_info:
1444     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1445                                  diag::err_seh___except_filter))
1446       return ExprError();
1447     break;
1448   case Builtin::BI__GetExceptionInfo:
1449     if (checkArgCount(*this, TheCall, 1))
1450       return ExprError();
1451 
1452     if (CheckCXXThrowOperand(
1453             TheCall->getBeginLoc(),
1454             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1455             TheCall))
1456       return ExprError();
1457 
1458     TheCall->setType(Context.VoidPtrTy);
1459     break;
1460   // OpenCL v2.0, s6.13.16 - Pipe functions
1461   case Builtin::BIread_pipe:
1462   case Builtin::BIwrite_pipe:
1463     // Since those two functions are declared with var args, we need a semantic
1464     // check for the argument.
1465     if (SemaBuiltinRWPipe(*this, TheCall))
1466       return ExprError();
1467     break;
1468   case Builtin::BIreserve_read_pipe:
1469   case Builtin::BIreserve_write_pipe:
1470   case Builtin::BIwork_group_reserve_read_pipe:
1471   case Builtin::BIwork_group_reserve_write_pipe:
1472     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BIsub_group_reserve_read_pipe:
1476   case Builtin::BIsub_group_reserve_write_pipe:
1477     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1478         SemaBuiltinReserveRWPipe(*this, TheCall))
1479       return ExprError();
1480     break;
1481   case Builtin::BIcommit_read_pipe:
1482   case Builtin::BIcommit_write_pipe:
1483   case Builtin::BIwork_group_commit_read_pipe:
1484   case Builtin::BIwork_group_commit_write_pipe:
1485     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1486       return ExprError();
1487     break;
1488   case Builtin::BIsub_group_commit_read_pipe:
1489   case Builtin::BIsub_group_commit_write_pipe:
1490     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1491         SemaBuiltinCommitRWPipe(*this, TheCall))
1492       return ExprError();
1493     break;
1494   case Builtin::BIget_pipe_num_packets:
1495   case Builtin::BIget_pipe_max_packets:
1496     if (SemaBuiltinPipePackets(*this, TheCall))
1497       return ExprError();
1498     break;
1499   case Builtin::BIto_global:
1500   case Builtin::BIto_local:
1501   case Builtin::BIto_private:
1502     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1503       return ExprError();
1504     break;
1505   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1506   case Builtin::BIenqueue_kernel:
1507     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1508       return ExprError();
1509     break;
1510   case Builtin::BIget_kernel_work_group_size:
1511   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1512     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1513       return ExprError();
1514     break;
1515   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1516   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1517     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1518       return ExprError();
1519     break;
1520   case Builtin::BI__builtin_os_log_format:
1521   case Builtin::BI__builtin_os_log_format_buffer_size:
1522     if (SemaBuiltinOSLogFormat(TheCall))
1523       return ExprError();
1524     break;
1525   }
1526 
1527   // Since the target specific builtins for each arch overlap, only check those
1528   // of the arch we are compiling for.
1529   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1530     switch (Context.getTargetInfo().getTriple().getArch()) {
1531       case llvm::Triple::arm:
1532       case llvm::Triple::armeb:
1533       case llvm::Triple::thumb:
1534       case llvm::Triple::thumbeb:
1535         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1536           return ExprError();
1537         break;
1538       case llvm::Triple::aarch64:
1539       case llvm::Triple::aarch64_32:
1540       case llvm::Triple::aarch64_be:
1541         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1542           return ExprError();
1543         break;
1544       case llvm::Triple::bpfeb:
1545       case llvm::Triple::bpfel:
1546         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1547           return ExprError();
1548         break;
1549       case llvm::Triple::hexagon:
1550         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1551           return ExprError();
1552         break;
1553       case llvm::Triple::mips:
1554       case llvm::Triple::mipsel:
1555       case llvm::Triple::mips64:
1556       case llvm::Triple::mips64el:
1557         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1558           return ExprError();
1559         break;
1560       case llvm::Triple::systemz:
1561         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1562           return ExprError();
1563         break;
1564       case llvm::Triple::x86:
1565       case llvm::Triple::x86_64:
1566         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1567           return ExprError();
1568         break;
1569       case llvm::Triple::ppc:
1570       case llvm::Triple::ppc64:
1571       case llvm::Triple::ppc64le:
1572         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1573           return ExprError();
1574         break;
1575       default:
1576         break;
1577     }
1578   }
1579 
1580   return TheCallResult;
1581 }
1582 
1583 // Get the valid immediate range for the specified NEON type code.
1584 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1585   NeonTypeFlags Type(t);
1586   int IsQuad = ForceQuad ? true : Type.isQuad();
1587   switch (Type.getEltType()) {
1588   case NeonTypeFlags::Int8:
1589   case NeonTypeFlags::Poly8:
1590     return shift ? 7 : (8 << IsQuad) - 1;
1591   case NeonTypeFlags::Int16:
1592   case NeonTypeFlags::Poly16:
1593     return shift ? 15 : (4 << IsQuad) - 1;
1594   case NeonTypeFlags::Int32:
1595     return shift ? 31 : (2 << IsQuad) - 1;
1596   case NeonTypeFlags::Int64:
1597   case NeonTypeFlags::Poly64:
1598     return shift ? 63 : (1 << IsQuad) - 1;
1599   case NeonTypeFlags::Poly128:
1600     return shift ? 127 : (1 << IsQuad) - 1;
1601   case NeonTypeFlags::Float16:
1602     assert(!shift && "cannot shift float types!");
1603     return (4 << IsQuad) - 1;
1604   case NeonTypeFlags::Float32:
1605     assert(!shift && "cannot shift float types!");
1606     return (2 << IsQuad) - 1;
1607   case NeonTypeFlags::Float64:
1608     assert(!shift && "cannot shift float types!");
1609     return (1 << IsQuad) - 1;
1610   }
1611   llvm_unreachable("Invalid NeonTypeFlag!");
1612 }
1613 
1614 /// getNeonEltType - Return the QualType corresponding to the elements of
1615 /// the vector type specified by the NeonTypeFlags.  This is used to check
1616 /// the pointer arguments for Neon load/store intrinsics.
1617 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1618                                bool IsPolyUnsigned, bool IsInt64Long) {
1619   switch (Flags.getEltType()) {
1620   case NeonTypeFlags::Int8:
1621     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1622   case NeonTypeFlags::Int16:
1623     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1624   case NeonTypeFlags::Int32:
1625     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1626   case NeonTypeFlags::Int64:
1627     if (IsInt64Long)
1628       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1629     else
1630       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1631                                 : Context.LongLongTy;
1632   case NeonTypeFlags::Poly8:
1633     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1634   case NeonTypeFlags::Poly16:
1635     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1636   case NeonTypeFlags::Poly64:
1637     if (IsInt64Long)
1638       return Context.UnsignedLongTy;
1639     else
1640       return Context.UnsignedLongLongTy;
1641   case NeonTypeFlags::Poly128:
1642     break;
1643   case NeonTypeFlags::Float16:
1644     return Context.HalfTy;
1645   case NeonTypeFlags::Float32:
1646     return Context.FloatTy;
1647   case NeonTypeFlags::Float64:
1648     return Context.DoubleTy;
1649   }
1650   llvm_unreachable("Invalid NeonTypeFlag!");
1651 }
1652 
1653 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1654   llvm::APSInt Result;
1655   uint64_t mask = 0;
1656   unsigned TV = 0;
1657   int PtrArgNum = -1;
1658   bool HasConstPtr = false;
1659   switch (BuiltinID) {
1660 #define GET_NEON_OVERLOAD_CHECK
1661 #include "clang/Basic/arm_neon.inc"
1662 #include "clang/Basic/arm_fp16.inc"
1663 #undef GET_NEON_OVERLOAD_CHECK
1664   }
1665 
1666   // For NEON intrinsics which are overloaded on vector element type, validate
1667   // the immediate which specifies which variant to emit.
1668   unsigned ImmArg = TheCall->getNumArgs()-1;
1669   if (mask) {
1670     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1671       return true;
1672 
1673     TV = Result.getLimitedValue(64);
1674     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1675       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1676              << TheCall->getArg(ImmArg)->getSourceRange();
1677   }
1678 
1679   if (PtrArgNum >= 0) {
1680     // Check that pointer arguments have the specified type.
1681     Expr *Arg = TheCall->getArg(PtrArgNum);
1682     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1683       Arg = ICE->getSubExpr();
1684     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1685     QualType RHSTy = RHS.get()->getType();
1686 
1687     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1688     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1689                           Arch == llvm::Triple::aarch64_32 ||
1690                           Arch == llvm::Triple::aarch64_be;
1691     bool IsInt64Long =
1692         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1693     QualType EltTy =
1694         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1695     if (HasConstPtr)
1696       EltTy = EltTy.withConst();
1697     QualType LHSTy = Context.getPointerType(EltTy);
1698     AssignConvertType ConvTy;
1699     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1700     if (RHS.isInvalid())
1701       return true;
1702     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1703                                  RHS.get(), AA_Assigning))
1704       return true;
1705   }
1706 
1707   // For NEON intrinsics which take an immediate value as part of the
1708   // instruction, range check them here.
1709   unsigned i = 0, l = 0, u = 0;
1710   switch (BuiltinID) {
1711   default:
1712     return false;
1713   #define GET_NEON_IMMEDIATE_CHECK
1714   #include "clang/Basic/arm_neon.inc"
1715   #include "clang/Basic/arm_fp16.inc"
1716   #undef GET_NEON_IMMEDIATE_CHECK
1717   }
1718 
1719   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1720 }
1721 
1722 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1723   switch (BuiltinID) {
1724   default:
1725     return false;
1726   #include "clang/Basic/arm_mve_builtin_sema.inc"
1727   }
1728 }
1729 
1730 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1731                                         unsigned MaxWidth) {
1732   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1733           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1734           BuiltinID == ARM::BI__builtin_arm_strex ||
1735           BuiltinID == ARM::BI__builtin_arm_stlex ||
1736           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1737           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1738           BuiltinID == AArch64::BI__builtin_arm_strex ||
1739           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1740          "unexpected ARM builtin");
1741   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1742                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1743                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1744                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1745 
1746   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1747 
1748   // Ensure that we have the proper number of arguments.
1749   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1750     return true;
1751 
1752   // Inspect the pointer argument of the atomic builtin.  This should always be
1753   // a pointer type, whose element is an integral scalar or pointer type.
1754   // Because it is a pointer type, we don't have to worry about any implicit
1755   // casts here.
1756   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1757   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1758   if (PointerArgRes.isInvalid())
1759     return true;
1760   PointerArg = PointerArgRes.get();
1761 
1762   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1763   if (!pointerType) {
1764     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1765         << PointerArg->getType() << PointerArg->getSourceRange();
1766     return true;
1767   }
1768 
1769   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1770   // task is to insert the appropriate casts into the AST. First work out just
1771   // what the appropriate type is.
1772   QualType ValType = pointerType->getPointeeType();
1773   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1774   if (IsLdrex)
1775     AddrType.addConst();
1776 
1777   // Issue a warning if the cast is dodgy.
1778   CastKind CastNeeded = CK_NoOp;
1779   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1780     CastNeeded = CK_BitCast;
1781     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1782         << PointerArg->getType() << Context.getPointerType(AddrType)
1783         << AA_Passing << PointerArg->getSourceRange();
1784   }
1785 
1786   // Finally, do the cast and replace the argument with the corrected version.
1787   AddrType = Context.getPointerType(AddrType);
1788   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1789   if (PointerArgRes.isInvalid())
1790     return true;
1791   PointerArg = PointerArgRes.get();
1792 
1793   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1794 
1795   // In general, we allow ints, floats and pointers to be loaded and stored.
1796   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1797       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1798     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1799         << PointerArg->getType() << PointerArg->getSourceRange();
1800     return true;
1801   }
1802 
1803   // But ARM doesn't have instructions to deal with 128-bit versions.
1804   if (Context.getTypeSize(ValType) > MaxWidth) {
1805     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1806     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1807         << PointerArg->getType() << PointerArg->getSourceRange();
1808     return true;
1809   }
1810 
1811   switch (ValType.getObjCLifetime()) {
1812   case Qualifiers::OCL_None:
1813   case Qualifiers::OCL_ExplicitNone:
1814     // okay
1815     break;
1816 
1817   case Qualifiers::OCL_Weak:
1818   case Qualifiers::OCL_Strong:
1819   case Qualifiers::OCL_Autoreleasing:
1820     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1821         << ValType << PointerArg->getSourceRange();
1822     return true;
1823   }
1824 
1825   if (IsLdrex) {
1826     TheCall->setType(ValType);
1827     return false;
1828   }
1829 
1830   // Initialize the argument to be stored.
1831   ExprResult ValArg = TheCall->getArg(0);
1832   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1833       Context, ValType, /*consume*/ false);
1834   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1835   if (ValArg.isInvalid())
1836     return true;
1837   TheCall->setArg(0, ValArg.get());
1838 
1839   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1840   // but the custom checker bypasses all default analysis.
1841   TheCall->setType(Context.IntTy);
1842   return false;
1843 }
1844 
1845 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1846   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1847       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1848       BuiltinID == ARM::BI__builtin_arm_strex ||
1849       BuiltinID == ARM::BI__builtin_arm_stlex) {
1850     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1851   }
1852 
1853   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1854     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1855       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1856   }
1857 
1858   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1859       BuiltinID == ARM::BI__builtin_arm_wsr64)
1860     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1861 
1862   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1863       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1864       BuiltinID == ARM::BI__builtin_arm_wsr ||
1865       BuiltinID == ARM::BI__builtin_arm_wsrp)
1866     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1867 
1868   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1869     return true;
1870   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
1871     return true;
1872 
1873   // For intrinsics which take an immediate value as part of the instruction,
1874   // range check them here.
1875   // FIXME: VFP Intrinsics should error if VFP not present.
1876   switch (BuiltinID) {
1877   default: return false;
1878   case ARM::BI__builtin_arm_ssat:
1879     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1880   case ARM::BI__builtin_arm_usat:
1881     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1882   case ARM::BI__builtin_arm_ssat16:
1883     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1884   case ARM::BI__builtin_arm_usat16:
1885     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1886   case ARM::BI__builtin_arm_vcvtr_f:
1887   case ARM::BI__builtin_arm_vcvtr_d:
1888     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1889   case ARM::BI__builtin_arm_dmb:
1890   case ARM::BI__builtin_arm_dsb:
1891   case ARM::BI__builtin_arm_isb:
1892   case ARM::BI__builtin_arm_dbg:
1893     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1894   }
1895 }
1896 
1897 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1898                                          CallExpr *TheCall) {
1899   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1900       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1901       BuiltinID == AArch64::BI__builtin_arm_strex ||
1902       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1903     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1904   }
1905 
1906   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1907     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1908       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1909       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1910       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1911   }
1912 
1913   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1914       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1915     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1916 
1917   // Memory Tagging Extensions (MTE) Intrinsics
1918   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1919       BuiltinID == AArch64::BI__builtin_arm_addg ||
1920       BuiltinID == AArch64::BI__builtin_arm_gmi ||
1921       BuiltinID == AArch64::BI__builtin_arm_ldg ||
1922       BuiltinID == AArch64::BI__builtin_arm_stg ||
1923       BuiltinID == AArch64::BI__builtin_arm_subp) {
1924     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1925   }
1926 
1927   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1928       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1929       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1930       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1931     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1932 
1933   // Only check the valid encoding range. Any constant in this range would be
1934   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1935   // an exception for incorrect registers. This matches MSVC behavior.
1936   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1937       BuiltinID == AArch64::BI_WriteStatusReg)
1938     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1939 
1940   if (BuiltinID == AArch64::BI__getReg)
1941     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1942 
1943   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1944     return true;
1945 
1946   // For intrinsics which take an immediate value as part of the instruction,
1947   // range check them here.
1948   unsigned i = 0, l = 0, u = 0;
1949   switch (BuiltinID) {
1950   default: return false;
1951   case AArch64::BI__builtin_arm_dmb:
1952   case AArch64::BI__builtin_arm_dsb:
1953   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1954   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
1955   }
1956 
1957   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1958 }
1959 
1960 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
1961                                        CallExpr *TheCall) {
1962   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
1963          "unexpected ARM builtin");
1964 
1965   if (checkArgCount(*this, TheCall, 2))
1966     return true;
1967 
1968   // The first argument needs to be a record field access.
1969   // If it is an array element access, we delay decision
1970   // to BPF backend to check whether the access is a
1971   // field access or not.
1972   Expr *Arg = TheCall->getArg(0);
1973   if (Arg->getType()->getAsPlaceholderType() ||
1974       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
1975        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
1976        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
1977     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
1978         << 1 << Arg->getSourceRange();
1979     return true;
1980   }
1981 
1982   // The second argument needs to be a constant int
1983   llvm::APSInt Value;
1984   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
1985     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
1986         << 2 << Arg->getSourceRange();
1987     return true;
1988   }
1989 
1990   TheCall->setType(Context.UnsignedIntTy);
1991   return false;
1992 }
1993 
1994 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1995   struct BuiltinAndString {
1996     unsigned BuiltinID;
1997     const char *Str;
1998   };
1999 
2000   static BuiltinAndString ValidCPU[] = {
2001     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
2004     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
2005     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
2006     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
2009     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
2024   };
2025 
2026   static BuiltinAndString ValidHVX[] = {
2027     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2671     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2672     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2673     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2674     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2675     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2676     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2677     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2678     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2679     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2680     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2681     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2682     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2683     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2684     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2685     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2686     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2687     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2688     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2689     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2690     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2691     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2692     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2693     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2694     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2695     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2696     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2697     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2698     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2699     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2701     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2704     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2705     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2706     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2707     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2708     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2709     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2710     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2711     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2712     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2713     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2714     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2715     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2716     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2717     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2718     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2719     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2720     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2721     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2722     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2723     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2724     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2725     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2726     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2727     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2728     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2729     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2730     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2731     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2732     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2733     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2734     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2735     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2736     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2737     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2738     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2739     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2740     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2741     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2742     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2743     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2744     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2745     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2746     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2747     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2748     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2749     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2750     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2751     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2752     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2753     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2754     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2755     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2756     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2757     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2758     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2759   };
2760 
2761   // Sort the tables on first execution so we can binary search them.
2762   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2763     return LHS.BuiltinID < RHS.BuiltinID;
2764   };
2765   static const bool SortOnce =
2766       (llvm::sort(ValidCPU, SortCmp),
2767        llvm::sort(ValidHVX, SortCmp), true);
2768   (void)SortOnce;
2769   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2770     return BI.BuiltinID < BuiltinID;
2771   };
2772 
2773   const TargetInfo &TI = Context.getTargetInfo();
2774 
2775   const BuiltinAndString *FC =
2776       llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
2777   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2778     const TargetOptions &Opts = TI.getTargetOpts();
2779     StringRef CPU = Opts.CPU;
2780     if (!CPU.empty()) {
2781       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2782       CPU.consume_front("hexagon");
2783       SmallVector<StringRef, 3> CPUs;
2784       StringRef(FC->Str).split(CPUs, ',');
2785       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2786         return Diag(TheCall->getBeginLoc(),
2787                     diag::err_hexagon_builtin_unsupported_cpu);
2788     }
2789   }
2790 
2791   const BuiltinAndString *FH =
2792       llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
2793   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2794     if (!TI.hasFeature("hvx"))
2795       return Diag(TheCall->getBeginLoc(),
2796                   diag::err_hexagon_builtin_requires_hvx);
2797 
2798     SmallVector<StringRef, 3> HVXs;
2799     StringRef(FH->Str).split(HVXs, ',');
2800     bool IsValid = llvm::any_of(HVXs,
2801                                 [&TI] (StringRef V) {
2802                                   std::string F = "hvx" + V.str();
2803                                   return TI.hasFeature(F);
2804                                 });
2805     if (!IsValid)
2806       return Diag(TheCall->getBeginLoc(),
2807                   diag::err_hexagon_builtin_unsupported_hvx);
2808   }
2809 
2810   return false;
2811 }
2812 
2813 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2814   struct ArgInfo {
2815     uint8_t OpNum;
2816     bool IsSigned;
2817     uint8_t BitWidth;
2818     uint8_t Align;
2819   };
2820   struct BuiltinInfo {
2821     unsigned BuiltinID;
2822     ArgInfo Infos[2];
2823   };
2824 
2825   static BuiltinInfo Infos[] = {
2826     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2827     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2828     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2829     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2830     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2831     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2832     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2833     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2834     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2835     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2836     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2837 
2838     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2841     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2842     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2843     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2849 
2850     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2902                                                       {{ 1, false, 6,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2910                                                       {{ 1, false, 5,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2917                                                        { 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2919                                                        { 2, false, 6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2921                                                        { 3, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2923                                                        { 3, false, 6,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2940                                                       {{ 2, false, 4,  0 },
2941                                                        { 3, false, 5,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2943                                                       {{ 2, false, 4,  0 },
2944                                                        { 3, false, 5,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2946                                                       {{ 2, false, 4,  0 },
2947                                                        { 3, false, 5,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2949                                                       {{ 2, false, 4,  0 },
2950                                                        { 3, false, 5,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2959     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2960     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2961     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2962                                                        { 2, false, 5,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2964                                                        { 2, false, 6,  0 }} },
2965     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2966     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2967     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2968     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2969     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2970     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2971     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2972     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2973     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2974                                                       {{ 1, false, 4,  0 }} },
2975     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2976     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2977                                                       {{ 1, false, 4,  0 }} },
2978     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2979     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2980     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2981     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2982     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2983     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2984     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2985     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2986     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2987     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2988     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2989     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2990     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2991     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2992     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2993     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2994     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2995     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2996     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2997     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2998                                                       {{ 3, false, 1,  0 }} },
2999     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3000     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3001     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3002     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3003                                                       {{ 3, false, 1,  0 }} },
3004     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3005     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3006     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3007     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3008                                                       {{ 3, false, 1,  0 }} },
3009   };
3010 
3011   // Use a dynamically initialized static to sort the table exactly once on
3012   // first run.
3013   static const bool SortOnce =
3014       (llvm::sort(Infos,
3015                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3016                    return LHS.BuiltinID < RHS.BuiltinID;
3017                  }),
3018        true);
3019   (void)SortOnce;
3020 
3021   const BuiltinInfo *F = llvm::partition_point(
3022       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3023   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3024     return false;
3025 
3026   bool Error = false;
3027 
3028   for (const ArgInfo &A : F->Infos) {
3029     // Ignore empty ArgInfo elements.
3030     if (A.BitWidth == 0)
3031       continue;
3032 
3033     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3034     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3035     if (!A.Align) {
3036       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3037     } else {
3038       unsigned M = 1 << A.Align;
3039       Min *= M;
3040       Max *= M;
3041       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
3042                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3043     }
3044   }
3045   return Error;
3046 }
3047 
3048 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3049                                            CallExpr *TheCall) {
3050   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3051          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3052 }
3053 
3054 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3055   return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
3056          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3057 }
3058 
3059 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
3060   const TargetInfo &TI = Context.getTargetInfo();
3061 
3062   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3063       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3064     if (!TI.hasFeature("dsp"))
3065       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3066   }
3067 
3068   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3069       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3070     if (!TI.hasFeature("dspr2"))
3071       return Diag(TheCall->getBeginLoc(),
3072                   diag::err_mips_builtin_requires_dspr2);
3073   }
3074 
3075   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3076       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3077     if (!TI.hasFeature("msa"))
3078       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3079   }
3080 
3081   return false;
3082 }
3083 
3084 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3085 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3086 // ordering for DSP is unspecified. MSA is ordered by the data format used
3087 // by the underlying instruction i.e., df/m, df/n and then by size.
3088 //
3089 // FIXME: The size tests here should instead be tablegen'd along with the
3090 //        definitions from include/clang/Basic/BuiltinsMips.def.
3091 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3092 //        be too.
3093 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3094   unsigned i = 0, l = 0, u = 0, m = 0;
3095   switch (BuiltinID) {
3096   default: return false;
3097   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3098   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3099   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3100   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3101   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3102   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3103   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3104   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3105   // df/m field.
3106   // These intrinsics take an unsigned 3 bit immediate.
3107   case Mips::BI__builtin_msa_bclri_b:
3108   case Mips::BI__builtin_msa_bnegi_b:
3109   case Mips::BI__builtin_msa_bseti_b:
3110   case Mips::BI__builtin_msa_sat_s_b:
3111   case Mips::BI__builtin_msa_sat_u_b:
3112   case Mips::BI__builtin_msa_slli_b:
3113   case Mips::BI__builtin_msa_srai_b:
3114   case Mips::BI__builtin_msa_srari_b:
3115   case Mips::BI__builtin_msa_srli_b:
3116   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3117   case Mips::BI__builtin_msa_binsli_b:
3118   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3119   // These intrinsics take an unsigned 4 bit immediate.
3120   case Mips::BI__builtin_msa_bclri_h:
3121   case Mips::BI__builtin_msa_bnegi_h:
3122   case Mips::BI__builtin_msa_bseti_h:
3123   case Mips::BI__builtin_msa_sat_s_h:
3124   case Mips::BI__builtin_msa_sat_u_h:
3125   case Mips::BI__builtin_msa_slli_h:
3126   case Mips::BI__builtin_msa_srai_h:
3127   case Mips::BI__builtin_msa_srari_h:
3128   case Mips::BI__builtin_msa_srli_h:
3129   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3130   case Mips::BI__builtin_msa_binsli_h:
3131   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3132   // These intrinsics take an unsigned 5 bit immediate.
3133   // The first block of intrinsics actually have an unsigned 5 bit field,
3134   // not a df/n field.
3135   case Mips::BI__builtin_msa_cfcmsa:
3136   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3137   case Mips::BI__builtin_msa_clei_u_b:
3138   case Mips::BI__builtin_msa_clei_u_h:
3139   case Mips::BI__builtin_msa_clei_u_w:
3140   case Mips::BI__builtin_msa_clei_u_d:
3141   case Mips::BI__builtin_msa_clti_u_b:
3142   case Mips::BI__builtin_msa_clti_u_h:
3143   case Mips::BI__builtin_msa_clti_u_w:
3144   case Mips::BI__builtin_msa_clti_u_d:
3145   case Mips::BI__builtin_msa_maxi_u_b:
3146   case Mips::BI__builtin_msa_maxi_u_h:
3147   case Mips::BI__builtin_msa_maxi_u_w:
3148   case Mips::BI__builtin_msa_maxi_u_d:
3149   case Mips::BI__builtin_msa_mini_u_b:
3150   case Mips::BI__builtin_msa_mini_u_h:
3151   case Mips::BI__builtin_msa_mini_u_w:
3152   case Mips::BI__builtin_msa_mini_u_d:
3153   case Mips::BI__builtin_msa_addvi_b:
3154   case Mips::BI__builtin_msa_addvi_h:
3155   case Mips::BI__builtin_msa_addvi_w:
3156   case Mips::BI__builtin_msa_addvi_d:
3157   case Mips::BI__builtin_msa_bclri_w:
3158   case Mips::BI__builtin_msa_bnegi_w:
3159   case Mips::BI__builtin_msa_bseti_w:
3160   case Mips::BI__builtin_msa_sat_s_w:
3161   case Mips::BI__builtin_msa_sat_u_w:
3162   case Mips::BI__builtin_msa_slli_w:
3163   case Mips::BI__builtin_msa_srai_w:
3164   case Mips::BI__builtin_msa_srari_w:
3165   case Mips::BI__builtin_msa_srli_w:
3166   case Mips::BI__builtin_msa_srlri_w:
3167   case Mips::BI__builtin_msa_subvi_b:
3168   case Mips::BI__builtin_msa_subvi_h:
3169   case Mips::BI__builtin_msa_subvi_w:
3170   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3171   case Mips::BI__builtin_msa_binsli_w:
3172   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3173   // These intrinsics take an unsigned 6 bit immediate.
3174   case Mips::BI__builtin_msa_bclri_d:
3175   case Mips::BI__builtin_msa_bnegi_d:
3176   case Mips::BI__builtin_msa_bseti_d:
3177   case Mips::BI__builtin_msa_sat_s_d:
3178   case Mips::BI__builtin_msa_sat_u_d:
3179   case Mips::BI__builtin_msa_slli_d:
3180   case Mips::BI__builtin_msa_srai_d:
3181   case Mips::BI__builtin_msa_srari_d:
3182   case Mips::BI__builtin_msa_srli_d:
3183   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3184   case Mips::BI__builtin_msa_binsli_d:
3185   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3186   // These intrinsics take a signed 5 bit immediate.
3187   case Mips::BI__builtin_msa_ceqi_b:
3188   case Mips::BI__builtin_msa_ceqi_h:
3189   case Mips::BI__builtin_msa_ceqi_w:
3190   case Mips::BI__builtin_msa_ceqi_d:
3191   case Mips::BI__builtin_msa_clti_s_b:
3192   case Mips::BI__builtin_msa_clti_s_h:
3193   case Mips::BI__builtin_msa_clti_s_w:
3194   case Mips::BI__builtin_msa_clti_s_d:
3195   case Mips::BI__builtin_msa_clei_s_b:
3196   case Mips::BI__builtin_msa_clei_s_h:
3197   case Mips::BI__builtin_msa_clei_s_w:
3198   case Mips::BI__builtin_msa_clei_s_d:
3199   case Mips::BI__builtin_msa_maxi_s_b:
3200   case Mips::BI__builtin_msa_maxi_s_h:
3201   case Mips::BI__builtin_msa_maxi_s_w:
3202   case Mips::BI__builtin_msa_maxi_s_d:
3203   case Mips::BI__builtin_msa_mini_s_b:
3204   case Mips::BI__builtin_msa_mini_s_h:
3205   case Mips::BI__builtin_msa_mini_s_w:
3206   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3207   // These intrinsics take an unsigned 8 bit immediate.
3208   case Mips::BI__builtin_msa_andi_b:
3209   case Mips::BI__builtin_msa_nori_b:
3210   case Mips::BI__builtin_msa_ori_b:
3211   case Mips::BI__builtin_msa_shf_b:
3212   case Mips::BI__builtin_msa_shf_h:
3213   case Mips::BI__builtin_msa_shf_w:
3214   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3215   case Mips::BI__builtin_msa_bseli_b:
3216   case Mips::BI__builtin_msa_bmnzi_b:
3217   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3218   // df/n format
3219   // These intrinsics take an unsigned 4 bit immediate.
3220   case Mips::BI__builtin_msa_copy_s_b:
3221   case Mips::BI__builtin_msa_copy_u_b:
3222   case Mips::BI__builtin_msa_insve_b:
3223   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3224   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3225   // These intrinsics take an unsigned 3 bit immediate.
3226   case Mips::BI__builtin_msa_copy_s_h:
3227   case Mips::BI__builtin_msa_copy_u_h:
3228   case Mips::BI__builtin_msa_insve_h:
3229   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3230   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3231   // These intrinsics take an unsigned 2 bit immediate.
3232   case Mips::BI__builtin_msa_copy_s_w:
3233   case Mips::BI__builtin_msa_copy_u_w:
3234   case Mips::BI__builtin_msa_insve_w:
3235   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3236   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3237   // These intrinsics take an unsigned 1 bit immediate.
3238   case Mips::BI__builtin_msa_copy_s_d:
3239   case Mips::BI__builtin_msa_copy_u_d:
3240   case Mips::BI__builtin_msa_insve_d:
3241   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3242   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3243   // Memory offsets and immediate loads.
3244   // These intrinsics take a signed 10 bit immediate.
3245   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3246   case Mips::BI__builtin_msa_ldi_h:
3247   case Mips::BI__builtin_msa_ldi_w:
3248   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3249   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3250   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3251   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3252   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3253   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3254   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3255   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3256   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3257   }
3258 
3259   if (!m)
3260     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3261 
3262   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3263          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3264 }
3265 
3266 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3267   unsigned i = 0, l = 0, u = 0;
3268   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3269                       BuiltinID == PPC::BI__builtin_divdeu ||
3270                       BuiltinID == PPC::BI__builtin_bpermd;
3271   bool IsTarget64Bit = Context.getTargetInfo()
3272                               .getTypeWidth(Context
3273                                             .getTargetInfo()
3274                                             .getIntPtrType()) == 64;
3275   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3276                        BuiltinID == PPC::BI__builtin_divweu ||
3277                        BuiltinID == PPC::BI__builtin_divde ||
3278                        BuiltinID == PPC::BI__builtin_divdeu;
3279 
3280   if (Is64BitBltin && !IsTarget64Bit)
3281     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3282            << TheCall->getSourceRange();
3283 
3284   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3285       (BuiltinID == PPC::BI__builtin_bpermd &&
3286        !Context.getTargetInfo().hasFeature("bpermd")))
3287     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3288            << TheCall->getSourceRange();
3289 
3290   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3291     if (!Context.getTargetInfo().hasFeature("vsx"))
3292       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3293              << TheCall->getSourceRange();
3294     return false;
3295   };
3296 
3297   switch (BuiltinID) {
3298   default: return false;
3299   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3300   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3301     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3302            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3303   case PPC::BI__builtin_altivec_dss:
3304     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3305   case PPC::BI__builtin_tbegin:
3306   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3307   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3308   case PPC::BI__builtin_tabortwc:
3309   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3310   case PPC::BI__builtin_tabortwci:
3311   case PPC::BI__builtin_tabortdci:
3312     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3313            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3314   case PPC::BI__builtin_altivec_dst:
3315   case PPC::BI__builtin_altivec_dstt:
3316   case PPC::BI__builtin_altivec_dstst:
3317   case PPC::BI__builtin_altivec_dststt:
3318     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3319   case PPC::BI__builtin_vsx_xxpermdi:
3320   case PPC::BI__builtin_vsx_xxsldwi:
3321     return SemaBuiltinVSX(TheCall);
3322   case PPC::BI__builtin_unpack_vector_int128:
3323     return SemaVSXCheck(TheCall) ||
3324            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3325   case PPC::BI__builtin_pack_vector_int128:
3326     return SemaVSXCheck(TheCall);
3327   }
3328   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3329 }
3330 
3331 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3332                                            CallExpr *TheCall) {
3333   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3334     Expr *Arg = TheCall->getArg(0);
3335     llvm::APSInt AbortCode(32);
3336     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3337         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3338       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3339              << Arg->getSourceRange();
3340   }
3341 
3342   // For intrinsics which take an immediate value as part of the instruction,
3343   // range check them here.
3344   unsigned i = 0, l = 0, u = 0;
3345   switch (BuiltinID) {
3346   default: return false;
3347   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3348   case SystemZ::BI__builtin_s390_verimb:
3349   case SystemZ::BI__builtin_s390_verimh:
3350   case SystemZ::BI__builtin_s390_verimf:
3351   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3352   case SystemZ::BI__builtin_s390_vfaeb:
3353   case SystemZ::BI__builtin_s390_vfaeh:
3354   case SystemZ::BI__builtin_s390_vfaef:
3355   case SystemZ::BI__builtin_s390_vfaebs:
3356   case SystemZ::BI__builtin_s390_vfaehs:
3357   case SystemZ::BI__builtin_s390_vfaefs:
3358   case SystemZ::BI__builtin_s390_vfaezb:
3359   case SystemZ::BI__builtin_s390_vfaezh:
3360   case SystemZ::BI__builtin_s390_vfaezf:
3361   case SystemZ::BI__builtin_s390_vfaezbs:
3362   case SystemZ::BI__builtin_s390_vfaezhs:
3363   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3364   case SystemZ::BI__builtin_s390_vfisb:
3365   case SystemZ::BI__builtin_s390_vfidb:
3366     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3367            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3368   case SystemZ::BI__builtin_s390_vftcisb:
3369   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3370   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3371   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3372   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3373   case SystemZ::BI__builtin_s390_vstrcb:
3374   case SystemZ::BI__builtin_s390_vstrch:
3375   case SystemZ::BI__builtin_s390_vstrcf:
3376   case SystemZ::BI__builtin_s390_vstrczb:
3377   case SystemZ::BI__builtin_s390_vstrczh:
3378   case SystemZ::BI__builtin_s390_vstrczf:
3379   case SystemZ::BI__builtin_s390_vstrcbs:
3380   case SystemZ::BI__builtin_s390_vstrchs:
3381   case SystemZ::BI__builtin_s390_vstrcfs:
3382   case SystemZ::BI__builtin_s390_vstrczbs:
3383   case SystemZ::BI__builtin_s390_vstrczhs:
3384   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3385   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3386   case SystemZ::BI__builtin_s390_vfminsb:
3387   case SystemZ::BI__builtin_s390_vfmaxsb:
3388   case SystemZ::BI__builtin_s390_vfmindb:
3389   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3390   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3391   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3392   }
3393   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3394 }
3395 
3396 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3397 /// This checks that the target supports __builtin_cpu_supports and
3398 /// that the string argument is constant and valid.
3399 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3400   Expr *Arg = TheCall->getArg(0);
3401 
3402   // Check if the argument is a string literal.
3403   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3404     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3405            << Arg->getSourceRange();
3406 
3407   // Check the contents of the string.
3408   StringRef Feature =
3409       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3410   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3411     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3412            << Arg->getSourceRange();
3413   return false;
3414 }
3415 
3416 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3417 /// This checks that the target supports __builtin_cpu_is and
3418 /// that the string argument is constant and valid.
3419 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3420   Expr *Arg = TheCall->getArg(0);
3421 
3422   // Check if the argument is a string literal.
3423   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3424     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3425            << Arg->getSourceRange();
3426 
3427   // Check the contents of the string.
3428   StringRef Feature =
3429       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3430   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3431     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3432            << Arg->getSourceRange();
3433   return false;
3434 }
3435 
3436 // Check if the rounding mode is legal.
3437 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3438   // Indicates if this instruction has rounding control or just SAE.
3439   bool HasRC = false;
3440 
3441   unsigned ArgNum = 0;
3442   switch (BuiltinID) {
3443   default:
3444     return false;
3445   case X86::BI__builtin_ia32_vcvttsd2si32:
3446   case X86::BI__builtin_ia32_vcvttsd2si64:
3447   case X86::BI__builtin_ia32_vcvttsd2usi32:
3448   case X86::BI__builtin_ia32_vcvttsd2usi64:
3449   case X86::BI__builtin_ia32_vcvttss2si32:
3450   case X86::BI__builtin_ia32_vcvttss2si64:
3451   case X86::BI__builtin_ia32_vcvttss2usi32:
3452   case X86::BI__builtin_ia32_vcvttss2usi64:
3453     ArgNum = 1;
3454     break;
3455   case X86::BI__builtin_ia32_maxpd512:
3456   case X86::BI__builtin_ia32_maxps512:
3457   case X86::BI__builtin_ia32_minpd512:
3458   case X86::BI__builtin_ia32_minps512:
3459     ArgNum = 2;
3460     break;
3461   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3462   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3463   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3464   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3465   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3466   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3467   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3468   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3469   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3470   case X86::BI__builtin_ia32_exp2pd_mask:
3471   case X86::BI__builtin_ia32_exp2ps_mask:
3472   case X86::BI__builtin_ia32_getexppd512_mask:
3473   case X86::BI__builtin_ia32_getexpps512_mask:
3474   case X86::BI__builtin_ia32_rcp28pd_mask:
3475   case X86::BI__builtin_ia32_rcp28ps_mask:
3476   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3477   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3478   case X86::BI__builtin_ia32_vcomisd:
3479   case X86::BI__builtin_ia32_vcomiss:
3480   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3481     ArgNum = 3;
3482     break;
3483   case X86::BI__builtin_ia32_cmppd512_mask:
3484   case X86::BI__builtin_ia32_cmpps512_mask:
3485   case X86::BI__builtin_ia32_cmpsd_mask:
3486   case X86::BI__builtin_ia32_cmpss_mask:
3487   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3488   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3489   case X86::BI__builtin_ia32_getexpss128_round_mask:
3490   case X86::BI__builtin_ia32_getmantpd512_mask:
3491   case X86::BI__builtin_ia32_getmantps512_mask:
3492   case X86::BI__builtin_ia32_maxsd_round_mask:
3493   case X86::BI__builtin_ia32_maxss_round_mask:
3494   case X86::BI__builtin_ia32_minsd_round_mask:
3495   case X86::BI__builtin_ia32_minss_round_mask:
3496   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3497   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3498   case X86::BI__builtin_ia32_reducepd512_mask:
3499   case X86::BI__builtin_ia32_reduceps512_mask:
3500   case X86::BI__builtin_ia32_rndscalepd_mask:
3501   case X86::BI__builtin_ia32_rndscaleps_mask:
3502   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3503   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3504     ArgNum = 4;
3505     break;
3506   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3507   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3508   case X86::BI__builtin_ia32_fixupimmps512_mask:
3509   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3510   case X86::BI__builtin_ia32_fixupimmsd_mask:
3511   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3512   case X86::BI__builtin_ia32_fixupimmss_mask:
3513   case X86::BI__builtin_ia32_fixupimmss_maskz:
3514   case X86::BI__builtin_ia32_getmantsd_round_mask:
3515   case X86::BI__builtin_ia32_getmantss_round_mask:
3516   case X86::BI__builtin_ia32_rangepd512_mask:
3517   case X86::BI__builtin_ia32_rangeps512_mask:
3518   case X86::BI__builtin_ia32_rangesd128_round_mask:
3519   case X86::BI__builtin_ia32_rangess128_round_mask:
3520   case X86::BI__builtin_ia32_reducesd_mask:
3521   case X86::BI__builtin_ia32_reducess_mask:
3522   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3523   case X86::BI__builtin_ia32_rndscaless_round_mask:
3524     ArgNum = 5;
3525     break;
3526   case X86::BI__builtin_ia32_vcvtsd2si64:
3527   case X86::BI__builtin_ia32_vcvtsd2si32:
3528   case X86::BI__builtin_ia32_vcvtsd2usi32:
3529   case X86::BI__builtin_ia32_vcvtsd2usi64:
3530   case X86::BI__builtin_ia32_vcvtss2si32:
3531   case X86::BI__builtin_ia32_vcvtss2si64:
3532   case X86::BI__builtin_ia32_vcvtss2usi32:
3533   case X86::BI__builtin_ia32_vcvtss2usi64:
3534   case X86::BI__builtin_ia32_sqrtpd512:
3535   case X86::BI__builtin_ia32_sqrtps512:
3536     ArgNum = 1;
3537     HasRC = true;
3538     break;
3539   case X86::BI__builtin_ia32_addpd512:
3540   case X86::BI__builtin_ia32_addps512:
3541   case X86::BI__builtin_ia32_divpd512:
3542   case X86::BI__builtin_ia32_divps512:
3543   case X86::BI__builtin_ia32_mulpd512:
3544   case X86::BI__builtin_ia32_mulps512:
3545   case X86::BI__builtin_ia32_subpd512:
3546   case X86::BI__builtin_ia32_subps512:
3547   case X86::BI__builtin_ia32_cvtsi2sd64:
3548   case X86::BI__builtin_ia32_cvtsi2ss32:
3549   case X86::BI__builtin_ia32_cvtsi2ss64:
3550   case X86::BI__builtin_ia32_cvtusi2sd64:
3551   case X86::BI__builtin_ia32_cvtusi2ss32:
3552   case X86::BI__builtin_ia32_cvtusi2ss64:
3553     ArgNum = 2;
3554     HasRC = true;
3555     break;
3556   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3557   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3558   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3559   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3560   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3561   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3562   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3563   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3564   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3565   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3566   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3567   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3568   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3569   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3570   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3571     ArgNum = 3;
3572     HasRC = true;
3573     break;
3574   case X86::BI__builtin_ia32_addss_round_mask:
3575   case X86::BI__builtin_ia32_addsd_round_mask:
3576   case X86::BI__builtin_ia32_divss_round_mask:
3577   case X86::BI__builtin_ia32_divsd_round_mask:
3578   case X86::BI__builtin_ia32_mulss_round_mask:
3579   case X86::BI__builtin_ia32_mulsd_round_mask:
3580   case X86::BI__builtin_ia32_subss_round_mask:
3581   case X86::BI__builtin_ia32_subsd_round_mask:
3582   case X86::BI__builtin_ia32_scalefpd512_mask:
3583   case X86::BI__builtin_ia32_scalefps512_mask:
3584   case X86::BI__builtin_ia32_scalefsd_round_mask:
3585   case X86::BI__builtin_ia32_scalefss_round_mask:
3586   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3587   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3588   case X86::BI__builtin_ia32_sqrtss_round_mask:
3589   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3590   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3591   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3592   case X86::BI__builtin_ia32_vfmaddss3_mask:
3593   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3594   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3595   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3596   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3597   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3598   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3599   case X86::BI__builtin_ia32_vfmaddps512_mask:
3600   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3601   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3602   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3603   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3604   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3605   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3606   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3607   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3608   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3609   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3610   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3611     ArgNum = 4;
3612     HasRC = true;
3613     break;
3614   }
3615 
3616   llvm::APSInt Result;
3617 
3618   // We can't check the value of a dependent argument.
3619   Expr *Arg = TheCall->getArg(ArgNum);
3620   if (Arg->isTypeDependent() || Arg->isValueDependent())
3621     return false;
3622 
3623   // Check constant-ness first.
3624   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3625     return true;
3626 
3627   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3628   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3629   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3630   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3631   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3632       Result == 8/*ROUND_NO_EXC*/ ||
3633       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3634       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3635     return false;
3636 
3637   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3638          << Arg->getSourceRange();
3639 }
3640 
3641 // Check if the gather/scatter scale is legal.
3642 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3643                                              CallExpr *TheCall) {
3644   unsigned ArgNum = 0;
3645   switch (BuiltinID) {
3646   default:
3647     return false;
3648   case X86::BI__builtin_ia32_gatherpfdpd:
3649   case X86::BI__builtin_ia32_gatherpfdps:
3650   case X86::BI__builtin_ia32_gatherpfqpd:
3651   case X86::BI__builtin_ia32_gatherpfqps:
3652   case X86::BI__builtin_ia32_scatterpfdpd:
3653   case X86::BI__builtin_ia32_scatterpfdps:
3654   case X86::BI__builtin_ia32_scatterpfqpd:
3655   case X86::BI__builtin_ia32_scatterpfqps:
3656     ArgNum = 3;
3657     break;
3658   case X86::BI__builtin_ia32_gatherd_pd:
3659   case X86::BI__builtin_ia32_gatherd_pd256:
3660   case X86::BI__builtin_ia32_gatherq_pd:
3661   case X86::BI__builtin_ia32_gatherq_pd256:
3662   case X86::BI__builtin_ia32_gatherd_ps:
3663   case X86::BI__builtin_ia32_gatherd_ps256:
3664   case X86::BI__builtin_ia32_gatherq_ps:
3665   case X86::BI__builtin_ia32_gatherq_ps256:
3666   case X86::BI__builtin_ia32_gatherd_q:
3667   case X86::BI__builtin_ia32_gatherd_q256:
3668   case X86::BI__builtin_ia32_gatherq_q:
3669   case X86::BI__builtin_ia32_gatherq_q256:
3670   case X86::BI__builtin_ia32_gatherd_d:
3671   case X86::BI__builtin_ia32_gatherd_d256:
3672   case X86::BI__builtin_ia32_gatherq_d:
3673   case X86::BI__builtin_ia32_gatherq_d256:
3674   case X86::BI__builtin_ia32_gather3div2df:
3675   case X86::BI__builtin_ia32_gather3div2di:
3676   case X86::BI__builtin_ia32_gather3div4df:
3677   case X86::BI__builtin_ia32_gather3div4di:
3678   case X86::BI__builtin_ia32_gather3div4sf:
3679   case X86::BI__builtin_ia32_gather3div4si:
3680   case X86::BI__builtin_ia32_gather3div8sf:
3681   case X86::BI__builtin_ia32_gather3div8si:
3682   case X86::BI__builtin_ia32_gather3siv2df:
3683   case X86::BI__builtin_ia32_gather3siv2di:
3684   case X86::BI__builtin_ia32_gather3siv4df:
3685   case X86::BI__builtin_ia32_gather3siv4di:
3686   case X86::BI__builtin_ia32_gather3siv4sf:
3687   case X86::BI__builtin_ia32_gather3siv4si:
3688   case X86::BI__builtin_ia32_gather3siv8sf:
3689   case X86::BI__builtin_ia32_gather3siv8si:
3690   case X86::BI__builtin_ia32_gathersiv8df:
3691   case X86::BI__builtin_ia32_gathersiv16sf:
3692   case X86::BI__builtin_ia32_gatherdiv8df:
3693   case X86::BI__builtin_ia32_gatherdiv16sf:
3694   case X86::BI__builtin_ia32_gathersiv8di:
3695   case X86::BI__builtin_ia32_gathersiv16si:
3696   case X86::BI__builtin_ia32_gatherdiv8di:
3697   case X86::BI__builtin_ia32_gatherdiv16si:
3698   case X86::BI__builtin_ia32_scatterdiv2df:
3699   case X86::BI__builtin_ia32_scatterdiv2di:
3700   case X86::BI__builtin_ia32_scatterdiv4df:
3701   case X86::BI__builtin_ia32_scatterdiv4di:
3702   case X86::BI__builtin_ia32_scatterdiv4sf:
3703   case X86::BI__builtin_ia32_scatterdiv4si:
3704   case X86::BI__builtin_ia32_scatterdiv8sf:
3705   case X86::BI__builtin_ia32_scatterdiv8si:
3706   case X86::BI__builtin_ia32_scattersiv2df:
3707   case X86::BI__builtin_ia32_scattersiv2di:
3708   case X86::BI__builtin_ia32_scattersiv4df:
3709   case X86::BI__builtin_ia32_scattersiv4di:
3710   case X86::BI__builtin_ia32_scattersiv4sf:
3711   case X86::BI__builtin_ia32_scattersiv4si:
3712   case X86::BI__builtin_ia32_scattersiv8sf:
3713   case X86::BI__builtin_ia32_scattersiv8si:
3714   case X86::BI__builtin_ia32_scattersiv8df:
3715   case X86::BI__builtin_ia32_scattersiv16sf:
3716   case X86::BI__builtin_ia32_scatterdiv8df:
3717   case X86::BI__builtin_ia32_scatterdiv16sf:
3718   case X86::BI__builtin_ia32_scattersiv8di:
3719   case X86::BI__builtin_ia32_scattersiv16si:
3720   case X86::BI__builtin_ia32_scatterdiv8di:
3721   case X86::BI__builtin_ia32_scatterdiv16si:
3722     ArgNum = 4;
3723     break;
3724   }
3725 
3726   llvm::APSInt Result;
3727 
3728   // We can't check the value of a dependent argument.
3729   Expr *Arg = TheCall->getArg(ArgNum);
3730   if (Arg->isTypeDependent() || Arg->isValueDependent())
3731     return false;
3732 
3733   // Check constant-ness first.
3734   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3735     return true;
3736 
3737   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3738     return false;
3739 
3740   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3741          << Arg->getSourceRange();
3742 }
3743 
3744 static bool isX86_32Builtin(unsigned BuiltinID) {
3745   // These builtins only work on x86-32 targets.
3746   switch (BuiltinID) {
3747   case X86::BI__builtin_ia32_readeflags_u32:
3748   case X86::BI__builtin_ia32_writeeflags_u32:
3749     return true;
3750   }
3751 
3752   return false;
3753 }
3754 
3755 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3756   if (BuiltinID == X86::BI__builtin_cpu_supports)
3757     return SemaBuiltinCpuSupports(*this, TheCall);
3758 
3759   if (BuiltinID == X86::BI__builtin_cpu_is)
3760     return SemaBuiltinCpuIs(*this, TheCall);
3761 
3762   // Check for 32-bit only builtins on a 64-bit target.
3763   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3764   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3765     return Diag(TheCall->getCallee()->getBeginLoc(),
3766                 diag::err_32_bit_builtin_64_bit_tgt);
3767 
3768   // If the intrinsic has rounding or SAE make sure its valid.
3769   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3770     return true;
3771 
3772   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3773   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3774     return true;
3775 
3776   // For intrinsics which take an immediate value as part of the instruction,
3777   // range check them here.
3778   int i = 0, l = 0, u = 0;
3779   switch (BuiltinID) {
3780   default:
3781     return false;
3782   case X86::BI__builtin_ia32_vec_ext_v2si:
3783   case X86::BI__builtin_ia32_vec_ext_v2di:
3784   case X86::BI__builtin_ia32_vextractf128_pd256:
3785   case X86::BI__builtin_ia32_vextractf128_ps256:
3786   case X86::BI__builtin_ia32_vextractf128_si256:
3787   case X86::BI__builtin_ia32_extract128i256:
3788   case X86::BI__builtin_ia32_extractf64x4_mask:
3789   case X86::BI__builtin_ia32_extracti64x4_mask:
3790   case X86::BI__builtin_ia32_extractf32x8_mask:
3791   case X86::BI__builtin_ia32_extracti32x8_mask:
3792   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3793   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3794   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3795   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3796     i = 1; l = 0; u = 1;
3797     break;
3798   case X86::BI__builtin_ia32_vec_set_v2di:
3799   case X86::BI__builtin_ia32_vinsertf128_pd256:
3800   case X86::BI__builtin_ia32_vinsertf128_ps256:
3801   case X86::BI__builtin_ia32_vinsertf128_si256:
3802   case X86::BI__builtin_ia32_insert128i256:
3803   case X86::BI__builtin_ia32_insertf32x8:
3804   case X86::BI__builtin_ia32_inserti32x8:
3805   case X86::BI__builtin_ia32_insertf64x4:
3806   case X86::BI__builtin_ia32_inserti64x4:
3807   case X86::BI__builtin_ia32_insertf64x2_256:
3808   case X86::BI__builtin_ia32_inserti64x2_256:
3809   case X86::BI__builtin_ia32_insertf32x4_256:
3810   case X86::BI__builtin_ia32_inserti32x4_256:
3811     i = 2; l = 0; u = 1;
3812     break;
3813   case X86::BI__builtin_ia32_vpermilpd:
3814   case X86::BI__builtin_ia32_vec_ext_v4hi:
3815   case X86::BI__builtin_ia32_vec_ext_v4si:
3816   case X86::BI__builtin_ia32_vec_ext_v4sf:
3817   case X86::BI__builtin_ia32_vec_ext_v4di:
3818   case X86::BI__builtin_ia32_extractf32x4_mask:
3819   case X86::BI__builtin_ia32_extracti32x4_mask:
3820   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3821   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3822     i = 1; l = 0; u = 3;
3823     break;
3824   case X86::BI_mm_prefetch:
3825   case X86::BI__builtin_ia32_vec_ext_v8hi:
3826   case X86::BI__builtin_ia32_vec_ext_v8si:
3827     i = 1; l = 0; u = 7;
3828     break;
3829   case X86::BI__builtin_ia32_sha1rnds4:
3830   case X86::BI__builtin_ia32_blendpd:
3831   case X86::BI__builtin_ia32_shufpd:
3832   case X86::BI__builtin_ia32_vec_set_v4hi:
3833   case X86::BI__builtin_ia32_vec_set_v4si:
3834   case X86::BI__builtin_ia32_vec_set_v4di:
3835   case X86::BI__builtin_ia32_shuf_f32x4_256:
3836   case X86::BI__builtin_ia32_shuf_f64x2_256:
3837   case X86::BI__builtin_ia32_shuf_i32x4_256:
3838   case X86::BI__builtin_ia32_shuf_i64x2_256:
3839   case X86::BI__builtin_ia32_insertf64x2_512:
3840   case X86::BI__builtin_ia32_inserti64x2_512:
3841   case X86::BI__builtin_ia32_insertf32x4:
3842   case X86::BI__builtin_ia32_inserti32x4:
3843     i = 2; l = 0; u = 3;
3844     break;
3845   case X86::BI__builtin_ia32_vpermil2pd:
3846   case X86::BI__builtin_ia32_vpermil2pd256:
3847   case X86::BI__builtin_ia32_vpermil2ps:
3848   case X86::BI__builtin_ia32_vpermil2ps256:
3849     i = 3; l = 0; u = 3;
3850     break;
3851   case X86::BI__builtin_ia32_cmpb128_mask:
3852   case X86::BI__builtin_ia32_cmpw128_mask:
3853   case X86::BI__builtin_ia32_cmpd128_mask:
3854   case X86::BI__builtin_ia32_cmpq128_mask:
3855   case X86::BI__builtin_ia32_cmpb256_mask:
3856   case X86::BI__builtin_ia32_cmpw256_mask:
3857   case X86::BI__builtin_ia32_cmpd256_mask:
3858   case X86::BI__builtin_ia32_cmpq256_mask:
3859   case X86::BI__builtin_ia32_cmpb512_mask:
3860   case X86::BI__builtin_ia32_cmpw512_mask:
3861   case X86::BI__builtin_ia32_cmpd512_mask:
3862   case X86::BI__builtin_ia32_cmpq512_mask:
3863   case X86::BI__builtin_ia32_ucmpb128_mask:
3864   case X86::BI__builtin_ia32_ucmpw128_mask:
3865   case X86::BI__builtin_ia32_ucmpd128_mask:
3866   case X86::BI__builtin_ia32_ucmpq128_mask:
3867   case X86::BI__builtin_ia32_ucmpb256_mask:
3868   case X86::BI__builtin_ia32_ucmpw256_mask:
3869   case X86::BI__builtin_ia32_ucmpd256_mask:
3870   case X86::BI__builtin_ia32_ucmpq256_mask:
3871   case X86::BI__builtin_ia32_ucmpb512_mask:
3872   case X86::BI__builtin_ia32_ucmpw512_mask:
3873   case X86::BI__builtin_ia32_ucmpd512_mask:
3874   case X86::BI__builtin_ia32_ucmpq512_mask:
3875   case X86::BI__builtin_ia32_vpcomub:
3876   case X86::BI__builtin_ia32_vpcomuw:
3877   case X86::BI__builtin_ia32_vpcomud:
3878   case X86::BI__builtin_ia32_vpcomuq:
3879   case X86::BI__builtin_ia32_vpcomb:
3880   case X86::BI__builtin_ia32_vpcomw:
3881   case X86::BI__builtin_ia32_vpcomd:
3882   case X86::BI__builtin_ia32_vpcomq:
3883   case X86::BI__builtin_ia32_vec_set_v8hi:
3884   case X86::BI__builtin_ia32_vec_set_v8si:
3885     i = 2; l = 0; u = 7;
3886     break;
3887   case X86::BI__builtin_ia32_vpermilpd256:
3888   case X86::BI__builtin_ia32_roundps:
3889   case X86::BI__builtin_ia32_roundpd:
3890   case X86::BI__builtin_ia32_roundps256:
3891   case X86::BI__builtin_ia32_roundpd256:
3892   case X86::BI__builtin_ia32_getmantpd128_mask:
3893   case X86::BI__builtin_ia32_getmantpd256_mask:
3894   case X86::BI__builtin_ia32_getmantps128_mask:
3895   case X86::BI__builtin_ia32_getmantps256_mask:
3896   case X86::BI__builtin_ia32_getmantpd512_mask:
3897   case X86::BI__builtin_ia32_getmantps512_mask:
3898   case X86::BI__builtin_ia32_vec_ext_v16qi:
3899   case X86::BI__builtin_ia32_vec_ext_v16hi:
3900     i = 1; l = 0; u = 15;
3901     break;
3902   case X86::BI__builtin_ia32_pblendd128:
3903   case X86::BI__builtin_ia32_blendps:
3904   case X86::BI__builtin_ia32_blendpd256:
3905   case X86::BI__builtin_ia32_shufpd256:
3906   case X86::BI__builtin_ia32_roundss:
3907   case X86::BI__builtin_ia32_roundsd:
3908   case X86::BI__builtin_ia32_rangepd128_mask:
3909   case X86::BI__builtin_ia32_rangepd256_mask:
3910   case X86::BI__builtin_ia32_rangepd512_mask:
3911   case X86::BI__builtin_ia32_rangeps128_mask:
3912   case X86::BI__builtin_ia32_rangeps256_mask:
3913   case X86::BI__builtin_ia32_rangeps512_mask:
3914   case X86::BI__builtin_ia32_getmantsd_round_mask:
3915   case X86::BI__builtin_ia32_getmantss_round_mask:
3916   case X86::BI__builtin_ia32_vec_set_v16qi:
3917   case X86::BI__builtin_ia32_vec_set_v16hi:
3918     i = 2; l = 0; u = 15;
3919     break;
3920   case X86::BI__builtin_ia32_vec_ext_v32qi:
3921     i = 1; l = 0; u = 31;
3922     break;
3923   case X86::BI__builtin_ia32_cmpps:
3924   case X86::BI__builtin_ia32_cmpss:
3925   case X86::BI__builtin_ia32_cmppd:
3926   case X86::BI__builtin_ia32_cmpsd:
3927   case X86::BI__builtin_ia32_cmpps256:
3928   case X86::BI__builtin_ia32_cmppd256:
3929   case X86::BI__builtin_ia32_cmpps128_mask:
3930   case X86::BI__builtin_ia32_cmppd128_mask:
3931   case X86::BI__builtin_ia32_cmpps256_mask:
3932   case X86::BI__builtin_ia32_cmppd256_mask:
3933   case X86::BI__builtin_ia32_cmpps512_mask:
3934   case X86::BI__builtin_ia32_cmppd512_mask:
3935   case X86::BI__builtin_ia32_cmpsd_mask:
3936   case X86::BI__builtin_ia32_cmpss_mask:
3937   case X86::BI__builtin_ia32_vec_set_v32qi:
3938     i = 2; l = 0; u = 31;
3939     break;
3940   case X86::BI__builtin_ia32_permdf256:
3941   case X86::BI__builtin_ia32_permdi256:
3942   case X86::BI__builtin_ia32_permdf512:
3943   case X86::BI__builtin_ia32_permdi512:
3944   case X86::BI__builtin_ia32_vpermilps:
3945   case X86::BI__builtin_ia32_vpermilps256:
3946   case X86::BI__builtin_ia32_vpermilpd512:
3947   case X86::BI__builtin_ia32_vpermilps512:
3948   case X86::BI__builtin_ia32_pshufd:
3949   case X86::BI__builtin_ia32_pshufd256:
3950   case X86::BI__builtin_ia32_pshufd512:
3951   case X86::BI__builtin_ia32_pshufhw:
3952   case X86::BI__builtin_ia32_pshufhw256:
3953   case X86::BI__builtin_ia32_pshufhw512:
3954   case X86::BI__builtin_ia32_pshuflw:
3955   case X86::BI__builtin_ia32_pshuflw256:
3956   case X86::BI__builtin_ia32_pshuflw512:
3957   case X86::BI__builtin_ia32_vcvtps2ph:
3958   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3959   case X86::BI__builtin_ia32_vcvtps2ph256:
3960   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3961   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3962   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3963   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3964   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3965   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3966   case X86::BI__builtin_ia32_rndscaleps_mask:
3967   case X86::BI__builtin_ia32_rndscalepd_mask:
3968   case X86::BI__builtin_ia32_reducepd128_mask:
3969   case X86::BI__builtin_ia32_reducepd256_mask:
3970   case X86::BI__builtin_ia32_reducepd512_mask:
3971   case X86::BI__builtin_ia32_reduceps128_mask:
3972   case X86::BI__builtin_ia32_reduceps256_mask:
3973   case X86::BI__builtin_ia32_reduceps512_mask:
3974   case X86::BI__builtin_ia32_prold512:
3975   case X86::BI__builtin_ia32_prolq512:
3976   case X86::BI__builtin_ia32_prold128:
3977   case X86::BI__builtin_ia32_prold256:
3978   case X86::BI__builtin_ia32_prolq128:
3979   case X86::BI__builtin_ia32_prolq256:
3980   case X86::BI__builtin_ia32_prord512:
3981   case X86::BI__builtin_ia32_prorq512:
3982   case X86::BI__builtin_ia32_prord128:
3983   case X86::BI__builtin_ia32_prord256:
3984   case X86::BI__builtin_ia32_prorq128:
3985   case X86::BI__builtin_ia32_prorq256:
3986   case X86::BI__builtin_ia32_fpclasspd128_mask:
3987   case X86::BI__builtin_ia32_fpclasspd256_mask:
3988   case X86::BI__builtin_ia32_fpclassps128_mask:
3989   case X86::BI__builtin_ia32_fpclassps256_mask:
3990   case X86::BI__builtin_ia32_fpclassps512_mask:
3991   case X86::BI__builtin_ia32_fpclasspd512_mask:
3992   case X86::BI__builtin_ia32_fpclasssd_mask:
3993   case X86::BI__builtin_ia32_fpclassss_mask:
3994   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3995   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3996   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3997   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3998   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3999   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4000   case X86::BI__builtin_ia32_kshiftliqi:
4001   case X86::BI__builtin_ia32_kshiftlihi:
4002   case X86::BI__builtin_ia32_kshiftlisi:
4003   case X86::BI__builtin_ia32_kshiftlidi:
4004   case X86::BI__builtin_ia32_kshiftriqi:
4005   case X86::BI__builtin_ia32_kshiftrihi:
4006   case X86::BI__builtin_ia32_kshiftrisi:
4007   case X86::BI__builtin_ia32_kshiftridi:
4008     i = 1; l = 0; u = 255;
4009     break;
4010   case X86::BI__builtin_ia32_vperm2f128_pd256:
4011   case X86::BI__builtin_ia32_vperm2f128_ps256:
4012   case X86::BI__builtin_ia32_vperm2f128_si256:
4013   case X86::BI__builtin_ia32_permti256:
4014   case X86::BI__builtin_ia32_pblendw128:
4015   case X86::BI__builtin_ia32_pblendw256:
4016   case X86::BI__builtin_ia32_blendps256:
4017   case X86::BI__builtin_ia32_pblendd256:
4018   case X86::BI__builtin_ia32_palignr128:
4019   case X86::BI__builtin_ia32_palignr256:
4020   case X86::BI__builtin_ia32_palignr512:
4021   case X86::BI__builtin_ia32_alignq512:
4022   case X86::BI__builtin_ia32_alignd512:
4023   case X86::BI__builtin_ia32_alignd128:
4024   case X86::BI__builtin_ia32_alignd256:
4025   case X86::BI__builtin_ia32_alignq128:
4026   case X86::BI__builtin_ia32_alignq256:
4027   case X86::BI__builtin_ia32_vcomisd:
4028   case X86::BI__builtin_ia32_vcomiss:
4029   case X86::BI__builtin_ia32_shuf_f32x4:
4030   case X86::BI__builtin_ia32_shuf_f64x2:
4031   case X86::BI__builtin_ia32_shuf_i32x4:
4032   case X86::BI__builtin_ia32_shuf_i64x2:
4033   case X86::BI__builtin_ia32_shufpd512:
4034   case X86::BI__builtin_ia32_shufps:
4035   case X86::BI__builtin_ia32_shufps256:
4036   case X86::BI__builtin_ia32_shufps512:
4037   case X86::BI__builtin_ia32_dbpsadbw128:
4038   case X86::BI__builtin_ia32_dbpsadbw256:
4039   case X86::BI__builtin_ia32_dbpsadbw512:
4040   case X86::BI__builtin_ia32_vpshldd128:
4041   case X86::BI__builtin_ia32_vpshldd256:
4042   case X86::BI__builtin_ia32_vpshldd512:
4043   case X86::BI__builtin_ia32_vpshldq128:
4044   case X86::BI__builtin_ia32_vpshldq256:
4045   case X86::BI__builtin_ia32_vpshldq512:
4046   case X86::BI__builtin_ia32_vpshldw128:
4047   case X86::BI__builtin_ia32_vpshldw256:
4048   case X86::BI__builtin_ia32_vpshldw512:
4049   case X86::BI__builtin_ia32_vpshrdd128:
4050   case X86::BI__builtin_ia32_vpshrdd256:
4051   case X86::BI__builtin_ia32_vpshrdd512:
4052   case X86::BI__builtin_ia32_vpshrdq128:
4053   case X86::BI__builtin_ia32_vpshrdq256:
4054   case X86::BI__builtin_ia32_vpshrdq512:
4055   case X86::BI__builtin_ia32_vpshrdw128:
4056   case X86::BI__builtin_ia32_vpshrdw256:
4057   case X86::BI__builtin_ia32_vpshrdw512:
4058     i = 2; l = 0; u = 255;
4059     break;
4060   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4061   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4062   case X86::BI__builtin_ia32_fixupimmps512_mask:
4063   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4064   case X86::BI__builtin_ia32_fixupimmsd_mask:
4065   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4066   case X86::BI__builtin_ia32_fixupimmss_mask:
4067   case X86::BI__builtin_ia32_fixupimmss_maskz:
4068   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4069   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4070   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4071   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4072   case X86::BI__builtin_ia32_fixupimmps128_mask:
4073   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4074   case X86::BI__builtin_ia32_fixupimmps256_mask:
4075   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4076   case X86::BI__builtin_ia32_pternlogd512_mask:
4077   case X86::BI__builtin_ia32_pternlogd512_maskz:
4078   case X86::BI__builtin_ia32_pternlogq512_mask:
4079   case X86::BI__builtin_ia32_pternlogq512_maskz:
4080   case X86::BI__builtin_ia32_pternlogd128_mask:
4081   case X86::BI__builtin_ia32_pternlogd128_maskz:
4082   case X86::BI__builtin_ia32_pternlogd256_mask:
4083   case X86::BI__builtin_ia32_pternlogd256_maskz:
4084   case X86::BI__builtin_ia32_pternlogq128_mask:
4085   case X86::BI__builtin_ia32_pternlogq128_maskz:
4086   case X86::BI__builtin_ia32_pternlogq256_mask:
4087   case X86::BI__builtin_ia32_pternlogq256_maskz:
4088     i = 3; l = 0; u = 255;
4089     break;
4090   case X86::BI__builtin_ia32_gatherpfdpd:
4091   case X86::BI__builtin_ia32_gatherpfdps:
4092   case X86::BI__builtin_ia32_gatherpfqpd:
4093   case X86::BI__builtin_ia32_gatherpfqps:
4094   case X86::BI__builtin_ia32_scatterpfdpd:
4095   case X86::BI__builtin_ia32_scatterpfdps:
4096   case X86::BI__builtin_ia32_scatterpfqpd:
4097   case X86::BI__builtin_ia32_scatterpfqps:
4098     i = 4; l = 2; u = 3;
4099     break;
4100   case X86::BI__builtin_ia32_reducesd_mask:
4101   case X86::BI__builtin_ia32_reducess_mask:
4102   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4103   case X86::BI__builtin_ia32_rndscaless_round_mask:
4104     i = 4; l = 0; u = 255;
4105     break;
4106   }
4107 
4108   // Note that we don't force a hard error on the range check here, allowing
4109   // template-generated or macro-generated dead code to potentially have out-of-
4110   // range values. These need to code generate, but don't need to necessarily
4111   // make any sense. We use a warning that defaults to an error.
4112   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4113 }
4114 
4115 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4116 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4117 /// Returns true when the format fits the function and the FormatStringInfo has
4118 /// been populated.
4119 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4120                                FormatStringInfo *FSI) {
4121   FSI->HasVAListArg = Format->getFirstArg() == 0;
4122   FSI->FormatIdx = Format->getFormatIdx() - 1;
4123   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4124 
4125   // The way the format attribute works in GCC, the implicit this argument
4126   // of member functions is counted. However, it doesn't appear in our own
4127   // lists, so decrement format_idx in that case.
4128   if (IsCXXMember) {
4129     if(FSI->FormatIdx == 0)
4130       return false;
4131     --FSI->FormatIdx;
4132     if (FSI->FirstDataArg != 0)
4133       --FSI->FirstDataArg;
4134   }
4135   return true;
4136 }
4137 
4138 /// Checks if a the given expression evaluates to null.
4139 ///
4140 /// Returns true if the value evaluates to null.
4141 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4142   // If the expression has non-null type, it doesn't evaluate to null.
4143   if (auto nullability
4144         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4145     if (*nullability == NullabilityKind::NonNull)
4146       return false;
4147   }
4148 
4149   // As a special case, transparent unions initialized with zero are
4150   // considered null for the purposes of the nonnull attribute.
4151   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4152     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4153       if (const CompoundLiteralExpr *CLE =
4154           dyn_cast<CompoundLiteralExpr>(Expr))
4155         if (const InitListExpr *ILE =
4156             dyn_cast<InitListExpr>(CLE->getInitializer()))
4157           Expr = ILE->getInit(0);
4158   }
4159 
4160   bool Result;
4161   return (!Expr->isValueDependent() &&
4162           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4163           !Result);
4164 }
4165 
4166 static void CheckNonNullArgument(Sema &S,
4167                                  const Expr *ArgExpr,
4168                                  SourceLocation CallSiteLoc) {
4169   if (CheckNonNullExpr(S, ArgExpr))
4170     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4171                           S.PDiag(diag::warn_null_arg)
4172                               << ArgExpr->getSourceRange());
4173 }
4174 
4175 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4176   FormatStringInfo FSI;
4177   if ((GetFormatStringType(Format) == FST_NSString) &&
4178       getFormatStringInfo(Format, false, &FSI)) {
4179     Idx = FSI.FormatIdx;
4180     return true;
4181   }
4182   return false;
4183 }
4184 
4185 /// Diagnose use of %s directive in an NSString which is being passed
4186 /// as formatting string to formatting method.
4187 static void
4188 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4189                                         const NamedDecl *FDecl,
4190                                         Expr **Args,
4191                                         unsigned NumArgs) {
4192   unsigned Idx = 0;
4193   bool Format = false;
4194   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4195   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4196     Idx = 2;
4197     Format = true;
4198   }
4199   else
4200     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4201       if (S.GetFormatNSStringIdx(I, Idx)) {
4202         Format = true;
4203         break;
4204       }
4205     }
4206   if (!Format || NumArgs <= Idx)
4207     return;
4208   const Expr *FormatExpr = Args[Idx];
4209   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4210     FormatExpr = CSCE->getSubExpr();
4211   const StringLiteral *FormatString;
4212   if (const ObjCStringLiteral *OSL =
4213       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4214     FormatString = OSL->getString();
4215   else
4216     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4217   if (!FormatString)
4218     return;
4219   if (S.FormatStringHasSArg(FormatString)) {
4220     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4221       << "%s" << 1 << 1;
4222     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4223       << FDecl->getDeclName();
4224   }
4225 }
4226 
4227 /// Determine whether the given type has a non-null nullability annotation.
4228 static bool isNonNullType(ASTContext &ctx, QualType type) {
4229   if (auto nullability = type->getNullability(ctx))
4230     return *nullability == NullabilityKind::NonNull;
4231 
4232   return false;
4233 }
4234 
4235 static void CheckNonNullArguments(Sema &S,
4236                                   const NamedDecl *FDecl,
4237                                   const FunctionProtoType *Proto,
4238                                   ArrayRef<const Expr *> Args,
4239                                   SourceLocation CallSiteLoc) {
4240   assert((FDecl || Proto) && "Need a function declaration or prototype");
4241 
4242   // Already checked by by constant evaluator.
4243   if (S.isConstantEvaluated())
4244     return;
4245   // Check the attributes attached to the method/function itself.
4246   llvm::SmallBitVector NonNullArgs;
4247   if (FDecl) {
4248     // Handle the nonnull attribute on the function/method declaration itself.
4249     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4250       if (!NonNull->args_size()) {
4251         // Easy case: all pointer arguments are nonnull.
4252         for (const auto *Arg : Args)
4253           if (S.isValidPointerAttrType(Arg->getType()))
4254             CheckNonNullArgument(S, Arg, CallSiteLoc);
4255         return;
4256       }
4257 
4258       for (const ParamIdx &Idx : NonNull->args()) {
4259         unsigned IdxAST = Idx.getASTIndex();
4260         if (IdxAST >= Args.size())
4261           continue;
4262         if (NonNullArgs.empty())
4263           NonNullArgs.resize(Args.size());
4264         NonNullArgs.set(IdxAST);
4265       }
4266     }
4267   }
4268 
4269   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4270     // Handle the nonnull attribute on the parameters of the
4271     // function/method.
4272     ArrayRef<ParmVarDecl*> parms;
4273     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4274       parms = FD->parameters();
4275     else
4276       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4277 
4278     unsigned ParamIndex = 0;
4279     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4280          I != E; ++I, ++ParamIndex) {
4281       const ParmVarDecl *PVD = *I;
4282       if (PVD->hasAttr<NonNullAttr>() ||
4283           isNonNullType(S.Context, PVD->getType())) {
4284         if (NonNullArgs.empty())
4285           NonNullArgs.resize(Args.size());
4286 
4287         NonNullArgs.set(ParamIndex);
4288       }
4289     }
4290   } else {
4291     // If we have a non-function, non-method declaration but no
4292     // function prototype, try to dig out the function prototype.
4293     if (!Proto) {
4294       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4295         QualType type = VD->getType().getNonReferenceType();
4296         if (auto pointerType = type->getAs<PointerType>())
4297           type = pointerType->getPointeeType();
4298         else if (auto blockType = type->getAs<BlockPointerType>())
4299           type = blockType->getPointeeType();
4300         // FIXME: data member pointers?
4301 
4302         // Dig out the function prototype, if there is one.
4303         Proto = type->getAs<FunctionProtoType>();
4304       }
4305     }
4306 
4307     // Fill in non-null argument information from the nullability
4308     // information on the parameter types (if we have them).
4309     if (Proto) {
4310       unsigned Index = 0;
4311       for (auto paramType : Proto->getParamTypes()) {
4312         if (isNonNullType(S.Context, paramType)) {
4313           if (NonNullArgs.empty())
4314             NonNullArgs.resize(Args.size());
4315 
4316           NonNullArgs.set(Index);
4317         }
4318 
4319         ++Index;
4320       }
4321     }
4322   }
4323 
4324   // Check for non-null arguments.
4325   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4326        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4327     if (NonNullArgs[ArgIndex])
4328       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4329   }
4330 }
4331 
4332 /// Handles the checks for format strings, non-POD arguments to vararg
4333 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4334 /// attributes.
4335 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4336                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4337                      bool IsMemberFunction, SourceLocation Loc,
4338                      SourceRange Range, VariadicCallType CallType) {
4339   // FIXME: We should check as much as we can in the template definition.
4340   if (CurContext->isDependentContext())
4341     return;
4342 
4343   // Printf and scanf checking.
4344   llvm::SmallBitVector CheckedVarArgs;
4345   if (FDecl) {
4346     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4347       // Only create vector if there are format attributes.
4348       CheckedVarArgs.resize(Args.size());
4349 
4350       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4351                            CheckedVarArgs);
4352     }
4353   }
4354 
4355   // Refuse POD arguments that weren't caught by the format string
4356   // checks above.
4357   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4358   if (CallType != VariadicDoesNotApply &&
4359       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4360     unsigned NumParams = Proto ? Proto->getNumParams()
4361                        : FDecl && isa<FunctionDecl>(FDecl)
4362                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4363                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4364                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4365                        : 0;
4366 
4367     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4368       // Args[ArgIdx] can be null in malformed code.
4369       if (const Expr *Arg = Args[ArgIdx]) {
4370         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4371           checkVariadicArgument(Arg, CallType);
4372       }
4373     }
4374   }
4375 
4376   if (FDecl || Proto) {
4377     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4378 
4379     // Type safety checking.
4380     if (FDecl) {
4381       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4382         CheckArgumentWithTypeTag(I, Args, Loc);
4383     }
4384   }
4385 
4386   if (FD)
4387     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4388 }
4389 
4390 /// CheckConstructorCall - Check a constructor call for correctness and safety
4391 /// properties not enforced by the C type system.
4392 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4393                                 ArrayRef<const Expr *> Args,
4394                                 const FunctionProtoType *Proto,
4395                                 SourceLocation Loc) {
4396   VariadicCallType CallType =
4397     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4398   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4399             Loc, SourceRange(), CallType);
4400 }
4401 
4402 /// CheckFunctionCall - Check a direct function call for various correctness
4403 /// and safety properties not strictly enforced by the C type system.
4404 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4405                              const FunctionProtoType *Proto) {
4406   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4407                               isa<CXXMethodDecl>(FDecl);
4408   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4409                           IsMemberOperatorCall;
4410   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4411                                                   TheCall->getCallee());
4412   Expr** Args = TheCall->getArgs();
4413   unsigned NumArgs = TheCall->getNumArgs();
4414 
4415   Expr *ImplicitThis = nullptr;
4416   if (IsMemberOperatorCall) {
4417     // If this is a call to a member operator, hide the first argument
4418     // from checkCall.
4419     // FIXME: Our choice of AST representation here is less than ideal.
4420     ImplicitThis = Args[0];
4421     ++Args;
4422     --NumArgs;
4423   } else if (IsMemberFunction)
4424     ImplicitThis =
4425         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4426 
4427   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4428             IsMemberFunction, TheCall->getRParenLoc(),
4429             TheCall->getCallee()->getSourceRange(), CallType);
4430 
4431   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4432   // None of the checks below are needed for functions that don't have
4433   // simple names (e.g., C++ conversion functions).
4434   if (!FnInfo)
4435     return false;
4436 
4437   CheckAbsoluteValueFunction(TheCall, FDecl);
4438   CheckMaxUnsignedZero(TheCall, FDecl);
4439 
4440   if (getLangOpts().ObjC)
4441     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4442 
4443   unsigned CMId = FDecl->getMemoryFunctionKind();
4444   if (CMId == 0)
4445     return false;
4446 
4447   // Handle memory setting and copying functions.
4448   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4449     CheckStrlcpycatArguments(TheCall, FnInfo);
4450   else if (CMId == Builtin::BIstrncat)
4451     CheckStrncatArguments(TheCall, FnInfo);
4452   else
4453     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4454 
4455   return false;
4456 }
4457 
4458 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4459                                ArrayRef<const Expr *> Args) {
4460   VariadicCallType CallType =
4461       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4462 
4463   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4464             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4465             CallType);
4466 
4467   return false;
4468 }
4469 
4470 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4471                             const FunctionProtoType *Proto) {
4472   QualType Ty;
4473   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4474     Ty = V->getType().getNonReferenceType();
4475   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4476     Ty = F->getType().getNonReferenceType();
4477   else
4478     return false;
4479 
4480   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4481       !Ty->isFunctionProtoType())
4482     return false;
4483 
4484   VariadicCallType CallType;
4485   if (!Proto || !Proto->isVariadic()) {
4486     CallType = VariadicDoesNotApply;
4487   } else if (Ty->isBlockPointerType()) {
4488     CallType = VariadicBlock;
4489   } else { // Ty->isFunctionPointerType()
4490     CallType = VariadicFunction;
4491   }
4492 
4493   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4494             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4495             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4496             TheCall->getCallee()->getSourceRange(), CallType);
4497 
4498   return false;
4499 }
4500 
4501 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4502 /// such as function pointers returned from functions.
4503 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4504   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4505                                                   TheCall->getCallee());
4506   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4507             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4508             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4509             TheCall->getCallee()->getSourceRange(), CallType);
4510 
4511   return false;
4512 }
4513 
4514 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4515   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4516     return false;
4517 
4518   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4519   switch (Op) {
4520   case AtomicExpr::AO__c11_atomic_init:
4521   case AtomicExpr::AO__opencl_atomic_init:
4522     llvm_unreachable("There is no ordering argument for an init");
4523 
4524   case AtomicExpr::AO__c11_atomic_load:
4525   case AtomicExpr::AO__opencl_atomic_load:
4526   case AtomicExpr::AO__atomic_load_n:
4527   case AtomicExpr::AO__atomic_load:
4528     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4529            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4530 
4531   case AtomicExpr::AO__c11_atomic_store:
4532   case AtomicExpr::AO__opencl_atomic_store:
4533   case AtomicExpr::AO__atomic_store:
4534   case AtomicExpr::AO__atomic_store_n:
4535     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4536            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4537            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4538 
4539   default:
4540     return true;
4541   }
4542 }
4543 
4544 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4545                                          AtomicExpr::AtomicOp Op) {
4546   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4547   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4548   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4549   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4550                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4551                          Op);
4552 }
4553 
4554 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4555                                  SourceLocation RParenLoc, MultiExprArg Args,
4556                                  AtomicExpr::AtomicOp Op,
4557                                  AtomicArgumentOrder ArgOrder) {
4558   // All the non-OpenCL operations take one of the following forms.
4559   // The OpenCL operations take the __c11 forms with one extra argument for
4560   // synchronization scope.
4561   enum {
4562     // C    __c11_atomic_init(A *, C)
4563     Init,
4564 
4565     // C    __c11_atomic_load(A *, int)
4566     Load,
4567 
4568     // void __atomic_load(A *, CP, int)
4569     LoadCopy,
4570 
4571     // void __atomic_store(A *, CP, int)
4572     Copy,
4573 
4574     // C    __c11_atomic_add(A *, M, int)
4575     Arithmetic,
4576 
4577     // C    __atomic_exchange_n(A *, CP, int)
4578     Xchg,
4579 
4580     // void __atomic_exchange(A *, C *, CP, int)
4581     GNUXchg,
4582 
4583     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4584     C11CmpXchg,
4585 
4586     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4587     GNUCmpXchg
4588   } Form = Init;
4589 
4590   const unsigned NumForm = GNUCmpXchg + 1;
4591   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4592   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4593   // where:
4594   //   C is an appropriate type,
4595   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4596   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4597   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4598   //   the int parameters are for orderings.
4599 
4600   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4601       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4602       "need to update code for modified forms");
4603   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4604                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4605                         AtomicExpr::AO__atomic_load,
4606                 "need to update code for modified C11 atomics");
4607   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4608                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4609   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4610                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4611                IsOpenCL;
4612   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4613              Op == AtomicExpr::AO__atomic_store_n ||
4614              Op == AtomicExpr::AO__atomic_exchange_n ||
4615              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4616   bool IsAddSub = false;
4617 
4618   switch (Op) {
4619   case AtomicExpr::AO__c11_atomic_init:
4620   case AtomicExpr::AO__opencl_atomic_init:
4621     Form = Init;
4622     break;
4623 
4624   case AtomicExpr::AO__c11_atomic_load:
4625   case AtomicExpr::AO__opencl_atomic_load:
4626   case AtomicExpr::AO__atomic_load_n:
4627     Form = Load;
4628     break;
4629 
4630   case AtomicExpr::AO__atomic_load:
4631     Form = LoadCopy;
4632     break;
4633 
4634   case AtomicExpr::AO__c11_atomic_store:
4635   case AtomicExpr::AO__opencl_atomic_store:
4636   case AtomicExpr::AO__atomic_store:
4637   case AtomicExpr::AO__atomic_store_n:
4638     Form = Copy;
4639     break;
4640 
4641   case AtomicExpr::AO__c11_atomic_fetch_add:
4642   case AtomicExpr::AO__c11_atomic_fetch_sub:
4643   case AtomicExpr::AO__opencl_atomic_fetch_add:
4644   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4645   case AtomicExpr::AO__opencl_atomic_fetch_min:
4646   case AtomicExpr::AO__opencl_atomic_fetch_max:
4647   case AtomicExpr::AO__atomic_fetch_add:
4648   case AtomicExpr::AO__atomic_fetch_sub:
4649   case AtomicExpr::AO__atomic_add_fetch:
4650   case AtomicExpr::AO__atomic_sub_fetch:
4651     IsAddSub = true;
4652     LLVM_FALLTHROUGH;
4653   case AtomicExpr::AO__c11_atomic_fetch_and:
4654   case AtomicExpr::AO__c11_atomic_fetch_or:
4655   case AtomicExpr::AO__c11_atomic_fetch_xor:
4656   case AtomicExpr::AO__opencl_atomic_fetch_and:
4657   case AtomicExpr::AO__opencl_atomic_fetch_or:
4658   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4659   case AtomicExpr::AO__atomic_fetch_and:
4660   case AtomicExpr::AO__atomic_fetch_or:
4661   case AtomicExpr::AO__atomic_fetch_xor:
4662   case AtomicExpr::AO__atomic_fetch_nand:
4663   case AtomicExpr::AO__atomic_and_fetch:
4664   case AtomicExpr::AO__atomic_or_fetch:
4665   case AtomicExpr::AO__atomic_xor_fetch:
4666   case AtomicExpr::AO__atomic_nand_fetch:
4667   case AtomicExpr::AO__c11_atomic_fetch_min:
4668   case AtomicExpr::AO__c11_atomic_fetch_max:
4669   case AtomicExpr::AO__atomic_min_fetch:
4670   case AtomicExpr::AO__atomic_max_fetch:
4671   case AtomicExpr::AO__atomic_fetch_min:
4672   case AtomicExpr::AO__atomic_fetch_max:
4673     Form = Arithmetic;
4674     break;
4675 
4676   case AtomicExpr::AO__c11_atomic_exchange:
4677   case AtomicExpr::AO__opencl_atomic_exchange:
4678   case AtomicExpr::AO__atomic_exchange_n:
4679     Form = Xchg;
4680     break;
4681 
4682   case AtomicExpr::AO__atomic_exchange:
4683     Form = GNUXchg;
4684     break;
4685 
4686   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4687   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4688   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4689   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4690     Form = C11CmpXchg;
4691     break;
4692 
4693   case AtomicExpr::AO__atomic_compare_exchange:
4694   case AtomicExpr::AO__atomic_compare_exchange_n:
4695     Form = GNUCmpXchg;
4696     break;
4697   }
4698 
4699   unsigned AdjustedNumArgs = NumArgs[Form];
4700   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4701     ++AdjustedNumArgs;
4702   // Check we have the right number of arguments.
4703   if (Args.size() < AdjustedNumArgs) {
4704     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4705         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4706         << ExprRange;
4707     return ExprError();
4708   } else if (Args.size() > AdjustedNumArgs) {
4709     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4710          diag::err_typecheck_call_too_many_args)
4711         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4712         << ExprRange;
4713     return ExprError();
4714   }
4715 
4716   // Inspect the first argument of the atomic operation.
4717   Expr *Ptr = Args[0];
4718   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4719   if (ConvertedPtr.isInvalid())
4720     return ExprError();
4721 
4722   Ptr = ConvertedPtr.get();
4723   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4724   if (!pointerType) {
4725     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4726         << Ptr->getType() << Ptr->getSourceRange();
4727     return ExprError();
4728   }
4729 
4730   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4731   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4732   QualType ValType = AtomTy; // 'C'
4733   if (IsC11) {
4734     if (!AtomTy->isAtomicType()) {
4735       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4736           << Ptr->getType() << Ptr->getSourceRange();
4737       return ExprError();
4738     }
4739     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4740         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4741       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4742           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4743           << Ptr->getSourceRange();
4744       return ExprError();
4745     }
4746     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4747   } else if (Form != Load && Form != LoadCopy) {
4748     if (ValType.isConstQualified()) {
4749       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4750           << Ptr->getType() << Ptr->getSourceRange();
4751       return ExprError();
4752     }
4753   }
4754 
4755   // For an arithmetic operation, the implied arithmetic must be well-formed.
4756   if (Form == Arithmetic) {
4757     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4758     if (IsAddSub && !ValType->isIntegerType()
4759         && !ValType->isPointerType()) {
4760       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4761           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4762       return ExprError();
4763     }
4764     if (!IsAddSub && !ValType->isIntegerType()) {
4765       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4766           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4767       return ExprError();
4768     }
4769     if (IsC11 && ValType->isPointerType() &&
4770         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4771                             diag::err_incomplete_type)) {
4772       return ExprError();
4773     }
4774   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4775     // For __atomic_*_n operations, the value type must be a scalar integral or
4776     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4777     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4778         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4779     return ExprError();
4780   }
4781 
4782   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4783       !AtomTy->isScalarType()) {
4784     // For GNU atomics, require a trivially-copyable type. This is not part of
4785     // the GNU atomics specification, but we enforce it for sanity.
4786     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4787         << Ptr->getType() << Ptr->getSourceRange();
4788     return ExprError();
4789   }
4790 
4791   switch (ValType.getObjCLifetime()) {
4792   case Qualifiers::OCL_None:
4793   case Qualifiers::OCL_ExplicitNone:
4794     // okay
4795     break;
4796 
4797   case Qualifiers::OCL_Weak:
4798   case Qualifiers::OCL_Strong:
4799   case Qualifiers::OCL_Autoreleasing:
4800     // FIXME: Can this happen? By this point, ValType should be known
4801     // to be trivially copyable.
4802     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4803         << ValType << Ptr->getSourceRange();
4804     return ExprError();
4805   }
4806 
4807   // All atomic operations have an overload which takes a pointer to a volatile
4808   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4809   // into the result or the other operands. Similarly atomic_load takes a
4810   // pointer to a const 'A'.
4811   ValType.removeLocalVolatile();
4812   ValType.removeLocalConst();
4813   QualType ResultType = ValType;
4814   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4815       Form == Init)
4816     ResultType = Context.VoidTy;
4817   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4818     ResultType = Context.BoolTy;
4819 
4820   // The type of a parameter passed 'by value'. In the GNU atomics, such
4821   // arguments are actually passed as pointers.
4822   QualType ByValType = ValType; // 'CP'
4823   bool IsPassedByAddress = false;
4824   if (!IsC11 && !IsN) {
4825     ByValType = Ptr->getType();
4826     IsPassedByAddress = true;
4827   }
4828 
4829   SmallVector<Expr *, 5> APIOrderedArgs;
4830   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4831     APIOrderedArgs.push_back(Args[0]);
4832     switch (Form) {
4833     case Init:
4834     case Load:
4835       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4836       break;
4837     case LoadCopy:
4838     case Copy:
4839     case Arithmetic:
4840     case Xchg:
4841       APIOrderedArgs.push_back(Args[2]); // Val1
4842       APIOrderedArgs.push_back(Args[1]); // Order
4843       break;
4844     case GNUXchg:
4845       APIOrderedArgs.push_back(Args[2]); // Val1
4846       APIOrderedArgs.push_back(Args[3]); // Val2
4847       APIOrderedArgs.push_back(Args[1]); // Order
4848       break;
4849     case C11CmpXchg:
4850       APIOrderedArgs.push_back(Args[2]); // Val1
4851       APIOrderedArgs.push_back(Args[4]); // Val2
4852       APIOrderedArgs.push_back(Args[1]); // Order
4853       APIOrderedArgs.push_back(Args[3]); // OrderFail
4854       break;
4855     case GNUCmpXchg:
4856       APIOrderedArgs.push_back(Args[2]); // Val1
4857       APIOrderedArgs.push_back(Args[4]); // Val2
4858       APIOrderedArgs.push_back(Args[5]); // Weak
4859       APIOrderedArgs.push_back(Args[1]); // Order
4860       APIOrderedArgs.push_back(Args[3]); // OrderFail
4861       break;
4862     }
4863   } else
4864     APIOrderedArgs.append(Args.begin(), Args.end());
4865 
4866   // The first argument's non-CV pointer type is used to deduce the type of
4867   // subsequent arguments, except for:
4868   //  - weak flag (always converted to bool)
4869   //  - memory order (always converted to int)
4870   //  - scope  (always converted to int)
4871   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4872     QualType Ty;
4873     if (i < NumVals[Form] + 1) {
4874       switch (i) {
4875       case 0:
4876         // The first argument is always a pointer. It has a fixed type.
4877         // It is always dereferenced, a nullptr is undefined.
4878         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4879         // Nothing else to do: we already know all we want about this pointer.
4880         continue;
4881       case 1:
4882         // The second argument is the non-atomic operand. For arithmetic, this
4883         // is always passed by value, and for a compare_exchange it is always
4884         // passed by address. For the rest, GNU uses by-address and C11 uses
4885         // by-value.
4886         assert(Form != Load);
4887         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4888           Ty = ValType;
4889         else if (Form == Copy || Form == Xchg) {
4890           if (IsPassedByAddress) {
4891             // The value pointer is always dereferenced, a nullptr is undefined.
4892             CheckNonNullArgument(*this, APIOrderedArgs[i],
4893                                  ExprRange.getBegin());
4894           }
4895           Ty = ByValType;
4896         } else if (Form == Arithmetic)
4897           Ty = Context.getPointerDiffType();
4898         else {
4899           Expr *ValArg = APIOrderedArgs[i];
4900           // The value pointer is always dereferenced, a nullptr is undefined.
4901           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4902           LangAS AS = LangAS::Default;
4903           // Keep address space of non-atomic pointer type.
4904           if (const PointerType *PtrTy =
4905                   ValArg->getType()->getAs<PointerType>()) {
4906             AS = PtrTy->getPointeeType().getAddressSpace();
4907           }
4908           Ty = Context.getPointerType(
4909               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4910         }
4911         break;
4912       case 2:
4913         // The third argument to compare_exchange / GNU exchange is the desired
4914         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4915         if (IsPassedByAddress)
4916           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4917         Ty = ByValType;
4918         break;
4919       case 3:
4920         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4921         Ty = Context.BoolTy;
4922         break;
4923       }
4924     } else {
4925       // The order(s) and scope are always converted to int.
4926       Ty = Context.IntTy;
4927     }
4928 
4929     InitializedEntity Entity =
4930         InitializedEntity::InitializeParameter(Context, Ty, false);
4931     ExprResult Arg = APIOrderedArgs[i];
4932     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4933     if (Arg.isInvalid())
4934       return true;
4935     APIOrderedArgs[i] = Arg.get();
4936   }
4937 
4938   // Permute the arguments into a 'consistent' order.
4939   SmallVector<Expr*, 5> SubExprs;
4940   SubExprs.push_back(Ptr);
4941   switch (Form) {
4942   case Init:
4943     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4944     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4945     break;
4946   case Load:
4947     SubExprs.push_back(APIOrderedArgs[1]); // Order
4948     break;
4949   case LoadCopy:
4950   case Copy:
4951   case Arithmetic:
4952   case Xchg:
4953     SubExprs.push_back(APIOrderedArgs[2]); // Order
4954     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4955     break;
4956   case GNUXchg:
4957     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4958     SubExprs.push_back(APIOrderedArgs[3]); // Order
4959     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4960     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4961     break;
4962   case C11CmpXchg:
4963     SubExprs.push_back(APIOrderedArgs[3]); // Order
4964     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4965     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4966     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4967     break;
4968   case GNUCmpXchg:
4969     SubExprs.push_back(APIOrderedArgs[4]); // Order
4970     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4971     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4972     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4973     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4974     break;
4975   }
4976 
4977   if (SubExprs.size() >= 2 && Form != Init) {
4978     llvm::APSInt Result(32);
4979     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4980         !isValidOrderingForOp(Result.getSExtValue(), Op))
4981       Diag(SubExprs[1]->getBeginLoc(),
4982            diag::warn_atomic_op_has_invalid_memory_order)
4983           << SubExprs[1]->getSourceRange();
4984   }
4985 
4986   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4987     auto *Scope = Args[Args.size() - 1];
4988     llvm::APSInt Result(32);
4989     if (Scope->isIntegerConstantExpr(Result, Context) &&
4990         !ScopeModel->isValid(Result.getZExtValue())) {
4991       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4992           << Scope->getSourceRange();
4993     }
4994     SubExprs.push_back(Scope);
4995   }
4996 
4997   AtomicExpr *AE = new (Context)
4998       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4999 
5000   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5001        Op == AtomicExpr::AO__c11_atomic_store ||
5002        Op == AtomicExpr::AO__opencl_atomic_load ||
5003        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5004       Context.AtomicUsesUnsupportedLibcall(AE))
5005     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5006         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5007              Op == AtomicExpr::AO__opencl_atomic_load)
5008                 ? 0
5009                 : 1);
5010 
5011   return AE;
5012 }
5013 
5014 /// checkBuiltinArgument - Given a call to a builtin function, perform
5015 /// normal type-checking on the given argument, updating the call in
5016 /// place.  This is useful when a builtin function requires custom
5017 /// type-checking for some of its arguments but not necessarily all of
5018 /// them.
5019 ///
5020 /// Returns true on error.
5021 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5022   FunctionDecl *Fn = E->getDirectCallee();
5023   assert(Fn && "builtin call without direct callee!");
5024 
5025   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5026   InitializedEntity Entity =
5027     InitializedEntity::InitializeParameter(S.Context, Param);
5028 
5029   ExprResult Arg = E->getArg(0);
5030   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5031   if (Arg.isInvalid())
5032     return true;
5033 
5034   E->setArg(ArgIndex, Arg.get());
5035   return false;
5036 }
5037 
5038 /// We have a call to a function like __sync_fetch_and_add, which is an
5039 /// overloaded function based on the pointer type of its first argument.
5040 /// The main BuildCallExpr routines have already promoted the types of
5041 /// arguments because all of these calls are prototyped as void(...).
5042 ///
5043 /// This function goes through and does final semantic checking for these
5044 /// builtins, as well as generating any warnings.
5045 ExprResult
5046 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5047   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5048   Expr *Callee = TheCall->getCallee();
5049   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5050   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5051 
5052   // Ensure that we have at least one argument to do type inference from.
5053   if (TheCall->getNumArgs() < 1) {
5054     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5055         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5056     return ExprError();
5057   }
5058 
5059   // Inspect the first argument of the atomic builtin.  This should always be
5060   // a pointer type, whose element is an integral scalar or pointer type.
5061   // Because it is a pointer type, we don't have to worry about any implicit
5062   // casts here.
5063   // FIXME: We don't allow floating point scalars as input.
5064   Expr *FirstArg = TheCall->getArg(0);
5065   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5066   if (FirstArgResult.isInvalid())
5067     return ExprError();
5068   FirstArg = FirstArgResult.get();
5069   TheCall->setArg(0, FirstArg);
5070 
5071   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5072   if (!pointerType) {
5073     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5074         << FirstArg->getType() << FirstArg->getSourceRange();
5075     return ExprError();
5076   }
5077 
5078   QualType ValType = pointerType->getPointeeType();
5079   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5080       !ValType->isBlockPointerType()) {
5081     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5082         << FirstArg->getType() << FirstArg->getSourceRange();
5083     return ExprError();
5084   }
5085 
5086   if (ValType.isConstQualified()) {
5087     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5088         << FirstArg->getType() << FirstArg->getSourceRange();
5089     return ExprError();
5090   }
5091 
5092   switch (ValType.getObjCLifetime()) {
5093   case Qualifiers::OCL_None:
5094   case Qualifiers::OCL_ExplicitNone:
5095     // okay
5096     break;
5097 
5098   case Qualifiers::OCL_Weak:
5099   case Qualifiers::OCL_Strong:
5100   case Qualifiers::OCL_Autoreleasing:
5101     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5102         << ValType << FirstArg->getSourceRange();
5103     return ExprError();
5104   }
5105 
5106   // Strip any qualifiers off ValType.
5107   ValType = ValType.getUnqualifiedType();
5108 
5109   // The majority of builtins return a value, but a few have special return
5110   // types, so allow them to override appropriately below.
5111   QualType ResultType = ValType;
5112 
5113   // We need to figure out which concrete builtin this maps onto.  For example,
5114   // __sync_fetch_and_add with a 2 byte object turns into
5115   // __sync_fetch_and_add_2.
5116 #define BUILTIN_ROW(x) \
5117   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5118     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5119 
5120   static const unsigned BuiltinIndices[][5] = {
5121     BUILTIN_ROW(__sync_fetch_and_add),
5122     BUILTIN_ROW(__sync_fetch_and_sub),
5123     BUILTIN_ROW(__sync_fetch_and_or),
5124     BUILTIN_ROW(__sync_fetch_and_and),
5125     BUILTIN_ROW(__sync_fetch_and_xor),
5126     BUILTIN_ROW(__sync_fetch_and_nand),
5127 
5128     BUILTIN_ROW(__sync_add_and_fetch),
5129     BUILTIN_ROW(__sync_sub_and_fetch),
5130     BUILTIN_ROW(__sync_and_and_fetch),
5131     BUILTIN_ROW(__sync_or_and_fetch),
5132     BUILTIN_ROW(__sync_xor_and_fetch),
5133     BUILTIN_ROW(__sync_nand_and_fetch),
5134 
5135     BUILTIN_ROW(__sync_val_compare_and_swap),
5136     BUILTIN_ROW(__sync_bool_compare_and_swap),
5137     BUILTIN_ROW(__sync_lock_test_and_set),
5138     BUILTIN_ROW(__sync_lock_release),
5139     BUILTIN_ROW(__sync_swap)
5140   };
5141 #undef BUILTIN_ROW
5142 
5143   // Determine the index of the size.
5144   unsigned SizeIndex;
5145   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5146   case 1: SizeIndex = 0; break;
5147   case 2: SizeIndex = 1; break;
5148   case 4: SizeIndex = 2; break;
5149   case 8: SizeIndex = 3; break;
5150   case 16: SizeIndex = 4; break;
5151   default:
5152     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5153         << FirstArg->getType() << FirstArg->getSourceRange();
5154     return ExprError();
5155   }
5156 
5157   // Each of these builtins has one pointer argument, followed by some number of
5158   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5159   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5160   // as the number of fixed args.
5161   unsigned BuiltinID = FDecl->getBuiltinID();
5162   unsigned BuiltinIndex, NumFixed = 1;
5163   bool WarnAboutSemanticsChange = false;
5164   switch (BuiltinID) {
5165   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5166   case Builtin::BI__sync_fetch_and_add:
5167   case Builtin::BI__sync_fetch_and_add_1:
5168   case Builtin::BI__sync_fetch_and_add_2:
5169   case Builtin::BI__sync_fetch_and_add_4:
5170   case Builtin::BI__sync_fetch_and_add_8:
5171   case Builtin::BI__sync_fetch_and_add_16:
5172     BuiltinIndex = 0;
5173     break;
5174 
5175   case Builtin::BI__sync_fetch_and_sub:
5176   case Builtin::BI__sync_fetch_and_sub_1:
5177   case Builtin::BI__sync_fetch_and_sub_2:
5178   case Builtin::BI__sync_fetch_and_sub_4:
5179   case Builtin::BI__sync_fetch_and_sub_8:
5180   case Builtin::BI__sync_fetch_and_sub_16:
5181     BuiltinIndex = 1;
5182     break;
5183 
5184   case Builtin::BI__sync_fetch_and_or:
5185   case Builtin::BI__sync_fetch_and_or_1:
5186   case Builtin::BI__sync_fetch_and_or_2:
5187   case Builtin::BI__sync_fetch_and_or_4:
5188   case Builtin::BI__sync_fetch_and_or_8:
5189   case Builtin::BI__sync_fetch_and_or_16:
5190     BuiltinIndex = 2;
5191     break;
5192 
5193   case Builtin::BI__sync_fetch_and_and:
5194   case Builtin::BI__sync_fetch_and_and_1:
5195   case Builtin::BI__sync_fetch_and_and_2:
5196   case Builtin::BI__sync_fetch_and_and_4:
5197   case Builtin::BI__sync_fetch_and_and_8:
5198   case Builtin::BI__sync_fetch_and_and_16:
5199     BuiltinIndex = 3;
5200     break;
5201 
5202   case Builtin::BI__sync_fetch_and_xor:
5203   case Builtin::BI__sync_fetch_and_xor_1:
5204   case Builtin::BI__sync_fetch_and_xor_2:
5205   case Builtin::BI__sync_fetch_and_xor_4:
5206   case Builtin::BI__sync_fetch_and_xor_8:
5207   case Builtin::BI__sync_fetch_and_xor_16:
5208     BuiltinIndex = 4;
5209     break;
5210 
5211   case Builtin::BI__sync_fetch_and_nand:
5212   case Builtin::BI__sync_fetch_and_nand_1:
5213   case Builtin::BI__sync_fetch_and_nand_2:
5214   case Builtin::BI__sync_fetch_and_nand_4:
5215   case Builtin::BI__sync_fetch_and_nand_8:
5216   case Builtin::BI__sync_fetch_and_nand_16:
5217     BuiltinIndex = 5;
5218     WarnAboutSemanticsChange = true;
5219     break;
5220 
5221   case Builtin::BI__sync_add_and_fetch:
5222   case Builtin::BI__sync_add_and_fetch_1:
5223   case Builtin::BI__sync_add_and_fetch_2:
5224   case Builtin::BI__sync_add_and_fetch_4:
5225   case Builtin::BI__sync_add_and_fetch_8:
5226   case Builtin::BI__sync_add_and_fetch_16:
5227     BuiltinIndex = 6;
5228     break;
5229 
5230   case Builtin::BI__sync_sub_and_fetch:
5231   case Builtin::BI__sync_sub_and_fetch_1:
5232   case Builtin::BI__sync_sub_and_fetch_2:
5233   case Builtin::BI__sync_sub_and_fetch_4:
5234   case Builtin::BI__sync_sub_and_fetch_8:
5235   case Builtin::BI__sync_sub_and_fetch_16:
5236     BuiltinIndex = 7;
5237     break;
5238 
5239   case Builtin::BI__sync_and_and_fetch:
5240   case Builtin::BI__sync_and_and_fetch_1:
5241   case Builtin::BI__sync_and_and_fetch_2:
5242   case Builtin::BI__sync_and_and_fetch_4:
5243   case Builtin::BI__sync_and_and_fetch_8:
5244   case Builtin::BI__sync_and_and_fetch_16:
5245     BuiltinIndex = 8;
5246     break;
5247 
5248   case Builtin::BI__sync_or_and_fetch:
5249   case Builtin::BI__sync_or_and_fetch_1:
5250   case Builtin::BI__sync_or_and_fetch_2:
5251   case Builtin::BI__sync_or_and_fetch_4:
5252   case Builtin::BI__sync_or_and_fetch_8:
5253   case Builtin::BI__sync_or_and_fetch_16:
5254     BuiltinIndex = 9;
5255     break;
5256 
5257   case Builtin::BI__sync_xor_and_fetch:
5258   case Builtin::BI__sync_xor_and_fetch_1:
5259   case Builtin::BI__sync_xor_and_fetch_2:
5260   case Builtin::BI__sync_xor_and_fetch_4:
5261   case Builtin::BI__sync_xor_and_fetch_8:
5262   case Builtin::BI__sync_xor_and_fetch_16:
5263     BuiltinIndex = 10;
5264     break;
5265 
5266   case Builtin::BI__sync_nand_and_fetch:
5267   case Builtin::BI__sync_nand_and_fetch_1:
5268   case Builtin::BI__sync_nand_and_fetch_2:
5269   case Builtin::BI__sync_nand_and_fetch_4:
5270   case Builtin::BI__sync_nand_and_fetch_8:
5271   case Builtin::BI__sync_nand_and_fetch_16:
5272     BuiltinIndex = 11;
5273     WarnAboutSemanticsChange = true;
5274     break;
5275 
5276   case Builtin::BI__sync_val_compare_and_swap:
5277   case Builtin::BI__sync_val_compare_and_swap_1:
5278   case Builtin::BI__sync_val_compare_and_swap_2:
5279   case Builtin::BI__sync_val_compare_and_swap_4:
5280   case Builtin::BI__sync_val_compare_and_swap_8:
5281   case Builtin::BI__sync_val_compare_and_swap_16:
5282     BuiltinIndex = 12;
5283     NumFixed = 2;
5284     break;
5285 
5286   case Builtin::BI__sync_bool_compare_and_swap:
5287   case Builtin::BI__sync_bool_compare_and_swap_1:
5288   case Builtin::BI__sync_bool_compare_and_swap_2:
5289   case Builtin::BI__sync_bool_compare_and_swap_4:
5290   case Builtin::BI__sync_bool_compare_and_swap_8:
5291   case Builtin::BI__sync_bool_compare_and_swap_16:
5292     BuiltinIndex = 13;
5293     NumFixed = 2;
5294     ResultType = Context.BoolTy;
5295     break;
5296 
5297   case Builtin::BI__sync_lock_test_and_set:
5298   case Builtin::BI__sync_lock_test_and_set_1:
5299   case Builtin::BI__sync_lock_test_and_set_2:
5300   case Builtin::BI__sync_lock_test_and_set_4:
5301   case Builtin::BI__sync_lock_test_and_set_8:
5302   case Builtin::BI__sync_lock_test_and_set_16:
5303     BuiltinIndex = 14;
5304     break;
5305 
5306   case Builtin::BI__sync_lock_release:
5307   case Builtin::BI__sync_lock_release_1:
5308   case Builtin::BI__sync_lock_release_2:
5309   case Builtin::BI__sync_lock_release_4:
5310   case Builtin::BI__sync_lock_release_8:
5311   case Builtin::BI__sync_lock_release_16:
5312     BuiltinIndex = 15;
5313     NumFixed = 0;
5314     ResultType = Context.VoidTy;
5315     break;
5316 
5317   case Builtin::BI__sync_swap:
5318   case Builtin::BI__sync_swap_1:
5319   case Builtin::BI__sync_swap_2:
5320   case Builtin::BI__sync_swap_4:
5321   case Builtin::BI__sync_swap_8:
5322   case Builtin::BI__sync_swap_16:
5323     BuiltinIndex = 16;
5324     break;
5325   }
5326 
5327   // Now that we know how many fixed arguments we expect, first check that we
5328   // have at least that many.
5329   if (TheCall->getNumArgs() < 1+NumFixed) {
5330     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5331         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5332         << Callee->getSourceRange();
5333     return ExprError();
5334   }
5335 
5336   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5337       << Callee->getSourceRange();
5338 
5339   if (WarnAboutSemanticsChange) {
5340     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5341         << Callee->getSourceRange();
5342   }
5343 
5344   // Get the decl for the concrete builtin from this, we can tell what the
5345   // concrete integer type we should convert to is.
5346   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5347   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5348   FunctionDecl *NewBuiltinDecl;
5349   if (NewBuiltinID == BuiltinID)
5350     NewBuiltinDecl = FDecl;
5351   else {
5352     // Perform builtin lookup to avoid redeclaring it.
5353     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5354     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5355     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5356     assert(Res.getFoundDecl());
5357     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5358     if (!NewBuiltinDecl)
5359       return ExprError();
5360   }
5361 
5362   // The first argument --- the pointer --- has a fixed type; we
5363   // deduce the types of the rest of the arguments accordingly.  Walk
5364   // the remaining arguments, converting them to the deduced value type.
5365   for (unsigned i = 0; i != NumFixed; ++i) {
5366     ExprResult Arg = TheCall->getArg(i+1);
5367 
5368     // GCC does an implicit conversion to the pointer or integer ValType.  This
5369     // can fail in some cases (1i -> int**), check for this error case now.
5370     // Initialize the argument.
5371     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5372                                                    ValType, /*consume*/ false);
5373     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5374     if (Arg.isInvalid())
5375       return ExprError();
5376 
5377     // Okay, we have something that *can* be converted to the right type.  Check
5378     // to see if there is a potentially weird extension going on here.  This can
5379     // happen when you do an atomic operation on something like an char* and
5380     // pass in 42.  The 42 gets converted to char.  This is even more strange
5381     // for things like 45.123 -> char, etc.
5382     // FIXME: Do this check.
5383     TheCall->setArg(i+1, Arg.get());
5384   }
5385 
5386   // Create a new DeclRefExpr to refer to the new decl.
5387   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5388       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5389       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5390       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5391 
5392   // Set the callee in the CallExpr.
5393   // FIXME: This loses syntactic information.
5394   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5395   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5396                                               CK_BuiltinFnToFnPtr);
5397   TheCall->setCallee(PromotedCall.get());
5398 
5399   // Change the result type of the call to match the original value type. This
5400   // is arbitrary, but the codegen for these builtins ins design to handle it
5401   // gracefully.
5402   TheCall->setType(ResultType);
5403 
5404   return TheCallResult;
5405 }
5406 
5407 /// SemaBuiltinNontemporalOverloaded - We have a call to
5408 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5409 /// overloaded function based on the pointer type of its last argument.
5410 ///
5411 /// This function goes through and does final semantic checking for these
5412 /// builtins.
5413 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5414   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5415   DeclRefExpr *DRE =
5416       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5417   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5418   unsigned BuiltinID = FDecl->getBuiltinID();
5419   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5420           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5421          "Unexpected nontemporal load/store builtin!");
5422   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5423   unsigned numArgs = isStore ? 2 : 1;
5424 
5425   // Ensure that we have the proper number of arguments.
5426   if (checkArgCount(*this, TheCall, numArgs))
5427     return ExprError();
5428 
5429   // Inspect the last argument of the nontemporal builtin.  This should always
5430   // be a pointer type, from which we imply the type of the memory access.
5431   // Because it is a pointer type, we don't have to worry about any implicit
5432   // casts here.
5433   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5434   ExprResult PointerArgResult =
5435       DefaultFunctionArrayLvalueConversion(PointerArg);
5436 
5437   if (PointerArgResult.isInvalid())
5438     return ExprError();
5439   PointerArg = PointerArgResult.get();
5440   TheCall->setArg(numArgs - 1, PointerArg);
5441 
5442   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5443   if (!pointerType) {
5444     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5445         << PointerArg->getType() << PointerArg->getSourceRange();
5446     return ExprError();
5447   }
5448 
5449   QualType ValType = pointerType->getPointeeType();
5450 
5451   // Strip any qualifiers off ValType.
5452   ValType = ValType.getUnqualifiedType();
5453   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5454       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5455       !ValType->isVectorType()) {
5456     Diag(DRE->getBeginLoc(),
5457          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5458         << PointerArg->getType() << PointerArg->getSourceRange();
5459     return ExprError();
5460   }
5461 
5462   if (!isStore) {
5463     TheCall->setType(ValType);
5464     return TheCallResult;
5465   }
5466 
5467   ExprResult ValArg = TheCall->getArg(0);
5468   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5469       Context, ValType, /*consume*/ false);
5470   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5471   if (ValArg.isInvalid())
5472     return ExprError();
5473 
5474   TheCall->setArg(0, ValArg.get());
5475   TheCall->setType(Context.VoidTy);
5476   return TheCallResult;
5477 }
5478 
5479 /// CheckObjCString - Checks that the argument to the builtin
5480 /// CFString constructor is correct
5481 /// Note: It might also make sense to do the UTF-16 conversion here (would
5482 /// simplify the backend).
5483 bool Sema::CheckObjCString(Expr *Arg) {
5484   Arg = Arg->IgnoreParenCasts();
5485   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5486 
5487   if (!Literal || !Literal->isAscii()) {
5488     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5489         << Arg->getSourceRange();
5490     return true;
5491   }
5492 
5493   if (Literal->containsNonAsciiOrNull()) {
5494     StringRef String = Literal->getString();
5495     unsigned NumBytes = String.size();
5496     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5497     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5498     llvm::UTF16 *ToPtr = &ToBuf[0];
5499 
5500     llvm::ConversionResult Result =
5501         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5502                                  ToPtr + NumBytes, llvm::strictConversion);
5503     // Check for conversion failure.
5504     if (Result != llvm::conversionOK)
5505       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5506           << Arg->getSourceRange();
5507   }
5508   return false;
5509 }
5510 
5511 /// CheckObjCString - Checks that the format string argument to the os_log()
5512 /// and os_trace() functions is correct, and converts it to const char *.
5513 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5514   Arg = Arg->IgnoreParenCasts();
5515   auto *Literal = dyn_cast<StringLiteral>(Arg);
5516   if (!Literal) {
5517     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5518       Literal = ObjcLiteral->getString();
5519     }
5520   }
5521 
5522   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5523     return ExprError(
5524         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5525         << Arg->getSourceRange());
5526   }
5527 
5528   ExprResult Result(Literal);
5529   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5530   InitializedEntity Entity =
5531       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5532   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5533   return Result;
5534 }
5535 
5536 /// Check that the user is calling the appropriate va_start builtin for the
5537 /// target and calling convention.
5538 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5539   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5540   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5541   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5542                     TT.getArch() == llvm::Triple::aarch64_32);
5543   bool IsWindows = TT.isOSWindows();
5544   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5545   if (IsX64 || IsAArch64) {
5546     CallingConv CC = CC_C;
5547     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5548       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5549     if (IsMSVAStart) {
5550       // Don't allow this in System V ABI functions.
5551       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5552         return S.Diag(Fn->getBeginLoc(),
5553                       diag::err_ms_va_start_used_in_sysv_function);
5554     } else {
5555       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5556       // On x64 Windows, don't allow this in System V ABI functions.
5557       // (Yes, that means there's no corresponding way to support variadic
5558       // System V ABI functions on Windows.)
5559       if ((IsWindows && CC == CC_X86_64SysV) ||
5560           (!IsWindows && CC == CC_Win64))
5561         return S.Diag(Fn->getBeginLoc(),
5562                       diag::err_va_start_used_in_wrong_abi_function)
5563                << !IsWindows;
5564     }
5565     return false;
5566   }
5567 
5568   if (IsMSVAStart)
5569     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5570   return false;
5571 }
5572 
5573 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5574                                              ParmVarDecl **LastParam = nullptr) {
5575   // Determine whether the current function, block, or obj-c method is variadic
5576   // and get its parameter list.
5577   bool IsVariadic = false;
5578   ArrayRef<ParmVarDecl *> Params;
5579   DeclContext *Caller = S.CurContext;
5580   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5581     IsVariadic = Block->isVariadic();
5582     Params = Block->parameters();
5583   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5584     IsVariadic = FD->isVariadic();
5585     Params = FD->parameters();
5586   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5587     IsVariadic = MD->isVariadic();
5588     // FIXME: This isn't correct for methods (results in bogus warning).
5589     Params = MD->parameters();
5590   } else if (isa<CapturedDecl>(Caller)) {
5591     // We don't support va_start in a CapturedDecl.
5592     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5593     return true;
5594   } else {
5595     // This must be some other declcontext that parses exprs.
5596     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5597     return true;
5598   }
5599 
5600   if (!IsVariadic) {
5601     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5602     return true;
5603   }
5604 
5605   if (LastParam)
5606     *LastParam = Params.empty() ? nullptr : Params.back();
5607 
5608   return false;
5609 }
5610 
5611 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5612 /// for validity.  Emit an error and return true on failure; return false
5613 /// on success.
5614 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5615   Expr *Fn = TheCall->getCallee();
5616 
5617   if (checkVAStartABI(*this, BuiltinID, Fn))
5618     return true;
5619 
5620   if (TheCall->getNumArgs() > 2) {
5621     Diag(TheCall->getArg(2)->getBeginLoc(),
5622          diag::err_typecheck_call_too_many_args)
5623         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5624         << Fn->getSourceRange()
5625         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5626                        (*(TheCall->arg_end() - 1))->getEndLoc());
5627     return true;
5628   }
5629 
5630   if (TheCall->getNumArgs() < 2) {
5631     return Diag(TheCall->getEndLoc(),
5632                 diag::err_typecheck_call_too_few_args_at_least)
5633            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5634   }
5635 
5636   // Type-check the first argument normally.
5637   if (checkBuiltinArgument(*this, TheCall, 0))
5638     return true;
5639 
5640   // Check that the current function is variadic, and get its last parameter.
5641   ParmVarDecl *LastParam;
5642   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5643     return true;
5644 
5645   // Verify that the second argument to the builtin is the last argument of the
5646   // current function or method.
5647   bool SecondArgIsLastNamedArgument = false;
5648   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5649 
5650   // These are valid if SecondArgIsLastNamedArgument is false after the next
5651   // block.
5652   QualType Type;
5653   SourceLocation ParamLoc;
5654   bool IsCRegister = false;
5655 
5656   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5657     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5658       SecondArgIsLastNamedArgument = PV == LastParam;
5659 
5660       Type = PV->getType();
5661       ParamLoc = PV->getLocation();
5662       IsCRegister =
5663           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5664     }
5665   }
5666 
5667   if (!SecondArgIsLastNamedArgument)
5668     Diag(TheCall->getArg(1)->getBeginLoc(),
5669          diag::warn_second_arg_of_va_start_not_last_named_param);
5670   else if (IsCRegister || Type->isReferenceType() ||
5671            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5672              // Promotable integers are UB, but enumerations need a bit of
5673              // extra checking to see what their promotable type actually is.
5674              if (!Type->isPromotableIntegerType())
5675                return false;
5676              if (!Type->isEnumeralType())
5677                return true;
5678              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5679              return !(ED &&
5680                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5681            }()) {
5682     unsigned Reason = 0;
5683     if (Type->isReferenceType())  Reason = 1;
5684     else if (IsCRegister)         Reason = 2;
5685     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5686     Diag(ParamLoc, diag::note_parameter_type) << Type;
5687   }
5688 
5689   TheCall->setType(Context.VoidTy);
5690   return false;
5691 }
5692 
5693 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5694   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5695   //                 const char *named_addr);
5696 
5697   Expr *Func = Call->getCallee();
5698 
5699   if (Call->getNumArgs() < 3)
5700     return Diag(Call->getEndLoc(),
5701                 diag::err_typecheck_call_too_few_args_at_least)
5702            << 0 /*function call*/ << 3 << Call->getNumArgs();
5703 
5704   // Type-check the first argument normally.
5705   if (checkBuiltinArgument(*this, Call, 0))
5706     return true;
5707 
5708   // Check that the current function is variadic.
5709   if (checkVAStartIsInVariadicFunction(*this, Func))
5710     return true;
5711 
5712   // __va_start on Windows does not validate the parameter qualifiers
5713 
5714   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5715   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5716 
5717   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5718   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5719 
5720   const QualType &ConstCharPtrTy =
5721       Context.getPointerType(Context.CharTy.withConst());
5722   if (!Arg1Ty->isPointerType() ||
5723       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5724     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5725         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5726         << 0                                      /* qualifier difference */
5727         << 3                                      /* parameter mismatch */
5728         << 2 << Arg1->getType() << ConstCharPtrTy;
5729 
5730   const QualType SizeTy = Context.getSizeType();
5731   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5732     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5733         << Arg2->getType() << SizeTy << 1 /* different class */
5734         << 0                              /* qualifier difference */
5735         << 3                              /* parameter mismatch */
5736         << 3 << Arg2->getType() << SizeTy;
5737 
5738   return false;
5739 }
5740 
5741 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5742 /// friends.  This is declared to take (...), so we have to check everything.
5743 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5744   if (TheCall->getNumArgs() < 2)
5745     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5746            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5747   if (TheCall->getNumArgs() > 2)
5748     return Diag(TheCall->getArg(2)->getBeginLoc(),
5749                 diag::err_typecheck_call_too_many_args)
5750            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5751            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5752                           (*(TheCall->arg_end() - 1))->getEndLoc());
5753 
5754   ExprResult OrigArg0 = TheCall->getArg(0);
5755   ExprResult OrigArg1 = TheCall->getArg(1);
5756 
5757   // Do standard promotions between the two arguments, returning their common
5758   // type.
5759   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5760   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5761     return true;
5762 
5763   // Make sure any conversions are pushed back into the call; this is
5764   // type safe since unordered compare builtins are declared as "_Bool
5765   // foo(...)".
5766   TheCall->setArg(0, OrigArg0.get());
5767   TheCall->setArg(1, OrigArg1.get());
5768 
5769   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5770     return false;
5771 
5772   // If the common type isn't a real floating type, then the arguments were
5773   // invalid for this operation.
5774   if (Res.isNull() || !Res->isRealFloatingType())
5775     return Diag(OrigArg0.get()->getBeginLoc(),
5776                 diag::err_typecheck_call_invalid_ordered_compare)
5777            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5778            << SourceRange(OrigArg0.get()->getBeginLoc(),
5779                           OrigArg1.get()->getEndLoc());
5780 
5781   return false;
5782 }
5783 
5784 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5785 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5786 /// to check everything. We expect the last argument to be a floating point
5787 /// value.
5788 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5789   if (TheCall->getNumArgs() < NumArgs)
5790     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5791            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5792   if (TheCall->getNumArgs() > NumArgs)
5793     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5794                 diag::err_typecheck_call_too_many_args)
5795            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5796            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5797                           (*(TheCall->arg_end() - 1))->getEndLoc());
5798 
5799   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5800 
5801   if (OrigArg->isTypeDependent())
5802     return false;
5803 
5804   // This operation requires a non-_Complex floating-point number.
5805   if (!OrigArg->getType()->isRealFloatingType())
5806     return Diag(OrigArg->getBeginLoc(),
5807                 diag::err_typecheck_call_invalid_unary_fp)
5808            << OrigArg->getType() << OrigArg->getSourceRange();
5809 
5810   // If this is an implicit conversion from float -> float, double, or
5811   // long double, remove it.
5812   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5813     // Only remove standard FloatCasts, leaving other casts inplace
5814     if (Cast->getCastKind() == CK_FloatingCast) {
5815       Expr *CastArg = Cast->getSubExpr();
5816       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5817         assert(
5818             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5819              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5820              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5821             "promotion from float to either float, double, or long double is "
5822             "the only expected cast here");
5823         Cast->setSubExpr(nullptr);
5824         TheCall->setArg(NumArgs-1, CastArg);
5825       }
5826     }
5827   }
5828 
5829   return false;
5830 }
5831 
5832 // Customized Sema Checking for VSX builtins that have the following signature:
5833 // vector [...] builtinName(vector [...], vector [...], const int);
5834 // Which takes the same type of vectors (any legal vector type) for the first
5835 // two arguments and takes compile time constant for the third argument.
5836 // Example builtins are :
5837 // vector double vec_xxpermdi(vector double, vector double, int);
5838 // vector short vec_xxsldwi(vector short, vector short, int);
5839 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5840   unsigned ExpectedNumArgs = 3;
5841   if (TheCall->getNumArgs() < ExpectedNumArgs)
5842     return Diag(TheCall->getEndLoc(),
5843                 diag::err_typecheck_call_too_few_args_at_least)
5844            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5845            << TheCall->getSourceRange();
5846 
5847   if (TheCall->getNumArgs() > ExpectedNumArgs)
5848     return Diag(TheCall->getEndLoc(),
5849                 diag::err_typecheck_call_too_many_args_at_most)
5850            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5851            << TheCall->getSourceRange();
5852 
5853   // Check the third argument is a compile time constant
5854   llvm::APSInt Value;
5855   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5856     return Diag(TheCall->getBeginLoc(),
5857                 diag::err_vsx_builtin_nonconstant_argument)
5858            << 3 /* argument index */ << TheCall->getDirectCallee()
5859            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5860                           TheCall->getArg(2)->getEndLoc());
5861 
5862   QualType Arg1Ty = TheCall->getArg(0)->getType();
5863   QualType Arg2Ty = TheCall->getArg(1)->getType();
5864 
5865   // Check the type of argument 1 and argument 2 are vectors.
5866   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5867   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5868       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5869     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5870            << TheCall->getDirectCallee()
5871            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5872                           TheCall->getArg(1)->getEndLoc());
5873   }
5874 
5875   // Check the first two arguments are the same type.
5876   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5877     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5878            << TheCall->getDirectCallee()
5879            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5880                           TheCall->getArg(1)->getEndLoc());
5881   }
5882 
5883   // When default clang type checking is turned off and the customized type
5884   // checking is used, the returning type of the function must be explicitly
5885   // set. Otherwise it is _Bool by default.
5886   TheCall->setType(Arg1Ty);
5887 
5888   return false;
5889 }
5890 
5891 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5892 // This is declared to take (...), so we have to check everything.
5893 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5894   if (TheCall->getNumArgs() < 2)
5895     return ExprError(Diag(TheCall->getEndLoc(),
5896                           diag::err_typecheck_call_too_few_args_at_least)
5897                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5898                      << TheCall->getSourceRange());
5899 
5900   // Determine which of the following types of shufflevector we're checking:
5901   // 1) unary, vector mask: (lhs, mask)
5902   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5903   QualType resType = TheCall->getArg(0)->getType();
5904   unsigned numElements = 0;
5905 
5906   if (!TheCall->getArg(0)->isTypeDependent() &&
5907       !TheCall->getArg(1)->isTypeDependent()) {
5908     QualType LHSType = TheCall->getArg(0)->getType();
5909     QualType RHSType = TheCall->getArg(1)->getType();
5910 
5911     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5912       return ExprError(
5913           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5914           << TheCall->getDirectCallee()
5915           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5916                          TheCall->getArg(1)->getEndLoc()));
5917 
5918     numElements = LHSType->castAs<VectorType>()->getNumElements();
5919     unsigned numResElements = TheCall->getNumArgs() - 2;
5920 
5921     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5922     // with mask.  If so, verify that RHS is an integer vector type with the
5923     // same number of elts as lhs.
5924     if (TheCall->getNumArgs() == 2) {
5925       if (!RHSType->hasIntegerRepresentation() ||
5926           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5927         return ExprError(Diag(TheCall->getBeginLoc(),
5928                               diag::err_vec_builtin_incompatible_vector)
5929                          << TheCall->getDirectCallee()
5930                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5931                                         TheCall->getArg(1)->getEndLoc()));
5932     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5933       return ExprError(Diag(TheCall->getBeginLoc(),
5934                             diag::err_vec_builtin_incompatible_vector)
5935                        << TheCall->getDirectCallee()
5936                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5937                                       TheCall->getArg(1)->getEndLoc()));
5938     } else if (numElements != numResElements) {
5939       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5940       resType = Context.getVectorType(eltType, numResElements,
5941                                       VectorType::GenericVector);
5942     }
5943   }
5944 
5945   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5946     if (TheCall->getArg(i)->isTypeDependent() ||
5947         TheCall->getArg(i)->isValueDependent())
5948       continue;
5949 
5950     llvm::APSInt Result(32);
5951     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5952       return ExprError(Diag(TheCall->getBeginLoc(),
5953                             diag::err_shufflevector_nonconstant_argument)
5954                        << TheCall->getArg(i)->getSourceRange());
5955 
5956     // Allow -1 which will be translated to undef in the IR.
5957     if (Result.isSigned() && Result.isAllOnesValue())
5958       continue;
5959 
5960     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5961       return ExprError(Diag(TheCall->getBeginLoc(),
5962                             diag::err_shufflevector_argument_too_large)
5963                        << TheCall->getArg(i)->getSourceRange());
5964   }
5965 
5966   SmallVector<Expr*, 32> exprs;
5967 
5968   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5969     exprs.push_back(TheCall->getArg(i));
5970     TheCall->setArg(i, nullptr);
5971   }
5972 
5973   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5974                                          TheCall->getCallee()->getBeginLoc(),
5975                                          TheCall->getRParenLoc());
5976 }
5977 
5978 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5979 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5980                                        SourceLocation BuiltinLoc,
5981                                        SourceLocation RParenLoc) {
5982   ExprValueKind VK = VK_RValue;
5983   ExprObjectKind OK = OK_Ordinary;
5984   QualType DstTy = TInfo->getType();
5985   QualType SrcTy = E->getType();
5986 
5987   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5988     return ExprError(Diag(BuiltinLoc,
5989                           diag::err_convertvector_non_vector)
5990                      << E->getSourceRange());
5991   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5992     return ExprError(Diag(BuiltinLoc,
5993                           diag::err_convertvector_non_vector_type));
5994 
5995   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5996     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5997     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5998     if (SrcElts != DstElts)
5999       return ExprError(Diag(BuiltinLoc,
6000                             diag::err_convertvector_incompatible_vector)
6001                        << E->getSourceRange());
6002   }
6003 
6004   return new (Context)
6005       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6006 }
6007 
6008 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6009 // This is declared to take (const void*, ...) and can take two
6010 // optional constant int args.
6011 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6012   unsigned NumArgs = TheCall->getNumArgs();
6013 
6014   if (NumArgs > 3)
6015     return Diag(TheCall->getEndLoc(),
6016                 diag::err_typecheck_call_too_many_args_at_most)
6017            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6018 
6019   // Argument 0 is checked for us and the remaining arguments must be
6020   // constant integers.
6021   for (unsigned i = 1; i != NumArgs; ++i)
6022     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6023       return true;
6024 
6025   return false;
6026 }
6027 
6028 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6029 // __assume does not evaluate its arguments, and should warn if its argument
6030 // has side effects.
6031 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6032   Expr *Arg = TheCall->getArg(0);
6033   if (Arg->isInstantiationDependent()) return false;
6034 
6035   if (Arg->HasSideEffects(Context))
6036     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6037         << Arg->getSourceRange()
6038         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6039 
6040   return false;
6041 }
6042 
6043 /// Handle __builtin_alloca_with_align. This is declared
6044 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6045 /// than 8.
6046 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6047   // The alignment must be a constant integer.
6048   Expr *Arg = TheCall->getArg(1);
6049 
6050   // We can't check the value of a dependent argument.
6051   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6052     if (const auto *UE =
6053             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6054       if (UE->getKind() == UETT_AlignOf ||
6055           UE->getKind() == UETT_PreferredAlignOf)
6056         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6057             << Arg->getSourceRange();
6058 
6059     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6060 
6061     if (!Result.isPowerOf2())
6062       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6063              << Arg->getSourceRange();
6064 
6065     if (Result < Context.getCharWidth())
6066       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6067              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6068 
6069     if (Result > std::numeric_limits<int32_t>::max())
6070       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6071              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6072   }
6073 
6074   return false;
6075 }
6076 
6077 /// Handle __builtin_assume_aligned. This is declared
6078 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6079 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6080   unsigned NumArgs = TheCall->getNumArgs();
6081 
6082   if (NumArgs > 3)
6083     return Diag(TheCall->getEndLoc(),
6084                 diag::err_typecheck_call_too_many_args_at_most)
6085            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6086 
6087   // The alignment must be a constant integer.
6088   Expr *Arg = TheCall->getArg(1);
6089 
6090   // We can't check the value of a dependent argument.
6091   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6092     llvm::APSInt Result;
6093     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6094       return true;
6095 
6096     if (!Result.isPowerOf2())
6097       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6098              << Arg->getSourceRange();
6099 
6100     // Alignment calculations can wrap around if it's greater than 2**29.
6101     unsigned MaximumAlignment = 536870912;
6102     if (Result > MaximumAlignment)
6103       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6104           << Arg->getSourceRange() << MaximumAlignment;
6105   }
6106 
6107   if (NumArgs > 2) {
6108     ExprResult Arg(TheCall->getArg(2));
6109     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6110       Context.getSizeType(), false);
6111     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6112     if (Arg.isInvalid()) return true;
6113     TheCall->setArg(2, Arg.get());
6114   }
6115 
6116   return false;
6117 }
6118 
6119 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6120   unsigned BuiltinID =
6121       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6122   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6123 
6124   unsigned NumArgs = TheCall->getNumArgs();
6125   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6126   if (NumArgs < NumRequiredArgs) {
6127     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6128            << 0 /* function call */ << NumRequiredArgs << NumArgs
6129            << TheCall->getSourceRange();
6130   }
6131   if (NumArgs >= NumRequiredArgs + 0x100) {
6132     return Diag(TheCall->getEndLoc(),
6133                 diag::err_typecheck_call_too_many_args_at_most)
6134            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6135            << TheCall->getSourceRange();
6136   }
6137   unsigned i = 0;
6138 
6139   // For formatting call, check buffer arg.
6140   if (!IsSizeCall) {
6141     ExprResult Arg(TheCall->getArg(i));
6142     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6143         Context, Context.VoidPtrTy, false);
6144     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6145     if (Arg.isInvalid())
6146       return true;
6147     TheCall->setArg(i, Arg.get());
6148     i++;
6149   }
6150 
6151   // Check string literal arg.
6152   unsigned FormatIdx = i;
6153   {
6154     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6155     if (Arg.isInvalid())
6156       return true;
6157     TheCall->setArg(i, Arg.get());
6158     i++;
6159   }
6160 
6161   // Make sure variadic args are scalar.
6162   unsigned FirstDataArg = i;
6163   while (i < NumArgs) {
6164     ExprResult Arg = DefaultVariadicArgumentPromotion(
6165         TheCall->getArg(i), VariadicFunction, nullptr);
6166     if (Arg.isInvalid())
6167       return true;
6168     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6169     if (ArgSize.getQuantity() >= 0x100) {
6170       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6171              << i << (int)ArgSize.getQuantity() << 0xff
6172              << TheCall->getSourceRange();
6173     }
6174     TheCall->setArg(i, Arg.get());
6175     i++;
6176   }
6177 
6178   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6179   // call to avoid duplicate diagnostics.
6180   if (!IsSizeCall) {
6181     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6182     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6183     bool Success = CheckFormatArguments(
6184         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6185         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6186         CheckedVarArgs);
6187     if (!Success)
6188       return true;
6189   }
6190 
6191   if (IsSizeCall) {
6192     TheCall->setType(Context.getSizeType());
6193   } else {
6194     TheCall->setType(Context.VoidPtrTy);
6195   }
6196   return false;
6197 }
6198 
6199 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6200 /// TheCall is a constant expression.
6201 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6202                                   llvm::APSInt &Result) {
6203   Expr *Arg = TheCall->getArg(ArgNum);
6204   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6205   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6206 
6207   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6208 
6209   if (!Arg->isIntegerConstantExpr(Result, Context))
6210     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6211            << FDecl->getDeclName() << Arg->getSourceRange();
6212 
6213   return false;
6214 }
6215 
6216 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6217 /// TheCall is a constant expression in the range [Low, High].
6218 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6219                                        int Low, int High, bool RangeIsError) {
6220   if (isConstantEvaluated())
6221     return false;
6222   llvm::APSInt Result;
6223 
6224   // We can't check the value of a dependent argument.
6225   Expr *Arg = TheCall->getArg(ArgNum);
6226   if (Arg->isTypeDependent() || Arg->isValueDependent())
6227     return false;
6228 
6229   // Check constant-ness first.
6230   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6231     return true;
6232 
6233   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6234     if (RangeIsError)
6235       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6236              << Result.toString(10) << Low << High << Arg->getSourceRange();
6237     else
6238       // Defer the warning until we know if the code will be emitted so that
6239       // dead code can ignore this.
6240       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6241                           PDiag(diag::warn_argument_invalid_range)
6242                               << Result.toString(10) << Low << High
6243                               << Arg->getSourceRange());
6244   }
6245 
6246   return false;
6247 }
6248 
6249 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6250 /// TheCall is a constant expression is a multiple of Num..
6251 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6252                                           unsigned Num) {
6253   llvm::APSInt Result;
6254 
6255   // We can't check the value of a dependent argument.
6256   Expr *Arg = TheCall->getArg(ArgNum);
6257   if (Arg->isTypeDependent() || Arg->isValueDependent())
6258     return false;
6259 
6260   // Check constant-ness first.
6261   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6262     return true;
6263 
6264   if (Result.getSExtValue() % Num != 0)
6265     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6266            << Num << Arg->getSourceRange();
6267 
6268   return false;
6269 }
6270 
6271 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6272 /// constant expression representing a power of 2.
6273 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6274   llvm::APSInt Result;
6275 
6276   // We can't check the value of a dependent argument.
6277   Expr *Arg = TheCall->getArg(ArgNum);
6278   if (Arg->isTypeDependent() || Arg->isValueDependent())
6279     return false;
6280 
6281   // Check constant-ness first.
6282   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6283     return true;
6284 
6285   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6286   // and only if x is a power of 2.
6287   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6288     return false;
6289 
6290   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6291          << Arg->getSourceRange();
6292 }
6293 
6294 static bool IsShiftedByte(llvm::APSInt Value) {
6295   if (Value.isNegative())
6296     return false;
6297 
6298   // Check if it's a shifted byte, by shifting it down
6299   while (true) {
6300     // If the value fits in the bottom byte, the check passes.
6301     if (Value < 0x100)
6302       return true;
6303 
6304     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6305     // fails.
6306     if ((Value & 0xFF) != 0)
6307       return false;
6308 
6309     // If the bottom 8 bits are all 0, but something above that is nonzero,
6310     // then shifting the value right by 8 bits won't affect whether it's a
6311     // shifted byte or not. So do that, and go round again.
6312     Value >>= 8;
6313   }
6314 }
6315 
6316 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6317 /// a constant expression representing an arbitrary byte value shifted left by
6318 /// a multiple of 8 bits.
6319 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) {
6320   llvm::APSInt Result;
6321 
6322   // We can't check the value of a dependent argument.
6323   Expr *Arg = TheCall->getArg(ArgNum);
6324   if (Arg->isTypeDependent() || Arg->isValueDependent())
6325     return false;
6326 
6327   // Check constant-ness first.
6328   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6329     return true;
6330 
6331   if (IsShiftedByte(Result))
6332     return false;
6333 
6334   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6335          << Arg->getSourceRange();
6336 }
6337 
6338 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6339 /// TheCall is a constant expression representing either a shifted byte value,
6340 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6341 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6342 /// Arm MVE intrinsics.
6343 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6344                                                    int ArgNum) {
6345   llvm::APSInt Result;
6346 
6347   // We can't check the value of a dependent argument.
6348   Expr *Arg = TheCall->getArg(ArgNum);
6349   if (Arg->isTypeDependent() || Arg->isValueDependent())
6350     return false;
6351 
6352   // Check constant-ness first.
6353   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6354     return true;
6355 
6356   // Check to see if it's in either of the required forms.
6357   if (IsShiftedByte(Result) ||
6358       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6359     return false;
6360 
6361   return Diag(TheCall->getBeginLoc(),
6362               diag::err_argument_not_shifted_byte_or_xxff)
6363          << Arg->getSourceRange();
6364 }
6365 
6366 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6367 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6368   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6369     if (checkArgCount(*this, TheCall, 2))
6370       return true;
6371     Expr *Arg0 = TheCall->getArg(0);
6372     Expr *Arg1 = TheCall->getArg(1);
6373 
6374     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6375     if (FirstArg.isInvalid())
6376       return true;
6377     QualType FirstArgType = FirstArg.get()->getType();
6378     if (!FirstArgType->isAnyPointerType())
6379       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6380                << "first" << FirstArgType << Arg0->getSourceRange();
6381     TheCall->setArg(0, FirstArg.get());
6382 
6383     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6384     if (SecArg.isInvalid())
6385       return true;
6386     QualType SecArgType = SecArg.get()->getType();
6387     if (!SecArgType->isIntegerType())
6388       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6389                << "second" << SecArgType << Arg1->getSourceRange();
6390 
6391     // Derive the return type from the pointer argument.
6392     TheCall->setType(FirstArgType);
6393     return false;
6394   }
6395 
6396   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6397     if (checkArgCount(*this, TheCall, 2))
6398       return true;
6399 
6400     Expr *Arg0 = TheCall->getArg(0);
6401     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6402     if (FirstArg.isInvalid())
6403       return true;
6404     QualType FirstArgType = FirstArg.get()->getType();
6405     if (!FirstArgType->isAnyPointerType())
6406       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6407                << "first" << FirstArgType << Arg0->getSourceRange();
6408     TheCall->setArg(0, FirstArg.get());
6409 
6410     // Derive the return type from the pointer argument.
6411     TheCall->setType(FirstArgType);
6412 
6413     // Second arg must be an constant in range [0,15]
6414     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6415   }
6416 
6417   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6418     if (checkArgCount(*this, TheCall, 2))
6419       return true;
6420     Expr *Arg0 = TheCall->getArg(0);
6421     Expr *Arg1 = TheCall->getArg(1);
6422 
6423     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6424     if (FirstArg.isInvalid())
6425       return true;
6426     QualType FirstArgType = FirstArg.get()->getType();
6427     if (!FirstArgType->isAnyPointerType())
6428       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6429                << "first" << FirstArgType << Arg0->getSourceRange();
6430 
6431     QualType SecArgType = Arg1->getType();
6432     if (!SecArgType->isIntegerType())
6433       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6434                << "second" << SecArgType << Arg1->getSourceRange();
6435     TheCall->setType(Context.IntTy);
6436     return false;
6437   }
6438 
6439   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6440       BuiltinID == AArch64::BI__builtin_arm_stg) {
6441     if (checkArgCount(*this, TheCall, 1))
6442       return true;
6443     Expr *Arg0 = TheCall->getArg(0);
6444     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6445     if (FirstArg.isInvalid())
6446       return true;
6447 
6448     QualType FirstArgType = FirstArg.get()->getType();
6449     if (!FirstArgType->isAnyPointerType())
6450       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6451                << "first" << FirstArgType << Arg0->getSourceRange();
6452     TheCall->setArg(0, FirstArg.get());
6453 
6454     // Derive the return type from the pointer argument.
6455     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6456       TheCall->setType(FirstArgType);
6457     return false;
6458   }
6459 
6460   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6461     Expr *ArgA = TheCall->getArg(0);
6462     Expr *ArgB = TheCall->getArg(1);
6463 
6464     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6465     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6466 
6467     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6468       return true;
6469 
6470     QualType ArgTypeA = ArgExprA.get()->getType();
6471     QualType ArgTypeB = ArgExprB.get()->getType();
6472 
6473     auto isNull = [&] (Expr *E) -> bool {
6474       return E->isNullPointerConstant(
6475                         Context, Expr::NPC_ValueDependentIsNotNull); };
6476 
6477     // argument should be either a pointer or null
6478     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6479       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6480         << "first" << ArgTypeA << ArgA->getSourceRange();
6481 
6482     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6483       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6484         << "second" << ArgTypeB << ArgB->getSourceRange();
6485 
6486     // Ensure Pointee types are compatible
6487     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6488         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6489       QualType pointeeA = ArgTypeA->getPointeeType();
6490       QualType pointeeB = ArgTypeB->getPointeeType();
6491       if (!Context.typesAreCompatible(
6492              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6493              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6494         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6495           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6496           << ArgB->getSourceRange();
6497       }
6498     }
6499 
6500     // at least one argument should be pointer type
6501     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6502       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6503         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6504 
6505     if (isNull(ArgA)) // adopt type of the other pointer
6506       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6507 
6508     if (isNull(ArgB))
6509       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6510 
6511     TheCall->setArg(0, ArgExprA.get());
6512     TheCall->setArg(1, ArgExprB.get());
6513     TheCall->setType(Context.LongLongTy);
6514     return false;
6515   }
6516   assert(false && "Unhandled ARM MTE intrinsic");
6517   return true;
6518 }
6519 
6520 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6521 /// TheCall is an ARM/AArch64 special register string literal.
6522 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6523                                     int ArgNum, unsigned ExpectedFieldNum,
6524                                     bool AllowName) {
6525   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6526                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6527                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6528                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6529                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6530                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6531   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6532                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6533                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6534                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6535                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6536                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6537   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6538 
6539   // We can't check the value of a dependent argument.
6540   Expr *Arg = TheCall->getArg(ArgNum);
6541   if (Arg->isTypeDependent() || Arg->isValueDependent())
6542     return false;
6543 
6544   // Check if the argument is a string literal.
6545   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6546     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6547            << Arg->getSourceRange();
6548 
6549   // Check the type of special register given.
6550   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6551   SmallVector<StringRef, 6> Fields;
6552   Reg.split(Fields, ":");
6553 
6554   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6555     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6556            << Arg->getSourceRange();
6557 
6558   // If the string is the name of a register then we cannot check that it is
6559   // valid here but if the string is of one the forms described in ACLE then we
6560   // can check that the supplied fields are integers and within the valid
6561   // ranges.
6562   if (Fields.size() > 1) {
6563     bool FiveFields = Fields.size() == 5;
6564 
6565     bool ValidString = true;
6566     if (IsARMBuiltin) {
6567       ValidString &= Fields[0].startswith_lower("cp") ||
6568                      Fields[0].startswith_lower("p");
6569       if (ValidString)
6570         Fields[0] =
6571           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6572 
6573       ValidString &= Fields[2].startswith_lower("c");
6574       if (ValidString)
6575         Fields[2] = Fields[2].drop_front(1);
6576 
6577       if (FiveFields) {
6578         ValidString &= Fields[3].startswith_lower("c");
6579         if (ValidString)
6580           Fields[3] = Fields[3].drop_front(1);
6581       }
6582     }
6583 
6584     SmallVector<int, 5> Ranges;
6585     if (FiveFields)
6586       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6587     else
6588       Ranges.append({15, 7, 15});
6589 
6590     for (unsigned i=0; i<Fields.size(); ++i) {
6591       int IntField;
6592       ValidString &= !Fields[i].getAsInteger(10, IntField);
6593       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6594     }
6595 
6596     if (!ValidString)
6597       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6598              << Arg->getSourceRange();
6599   } else if (IsAArch64Builtin && Fields.size() == 1) {
6600     // If the register name is one of those that appear in the condition below
6601     // and the special register builtin being used is one of the write builtins,
6602     // then we require that the argument provided for writing to the register
6603     // is an integer constant expression. This is because it will be lowered to
6604     // an MSR (immediate) instruction, so we need to know the immediate at
6605     // compile time.
6606     if (TheCall->getNumArgs() != 2)
6607       return false;
6608 
6609     std::string RegLower = Reg.lower();
6610     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6611         RegLower != "pan" && RegLower != "uao")
6612       return false;
6613 
6614     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6615   }
6616 
6617   return false;
6618 }
6619 
6620 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6621 /// This checks that the target supports __builtin_longjmp and
6622 /// that val is a constant 1.
6623 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6624   if (!Context.getTargetInfo().hasSjLjLowering())
6625     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6626            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6627 
6628   Expr *Arg = TheCall->getArg(1);
6629   llvm::APSInt Result;
6630 
6631   // TODO: This is less than ideal. Overload this to take a value.
6632   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6633     return true;
6634 
6635   if (Result != 1)
6636     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6637            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6638 
6639   return false;
6640 }
6641 
6642 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6643 /// This checks that the target supports __builtin_setjmp.
6644 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6645   if (!Context.getTargetInfo().hasSjLjLowering())
6646     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6647            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6648   return false;
6649 }
6650 
6651 namespace {
6652 
6653 class UncoveredArgHandler {
6654   enum { Unknown = -1, AllCovered = -2 };
6655 
6656   signed FirstUncoveredArg = Unknown;
6657   SmallVector<const Expr *, 4> DiagnosticExprs;
6658 
6659 public:
6660   UncoveredArgHandler() = default;
6661 
6662   bool hasUncoveredArg() const {
6663     return (FirstUncoveredArg >= 0);
6664   }
6665 
6666   unsigned getUncoveredArg() const {
6667     assert(hasUncoveredArg() && "no uncovered argument");
6668     return FirstUncoveredArg;
6669   }
6670 
6671   void setAllCovered() {
6672     // A string has been found with all arguments covered, so clear out
6673     // the diagnostics.
6674     DiagnosticExprs.clear();
6675     FirstUncoveredArg = AllCovered;
6676   }
6677 
6678   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6679     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6680 
6681     // Don't update if a previous string covers all arguments.
6682     if (FirstUncoveredArg == AllCovered)
6683       return;
6684 
6685     // UncoveredArgHandler tracks the highest uncovered argument index
6686     // and with it all the strings that match this index.
6687     if (NewFirstUncoveredArg == FirstUncoveredArg)
6688       DiagnosticExprs.push_back(StrExpr);
6689     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6690       DiagnosticExprs.clear();
6691       DiagnosticExprs.push_back(StrExpr);
6692       FirstUncoveredArg = NewFirstUncoveredArg;
6693     }
6694   }
6695 
6696   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6697 };
6698 
6699 enum StringLiteralCheckType {
6700   SLCT_NotALiteral,
6701   SLCT_UncheckedLiteral,
6702   SLCT_CheckedLiteral
6703 };
6704 
6705 } // namespace
6706 
6707 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6708                                      BinaryOperatorKind BinOpKind,
6709                                      bool AddendIsRight) {
6710   unsigned BitWidth = Offset.getBitWidth();
6711   unsigned AddendBitWidth = Addend.getBitWidth();
6712   // There might be negative interim results.
6713   if (Addend.isUnsigned()) {
6714     Addend = Addend.zext(++AddendBitWidth);
6715     Addend.setIsSigned(true);
6716   }
6717   // Adjust the bit width of the APSInts.
6718   if (AddendBitWidth > BitWidth) {
6719     Offset = Offset.sext(AddendBitWidth);
6720     BitWidth = AddendBitWidth;
6721   } else if (BitWidth > AddendBitWidth) {
6722     Addend = Addend.sext(BitWidth);
6723   }
6724 
6725   bool Ov = false;
6726   llvm::APSInt ResOffset = Offset;
6727   if (BinOpKind == BO_Add)
6728     ResOffset = Offset.sadd_ov(Addend, Ov);
6729   else {
6730     assert(AddendIsRight && BinOpKind == BO_Sub &&
6731            "operator must be add or sub with addend on the right");
6732     ResOffset = Offset.ssub_ov(Addend, Ov);
6733   }
6734 
6735   // We add an offset to a pointer here so we should support an offset as big as
6736   // possible.
6737   if (Ov) {
6738     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6739            "index (intermediate) result too big");
6740     Offset = Offset.sext(2 * BitWidth);
6741     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6742     return;
6743   }
6744 
6745   Offset = ResOffset;
6746 }
6747 
6748 namespace {
6749 
6750 // This is a wrapper class around StringLiteral to support offsetted string
6751 // literals as format strings. It takes the offset into account when returning
6752 // the string and its length or the source locations to display notes correctly.
6753 class FormatStringLiteral {
6754   const StringLiteral *FExpr;
6755   int64_t Offset;
6756 
6757  public:
6758   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6759       : FExpr(fexpr), Offset(Offset) {}
6760 
6761   StringRef getString() const {
6762     return FExpr->getString().drop_front(Offset);
6763   }
6764 
6765   unsigned getByteLength() const {
6766     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6767   }
6768 
6769   unsigned getLength() const { return FExpr->getLength() - Offset; }
6770   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6771 
6772   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6773 
6774   QualType getType() const { return FExpr->getType(); }
6775 
6776   bool isAscii() const { return FExpr->isAscii(); }
6777   bool isWide() const { return FExpr->isWide(); }
6778   bool isUTF8() const { return FExpr->isUTF8(); }
6779   bool isUTF16() const { return FExpr->isUTF16(); }
6780   bool isUTF32() const { return FExpr->isUTF32(); }
6781   bool isPascal() const { return FExpr->isPascal(); }
6782 
6783   SourceLocation getLocationOfByte(
6784       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6785       const TargetInfo &Target, unsigned *StartToken = nullptr,
6786       unsigned *StartTokenByteOffset = nullptr) const {
6787     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6788                                     StartToken, StartTokenByteOffset);
6789   }
6790 
6791   SourceLocation getBeginLoc() const LLVM_READONLY {
6792     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6793   }
6794 
6795   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6796 };
6797 
6798 }  // namespace
6799 
6800 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6801                               const Expr *OrigFormatExpr,
6802                               ArrayRef<const Expr *> Args,
6803                               bool HasVAListArg, unsigned format_idx,
6804                               unsigned firstDataArg,
6805                               Sema::FormatStringType Type,
6806                               bool inFunctionCall,
6807                               Sema::VariadicCallType CallType,
6808                               llvm::SmallBitVector &CheckedVarArgs,
6809                               UncoveredArgHandler &UncoveredArg,
6810                               bool IgnoreStringsWithoutSpecifiers);
6811 
6812 // Determine if an expression is a string literal or constant string.
6813 // If this function returns false on the arguments to a function expecting a
6814 // format string, we will usually need to emit a warning.
6815 // True string literals are then checked by CheckFormatString.
6816 static StringLiteralCheckType
6817 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6818                       bool HasVAListArg, unsigned format_idx,
6819                       unsigned firstDataArg, Sema::FormatStringType Type,
6820                       Sema::VariadicCallType CallType, bool InFunctionCall,
6821                       llvm::SmallBitVector &CheckedVarArgs,
6822                       UncoveredArgHandler &UncoveredArg,
6823                       llvm::APSInt Offset,
6824                       bool IgnoreStringsWithoutSpecifiers = false) {
6825   if (S.isConstantEvaluated())
6826     return SLCT_NotALiteral;
6827  tryAgain:
6828   assert(Offset.isSigned() && "invalid offset");
6829 
6830   if (E->isTypeDependent() || E->isValueDependent())
6831     return SLCT_NotALiteral;
6832 
6833   E = E->IgnoreParenCasts();
6834 
6835   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6836     // Technically -Wformat-nonliteral does not warn about this case.
6837     // The behavior of printf and friends in this case is implementation
6838     // dependent.  Ideally if the format string cannot be null then
6839     // it should have a 'nonnull' attribute in the function prototype.
6840     return SLCT_UncheckedLiteral;
6841 
6842   switch (E->getStmtClass()) {
6843   case Stmt::BinaryConditionalOperatorClass:
6844   case Stmt::ConditionalOperatorClass: {
6845     // The expression is a literal if both sub-expressions were, and it was
6846     // completely checked only if both sub-expressions were checked.
6847     const AbstractConditionalOperator *C =
6848         cast<AbstractConditionalOperator>(E);
6849 
6850     // Determine whether it is necessary to check both sub-expressions, for
6851     // example, because the condition expression is a constant that can be
6852     // evaluated at compile time.
6853     bool CheckLeft = true, CheckRight = true;
6854 
6855     bool Cond;
6856     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6857                                                  S.isConstantEvaluated())) {
6858       if (Cond)
6859         CheckRight = false;
6860       else
6861         CheckLeft = false;
6862     }
6863 
6864     // We need to maintain the offsets for the right and the left hand side
6865     // separately to check if every possible indexed expression is a valid
6866     // string literal. They might have different offsets for different string
6867     // literals in the end.
6868     StringLiteralCheckType Left;
6869     if (!CheckLeft)
6870       Left = SLCT_UncheckedLiteral;
6871     else {
6872       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6873                                    HasVAListArg, format_idx, firstDataArg,
6874                                    Type, CallType, InFunctionCall,
6875                                    CheckedVarArgs, UncoveredArg, Offset,
6876                                    IgnoreStringsWithoutSpecifiers);
6877       if (Left == SLCT_NotALiteral || !CheckRight) {
6878         return Left;
6879       }
6880     }
6881 
6882     StringLiteralCheckType Right = checkFormatStringExpr(
6883         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6884         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6885         IgnoreStringsWithoutSpecifiers);
6886 
6887     return (CheckLeft && Left < Right) ? Left : Right;
6888   }
6889 
6890   case Stmt::ImplicitCastExprClass:
6891     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6892     goto tryAgain;
6893 
6894   case Stmt::OpaqueValueExprClass:
6895     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6896       E = src;
6897       goto tryAgain;
6898     }
6899     return SLCT_NotALiteral;
6900 
6901   case Stmt::PredefinedExprClass:
6902     // While __func__, etc., are technically not string literals, they
6903     // cannot contain format specifiers and thus are not a security
6904     // liability.
6905     return SLCT_UncheckedLiteral;
6906 
6907   case Stmt::DeclRefExprClass: {
6908     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6909 
6910     // As an exception, do not flag errors for variables binding to
6911     // const string literals.
6912     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6913       bool isConstant = false;
6914       QualType T = DR->getType();
6915 
6916       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6917         isConstant = AT->getElementType().isConstant(S.Context);
6918       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6919         isConstant = T.isConstant(S.Context) &&
6920                      PT->getPointeeType().isConstant(S.Context);
6921       } else if (T->isObjCObjectPointerType()) {
6922         // In ObjC, there is usually no "const ObjectPointer" type,
6923         // so don't check if the pointee type is constant.
6924         isConstant = T.isConstant(S.Context);
6925       }
6926 
6927       if (isConstant) {
6928         if (const Expr *Init = VD->getAnyInitializer()) {
6929           // Look through initializers like const char c[] = { "foo" }
6930           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6931             if (InitList->isStringLiteralInit())
6932               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6933           }
6934           return checkFormatStringExpr(S, Init, Args,
6935                                        HasVAListArg, format_idx,
6936                                        firstDataArg, Type, CallType,
6937                                        /*InFunctionCall*/ false, CheckedVarArgs,
6938                                        UncoveredArg, Offset);
6939         }
6940       }
6941 
6942       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6943       // special check to see if the format string is a function parameter
6944       // of the function calling the printf function.  If the function
6945       // has an attribute indicating it is a printf-like function, then we
6946       // should suppress warnings concerning non-literals being used in a call
6947       // to a vprintf function.  For example:
6948       //
6949       // void
6950       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6951       //      va_list ap;
6952       //      va_start(ap, fmt);
6953       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6954       //      ...
6955       // }
6956       if (HasVAListArg) {
6957         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6958           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6959             int PVIndex = PV->getFunctionScopeIndex() + 1;
6960             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6961               // adjust for implicit parameter
6962               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6963                 if (MD->isInstance())
6964                   ++PVIndex;
6965               // We also check if the formats are compatible.
6966               // We can't pass a 'scanf' string to a 'printf' function.
6967               if (PVIndex == PVFormat->getFormatIdx() &&
6968                   Type == S.GetFormatStringType(PVFormat))
6969                 return SLCT_UncheckedLiteral;
6970             }
6971           }
6972         }
6973       }
6974     }
6975 
6976     return SLCT_NotALiteral;
6977   }
6978 
6979   case Stmt::CallExprClass:
6980   case Stmt::CXXMemberCallExprClass: {
6981     const CallExpr *CE = cast<CallExpr>(E);
6982     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6983       bool IsFirst = true;
6984       StringLiteralCheckType CommonResult;
6985       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6986         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6987         StringLiteralCheckType Result = checkFormatStringExpr(
6988             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6989             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6990             IgnoreStringsWithoutSpecifiers);
6991         if (IsFirst) {
6992           CommonResult = Result;
6993           IsFirst = false;
6994         }
6995       }
6996       if (!IsFirst)
6997         return CommonResult;
6998 
6999       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7000         unsigned BuiltinID = FD->getBuiltinID();
7001         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7002             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7003           const Expr *Arg = CE->getArg(0);
7004           return checkFormatStringExpr(S, Arg, Args,
7005                                        HasVAListArg, format_idx,
7006                                        firstDataArg, Type, CallType,
7007                                        InFunctionCall, CheckedVarArgs,
7008                                        UncoveredArg, Offset,
7009                                        IgnoreStringsWithoutSpecifiers);
7010         }
7011       }
7012     }
7013 
7014     return SLCT_NotALiteral;
7015   }
7016   case Stmt::ObjCMessageExprClass: {
7017     const auto *ME = cast<ObjCMessageExpr>(E);
7018     if (const auto *MD = ME->getMethodDecl()) {
7019       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7020         // As a special case heuristic, if we're using the method -[NSBundle
7021         // localizedStringForKey:value:table:], ignore any key strings that lack
7022         // format specifiers. The idea is that if the key doesn't have any
7023         // format specifiers then its probably just a key to map to the
7024         // localized strings. If it does have format specifiers though, then its
7025         // likely that the text of the key is the format string in the
7026         // programmer's language, and should be checked.
7027         const ObjCInterfaceDecl *IFace;
7028         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7029             IFace->getIdentifier()->isStr("NSBundle") &&
7030             MD->getSelector().isKeywordSelector(
7031                 {"localizedStringForKey", "value", "table"})) {
7032           IgnoreStringsWithoutSpecifiers = true;
7033         }
7034 
7035         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7036         return checkFormatStringExpr(
7037             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7038             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7039             IgnoreStringsWithoutSpecifiers);
7040       }
7041     }
7042 
7043     return SLCT_NotALiteral;
7044   }
7045   case Stmt::ObjCStringLiteralClass:
7046   case Stmt::StringLiteralClass: {
7047     const StringLiteral *StrE = nullptr;
7048 
7049     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7050       StrE = ObjCFExpr->getString();
7051     else
7052       StrE = cast<StringLiteral>(E);
7053 
7054     if (StrE) {
7055       if (Offset.isNegative() || Offset > StrE->getLength()) {
7056         // TODO: It would be better to have an explicit warning for out of
7057         // bounds literals.
7058         return SLCT_NotALiteral;
7059       }
7060       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7061       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7062                         firstDataArg, Type, InFunctionCall, CallType,
7063                         CheckedVarArgs, UncoveredArg,
7064                         IgnoreStringsWithoutSpecifiers);
7065       return SLCT_CheckedLiteral;
7066     }
7067 
7068     return SLCT_NotALiteral;
7069   }
7070   case Stmt::BinaryOperatorClass: {
7071     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7072 
7073     // A string literal + an int offset is still a string literal.
7074     if (BinOp->isAdditiveOp()) {
7075       Expr::EvalResult LResult, RResult;
7076 
7077       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7078           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7079       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7080           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7081 
7082       if (LIsInt != RIsInt) {
7083         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7084 
7085         if (LIsInt) {
7086           if (BinOpKind == BO_Add) {
7087             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7088             E = BinOp->getRHS();
7089             goto tryAgain;
7090           }
7091         } else {
7092           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7093           E = BinOp->getLHS();
7094           goto tryAgain;
7095         }
7096       }
7097     }
7098 
7099     return SLCT_NotALiteral;
7100   }
7101   case Stmt::UnaryOperatorClass: {
7102     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7103     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7104     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7105       Expr::EvalResult IndexResult;
7106       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7107                                        Expr::SE_NoSideEffects,
7108                                        S.isConstantEvaluated())) {
7109         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7110                    /*RHS is int*/ true);
7111         E = ASE->getBase();
7112         goto tryAgain;
7113       }
7114     }
7115 
7116     return SLCT_NotALiteral;
7117   }
7118 
7119   default:
7120     return SLCT_NotALiteral;
7121   }
7122 }
7123 
7124 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7125   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7126       .Case("scanf", FST_Scanf)
7127       .Cases("printf", "printf0", FST_Printf)
7128       .Cases("NSString", "CFString", FST_NSString)
7129       .Case("strftime", FST_Strftime)
7130       .Case("strfmon", FST_Strfmon)
7131       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7132       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7133       .Case("os_trace", FST_OSLog)
7134       .Case("os_log", FST_OSLog)
7135       .Default(FST_Unknown);
7136 }
7137 
7138 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7139 /// functions) for correct use of format strings.
7140 /// Returns true if a format string has been fully checked.
7141 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7142                                 ArrayRef<const Expr *> Args,
7143                                 bool IsCXXMember,
7144                                 VariadicCallType CallType,
7145                                 SourceLocation Loc, SourceRange Range,
7146                                 llvm::SmallBitVector &CheckedVarArgs) {
7147   FormatStringInfo FSI;
7148   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7149     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7150                                 FSI.FirstDataArg, GetFormatStringType(Format),
7151                                 CallType, Loc, Range, CheckedVarArgs);
7152   return false;
7153 }
7154 
7155 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7156                                 bool HasVAListArg, unsigned format_idx,
7157                                 unsigned firstDataArg, FormatStringType Type,
7158                                 VariadicCallType CallType,
7159                                 SourceLocation Loc, SourceRange Range,
7160                                 llvm::SmallBitVector &CheckedVarArgs) {
7161   // CHECK: printf/scanf-like function is called with no format string.
7162   if (format_idx >= Args.size()) {
7163     Diag(Loc, diag::warn_missing_format_string) << Range;
7164     return false;
7165   }
7166 
7167   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7168 
7169   // CHECK: format string is not a string literal.
7170   //
7171   // Dynamically generated format strings are difficult to
7172   // automatically vet at compile time.  Requiring that format strings
7173   // are string literals: (1) permits the checking of format strings by
7174   // the compiler and thereby (2) can practically remove the source of
7175   // many format string exploits.
7176 
7177   // Format string can be either ObjC string (e.g. @"%d") or
7178   // C string (e.g. "%d")
7179   // ObjC string uses the same format specifiers as C string, so we can use
7180   // the same format string checking logic for both ObjC and C strings.
7181   UncoveredArgHandler UncoveredArg;
7182   StringLiteralCheckType CT =
7183       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7184                             format_idx, firstDataArg, Type, CallType,
7185                             /*IsFunctionCall*/ true, CheckedVarArgs,
7186                             UncoveredArg,
7187                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7188 
7189   // Generate a diagnostic where an uncovered argument is detected.
7190   if (UncoveredArg.hasUncoveredArg()) {
7191     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7192     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7193     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7194   }
7195 
7196   if (CT != SLCT_NotALiteral)
7197     // Literal format string found, check done!
7198     return CT == SLCT_CheckedLiteral;
7199 
7200   // Strftime is particular as it always uses a single 'time' argument,
7201   // so it is safe to pass a non-literal string.
7202   if (Type == FST_Strftime)
7203     return false;
7204 
7205   // Do not emit diag when the string param is a macro expansion and the
7206   // format is either NSString or CFString. This is a hack to prevent
7207   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7208   // which are usually used in place of NS and CF string literals.
7209   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7210   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7211     return false;
7212 
7213   // If there are no arguments specified, warn with -Wformat-security, otherwise
7214   // warn only with -Wformat-nonliteral.
7215   if (Args.size() == firstDataArg) {
7216     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7217       << OrigFormatExpr->getSourceRange();
7218     switch (Type) {
7219     default:
7220       break;
7221     case FST_Kprintf:
7222     case FST_FreeBSDKPrintf:
7223     case FST_Printf:
7224       Diag(FormatLoc, diag::note_format_security_fixit)
7225         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7226       break;
7227     case FST_NSString:
7228       Diag(FormatLoc, diag::note_format_security_fixit)
7229         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7230       break;
7231     }
7232   } else {
7233     Diag(FormatLoc, diag::warn_format_nonliteral)
7234       << OrigFormatExpr->getSourceRange();
7235   }
7236   return false;
7237 }
7238 
7239 namespace {
7240 
7241 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7242 protected:
7243   Sema &S;
7244   const FormatStringLiteral *FExpr;
7245   const Expr *OrigFormatExpr;
7246   const Sema::FormatStringType FSType;
7247   const unsigned FirstDataArg;
7248   const unsigned NumDataArgs;
7249   const char *Beg; // Start of format string.
7250   const bool HasVAListArg;
7251   ArrayRef<const Expr *> Args;
7252   unsigned FormatIdx;
7253   llvm::SmallBitVector CoveredArgs;
7254   bool usesPositionalArgs = false;
7255   bool atFirstArg = true;
7256   bool inFunctionCall;
7257   Sema::VariadicCallType CallType;
7258   llvm::SmallBitVector &CheckedVarArgs;
7259   UncoveredArgHandler &UncoveredArg;
7260 
7261 public:
7262   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7263                      const Expr *origFormatExpr,
7264                      const Sema::FormatStringType type, unsigned firstDataArg,
7265                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7266                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7267                      bool inFunctionCall, Sema::VariadicCallType callType,
7268                      llvm::SmallBitVector &CheckedVarArgs,
7269                      UncoveredArgHandler &UncoveredArg)
7270       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7271         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7272         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7273         inFunctionCall(inFunctionCall), CallType(callType),
7274         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7275     CoveredArgs.resize(numDataArgs);
7276     CoveredArgs.reset();
7277   }
7278 
7279   void DoneProcessing();
7280 
7281   void HandleIncompleteSpecifier(const char *startSpecifier,
7282                                  unsigned specifierLen) override;
7283 
7284   void HandleInvalidLengthModifier(
7285                            const analyze_format_string::FormatSpecifier &FS,
7286                            const analyze_format_string::ConversionSpecifier &CS,
7287                            const char *startSpecifier, unsigned specifierLen,
7288                            unsigned DiagID);
7289 
7290   void HandleNonStandardLengthModifier(
7291                     const analyze_format_string::FormatSpecifier &FS,
7292                     const char *startSpecifier, unsigned specifierLen);
7293 
7294   void HandleNonStandardConversionSpecifier(
7295                     const analyze_format_string::ConversionSpecifier &CS,
7296                     const char *startSpecifier, unsigned specifierLen);
7297 
7298   void HandlePosition(const char *startPos, unsigned posLen) override;
7299 
7300   void HandleInvalidPosition(const char *startSpecifier,
7301                              unsigned specifierLen,
7302                              analyze_format_string::PositionContext p) override;
7303 
7304   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7305 
7306   void HandleNullChar(const char *nullCharacter) override;
7307 
7308   template <typename Range>
7309   static void
7310   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7311                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7312                        bool IsStringLocation, Range StringRange,
7313                        ArrayRef<FixItHint> Fixit = None);
7314 
7315 protected:
7316   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7317                                         const char *startSpec,
7318                                         unsigned specifierLen,
7319                                         const char *csStart, unsigned csLen);
7320 
7321   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7322                                          const char *startSpec,
7323                                          unsigned specifierLen);
7324 
7325   SourceRange getFormatStringRange();
7326   CharSourceRange getSpecifierRange(const char *startSpecifier,
7327                                     unsigned specifierLen);
7328   SourceLocation getLocationOfByte(const char *x);
7329 
7330   const Expr *getDataArg(unsigned i) const;
7331 
7332   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7333                     const analyze_format_string::ConversionSpecifier &CS,
7334                     const char *startSpecifier, unsigned specifierLen,
7335                     unsigned argIndex);
7336 
7337   template <typename Range>
7338   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7339                             bool IsStringLocation, Range StringRange,
7340                             ArrayRef<FixItHint> Fixit = None);
7341 };
7342 
7343 } // namespace
7344 
7345 SourceRange CheckFormatHandler::getFormatStringRange() {
7346   return OrigFormatExpr->getSourceRange();
7347 }
7348 
7349 CharSourceRange CheckFormatHandler::
7350 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7351   SourceLocation Start = getLocationOfByte(startSpecifier);
7352   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7353 
7354   // Advance the end SourceLocation by one due to half-open ranges.
7355   End = End.getLocWithOffset(1);
7356 
7357   return CharSourceRange::getCharRange(Start, End);
7358 }
7359 
7360 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7361   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7362                                   S.getLangOpts(), S.Context.getTargetInfo());
7363 }
7364 
7365 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7366                                                    unsigned specifierLen){
7367   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7368                        getLocationOfByte(startSpecifier),
7369                        /*IsStringLocation*/true,
7370                        getSpecifierRange(startSpecifier, specifierLen));
7371 }
7372 
7373 void CheckFormatHandler::HandleInvalidLengthModifier(
7374     const analyze_format_string::FormatSpecifier &FS,
7375     const analyze_format_string::ConversionSpecifier &CS,
7376     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7377   using namespace analyze_format_string;
7378 
7379   const LengthModifier &LM = FS.getLengthModifier();
7380   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7381 
7382   // See if we know how to fix this length modifier.
7383   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7384   if (FixedLM) {
7385     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7386                          getLocationOfByte(LM.getStart()),
7387                          /*IsStringLocation*/true,
7388                          getSpecifierRange(startSpecifier, specifierLen));
7389 
7390     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7391       << FixedLM->toString()
7392       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7393 
7394   } else {
7395     FixItHint Hint;
7396     if (DiagID == diag::warn_format_nonsensical_length)
7397       Hint = FixItHint::CreateRemoval(LMRange);
7398 
7399     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7400                          getLocationOfByte(LM.getStart()),
7401                          /*IsStringLocation*/true,
7402                          getSpecifierRange(startSpecifier, specifierLen),
7403                          Hint);
7404   }
7405 }
7406 
7407 void CheckFormatHandler::HandleNonStandardLengthModifier(
7408     const analyze_format_string::FormatSpecifier &FS,
7409     const char *startSpecifier, unsigned specifierLen) {
7410   using namespace analyze_format_string;
7411 
7412   const LengthModifier &LM = FS.getLengthModifier();
7413   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7414 
7415   // See if we know how to fix this length modifier.
7416   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7417   if (FixedLM) {
7418     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7419                            << LM.toString() << 0,
7420                          getLocationOfByte(LM.getStart()),
7421                          /*IsStringLocation*/true,
7422                          getSpecifierRange(startSpecifier, specifierLen));
7423 
7424     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7425       << FixedLM->toString()
7426       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7427 
7428   } else {
7429     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7430                            << LM.toString() << 0,
7431                          getLocationOfByte(LM.getStart()),
7432                          /*IsStringLocation*/true,
7433                          getSpecifierRange(startSpecifier, specifierLen));
7434   }
7435 }
7436 
7437 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7438     const analyze_format_string::ConversionSpecifier &CS,
7439     const char *startSpecifier, unsigned specifierLen) {
7440   using namespace analyze_format_string;
7441 
7442   // See if we know how to fix this conversion specifier.
7443   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7444   if (FixedCS) {
7445     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7446                           << CS.toString() << /*conversion specifier*/1,
7447                          getLocationOfByte(CS.getStart()),
7448                          /*IsStringLocation*/true,
7449                          getSpecifierRange(startSpecifier, specifierLen));
7450 
7451     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7452     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7453       << FixedCS->toString()
7454       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7455   } else {
7456     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7457                           << CS.toString() << /*conversion specifier*/1,
7458                          getLocationOfByte(CS.getStart()),
7459                          /*IsStringLocation*/true,
7460                          getSpecifierRange(startSpecifier, specifierLen));
7461   }
7462 }
7463 
7464 void CheckFormatHandler::HandlePosition(const char *startPos,
7465                                         unsigned posLen) {
7466   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7467                                getLocationOfByte(startPos),
7468                                /*IsStringLocation*/true,
7469                                getSpecifierRange(startPos, posLen));
7470 }
7471 
7472 void
7473 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7474                                      analyze_format_string::PositionContext p) {
7475   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7476                          << (unsigned) p,
7477                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7478                        getSpecifierRange(startPos, posLen));
7479 }
7480 
7481 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7482                                             unsigned posLen) {
7483   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7484                                getLocationOfByte(startPos),
7485                                /*IsStringLocation*/true,
7486                                getSpecifierRange(startPos, posLen));
7487 }
7488 
7489 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7490   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7491     // The presence of a null character is likely an error.
7492     EmitFormatDiagnostic(
7493       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7494       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7495       getFormatStringRange());
7496   }
7497 }
7498 
7499 // Note that this may return NULL if there was an error parsing or building
7500 // one of the argument expressions.
7501 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7502   return Args[FirstDataArg + i];
7503 }
7504 
7505 void CheckFormatHandler::DoneProcessing() {
7506   // Does the number of data arguments exceed the number of
7507   // format conversions in the format string?
7508   if (!HasVAListArg) {
7509       // Find any arguments that weren't covered.
7510     CoveredArgs.flip();
7511     signed notCoveredArg = CoveredArgs.find_first();
7512     if (notCoveredArg >= 0) {
7513       assert((unsigned)notCoveredArg < NumDataArgs);
7514       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7515     } else {
7516       UncoveredArg.setAllCovered();
7517     }
7518   }
7519 }
7520 
7521 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7522                                    const Expr *ArgExpr) {
7523   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7524          "Invalid state");
7525 
7526   if (!ArgExpr)
7527     return;
7528 
7529   SourceLocation Loc = ArgExpr->getBeginLoc();
7530 
7531   if (S.getSourceManager().isInSystemMacro(Loc))
7532     return;
7533 
7534   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7535   for (auto E : DiagnosticExprs)
7536     PDiag << E->getSourceRange();
7537 
7538   CheckFormatHandler::EmitFormatDiagnostic(
7539                                   S, IsFunctionCall, DiagnosticExprs[0],
7540                                   PDiag, Loc, /*IsStringLocation*/false,
7541                                   DiagnosticExprs[0]->getSourceRange());
7542 }
7543 
7544 bool
7545 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7546                                                      SourceLocation Loc,
7547                                                      const char *startSpec,
7548                                                      unsigned specifierLen,
7549                                                      const char *csStart,
7550                                                      unsigned csLen) {
7551   bool keepGoing = true;
7552   if (argIndex < NumDataArgs) {
7553     // Consider the argument coverered, even though the specifier doesn't
7554     // make sense.
7555     CoveredArgs.set(argIndex);
7556   }
7557   else {
7558     // If argIndex exceeds the number of data arguments we
7559     // don't issue a warning because that is just a cascade of warnings (and
7560     // they may have intended '%%' anyway). We don't want to continue processing
7561     // the format string after this point, however, as we will like just get
7562     // gibberish when trying to match arguments.
7563     keepGoing = false;
7564   }
7565 
7566   StringRef Specifier(csStart, csLen);
7567 
7568   // If the specifier in non-printable, it could be the first byte of a UTF-8
7569   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7570   // hex value.
7571   std::string CodePointStr;
7572   if (!llvm::sys::locale::isPrint(*csStart)) {
7573     llvm::UTF32 CodePoint;
7574     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7575     const llvm::UTF8 *E =
7576         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7577     llvm::ConversionResult Result =
7578         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7579 
7580     if (Result != llvm::conversionOK) {
7581       unsigned char FirstChar = *csStart;
7582       CodePoint = (llvm::UTF32)FirstChar;
7583     }
7584 
7585     llvm::raw_string_ostream OS(CodePointStr);
7586     if (CodePoint < 256)
7587       OS << "\\x" << llvm::format("%02x", CodePoint);
7588     else if (CodePoint <= 0xFFFF)
7589       OS << "\\u" << llvm::format("%04x", CodePoint);
7590     else
7591       OS << "\\U" << llvm::format("%08x", CodePoint);
7592     OS.flush();
7593     Specifier = CodePointStr;
7594   }
7595 
7596   EmitFormatDiagnostic(
7597       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7598       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7599 
7600   return keepGoing;
7601 }
7602 
7603 void
7604 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7605                                                       const char *startSpec,
7606                                                       unsigned specifierLen) {
7607   EmitFormatDiagnostic(
7608     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7609     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7610 }
7611 
7612 bool
7613 CheckFormatHandler::CheckNumArgs(
7614   const analyze_format_string::FormatSpecifier &FS,
7615   const analyze_format_string::ConversionSpecifier &CS,
7616   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7617 
7618   if (argIndex >= NumDataArgs) {
7619     PartialDiagnostic PDiag = FS.usesPositionalArg()
7620       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7621            << (argIndex+1) << NumDataArgs)
7622       : S.PDiag(diag::warn_printf_insufficient_data_args);
7623     EmitFormatDiagnostic(
7624       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7625       getSpecifierRange(startSpecifier, specifierLen));
7626 
7627     // Since more arguments than conversion tokens are given, by extension
7628     // all arguments are covered, so mark this as so.
7629     UncoveredArg.setAllCovered();
7630     return false;
7631   }
7632   return true;
7633 }
7634 
7635 template<typename Range>
7636 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7637                                               SourceLocation Loc,
7638                                               bool IsStringLocation,
7639                                               Range StringRange,
7640                                               ArrayRef<FixItHint> FixIt) {
7641   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7642                        Loc, IsStringLocation, StringRange, FixIt);
7643 }
7644 
7645 /// If the format string is not within the function call, emit a note
7646 /// so that the function call and string are in diagnostic messages.
7647 ///
7648 /// \param InFunctionCall if true, the format string is within the function
7649 /// call and only one diagnostic message will be produced.  Otherwise, an
7650 /// extra note will be emitted pointing to location of the format string.
7651 ///
7652 /// \param ArgumentExpr the expression that is passed as the format string
7653 /// argument in the function call.  Used for getting locations when two
7654 /// diagnostics are emitted.
7655 ///
7656 /// \param PDiag the callee should already have provided any strings for the
7657 /// diagnostic message.  This function only adds locations and fixits
7658 /// to diagnostics.
7659 ///
7660 /// \param Loc primary location for diagnostic.  If two diagnostics are
7661 /// required, one will be at Loc and a new SourceLocation will be created for
7662 /// the other one.
7663 ///
7664 /// \param IsStringLocation if true, Loc points to the format string should be
7665 /// used for the note.  Otherwise, Loc points to the argument list and will
7666 /// be used with PDiag.
7667 ///
7668 /// \param StringRange some or all of the string to highlight.  This is
7669 /// templated so it can accept either a CharSourceRange or a SourceRange.
7670 ///
7671 /// \param FixIt optional fix it hint for the format string.
7672 template <typename Range>
7673 void CheckFormatHandler::EmitFormatDiagnostic(
7674     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7675     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7676     Range StringRange, ArrayRef<FixItHint> FixIt) {
7677   if (InFunctionCall) {
7678     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7679     D << StringRange;
7680     D << FixIt;
7681   } else {
7682     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7683       << ArgumentExpr->getSourceRange();
7684 
7685     const Sema::SemaDiagnosticBuilder &Note =
7686       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7687              diag::note_format_string_defined);
7688 
7689     Note << StringRange;
7690     Note << FixIt;
7691   }
7692 }
7693 
7694 //===--- CHECK: Printf format string checking ------------------------------===//
7695 
7696 namespace {
7697 
7698 class CheckPrintfHandler : public CheckFormatHandler {
7699 public:
7700   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7701                      const Expr *origFormatExpr,
7702                      const Sema::FormatStringType type, unsigned firstDataArg,
7703                      unsigned numDataArgs, bool isObjC, const char *beg,
7704                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7705                      unsigned formatIdx, bool inFunctionCall,
7706                      Sema::VariadicCallType CallType,
7707                      llvm::SmallBitVector &CheckedVarArgs,
7708                      UncoveredArgHandler &UncoveredArg)
7709       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7710                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7711                            inFunctionCall, CallType, CheckedVarArgs,
7712                            UncoveredArg) {}
7713 
7714   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7715 
7716   /// Returns true if '%@' specifiers are allowed in the format string.
7717   bool allowsObjCArg() const {
7718     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7719            FSType == Sema::FST_OSTrace;
7720   }
7721 
7722   bool HandleInvalidPrintfConversionSpecifier(
7723                                       const analyze_printf::PrintfSpecifier &FS,
7724                                       const char *startSpecifier,
7725                                       unsigned specifierLen) override;
7726 
7727   void handleInvalidMaskType(StringRef MaskType) override;
7728 
7729   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7730                              const char *startSpecifier,
7731                              unsigned specifierLen) override;
7732   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7733                        const char *StartSpecifier,
7734                        unsigned SpecifierLen,
7735                        const Expr *E);
7736 
7737   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7738                     const char *startSpecifier, unsigned specifierLen);
7739   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7740                            const analyze_printf::OptionalAmount &Amt,
7741                            unsigned type,
7742                            const char *startSpecifier, unsigned specifierLen);
7743   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7744                   const analyze_printf::OptionalFlag &flag,
7745                   const char *startSpecifier, unsigned specifierLen);
7746   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7747                          const analyze_printf::OptionalFlag &ignoredFlag,
7748                          const analyze_printf::OptionalFlag &flag,
7749                          const char *startSpecifier, unsigned specifierLen);
7750   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7751                            const Expr *E);
7752 
7753   void HandleEmptyObjCModifierFlag(const char *startFlag,
7754                                    unsigned flagLen) override;
7755 
7756   void HandleInvalidObjCModifierFlag(const char *startFlag,
7757                                             unsigned flagLen) override;
7758 
7759   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7760                                            const char *flagsEnd,
7761                                            const char *conversionPosition)
7762                                              override;
7763 };
7764 
7765 } // namespace
7766 
7767 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7768                                       const analyze_printf::PrintfSpecifier &FS,
7769                                       const char *startSpecifier,
7770                                       unsigned specifierLen) {
7771   const analyze_printf::PrintfConversionSpecifier &CS =
7772     FS.getConversionSpecifier();
7773 
7774   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7775                                           getLocationOfByte(CS.getStart()),
7776                                           startSpecifier, specifierLen,
7777                                           CS.getStart(), CS.getLength());
7778 }
7779 
7780 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7781   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7782 }
7783 
7784 bool CheckPrintfHandler::HandleAmount(
7785                                const analyze_format_string::OptionalAmount &Amt,
7786                                unsigned k, const char *startSpecifier,
7787                                unsigned specifierLen) {
7788   if (Amt.hasDataArgument()) {
7789     if (!HasVAListArg) {
7790       unsigned argIndex = Amt.getArgIndex();
7791       if (argIndex >= NumDataArgs) {
7792         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7793                                << k,
7794                              getLocationOfByte(Amt.getStart()),
7795                              /*IsStringLocation*/true,
7796                              getSpecifierRange(startSpecifier, specifierLen));
7797         // Don't do any more checking.  We will just emit
7798         // spurious errors.
7799         return false;
7800       }
7801 
7802       // Type check the data argument.  It should be an 'int'.
7803       // Although not in conformance with C99, we also allow the argument to be
7804       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7805       // doesn't emit a warning for that case.
7806       CoveredArgs.set(argIndex);
7807       const Expr *Arg = getDataArg(argIndex);
7808       if (!Arg)
7809         return false;
7810 
7811       QualType T = Arg->getType();
7812 
7813       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7814       assert(AT.isValid());
7815 
7816       if (!AT.matchesType(S.Context, T)) {
7817         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7818                                << k << AT.getRepresentativeTypeName(S.Context)
7819                                << T << Arg->getSourceRange(),
7820                              getLocationOfByte(Amt.getStart()),
7821                              /*IsStringLocation*/true,
7822                              getSpecifierRange(startSpecifier, specifierLen));
7823         // Don't do any more checking.  We will just emit
7824         // spurious errors.
7825         return false;
7826       }
7827     }
7828   }
7829   return true;
7830 }
7831 
7832 void CheckPrintfHandler::HandleInvalidAmount(
7833                                       const analyze_printf::PrintfSpecifier &FS,
7834                                       const analyze_printf::OptionalAmount &Amt,
7835                                       unsigned type,
7836                                       const char *startSpecifier,
7837                                       unsigned specifierLen) {
7838   const analyze_printf::PrintfConversionSpecifier &CS =
7839     FS.getConversionSpecifier();
7840 
7841   FixItHint fixit =
7842     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7843       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7844                                  Amt.getConstantLength()))
7845       : FixItHint();
7846 
7847   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7848                          << type << CS.toString(),
7849                        getLocationOfByte(Amt.getStart()),
7850                        /*IsStringLocation*/true,
7851                        getSpecifierRange(startSpecifier, specifierLen),
7852                        fixit);
7853 }
7854 
7855 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7856                                     const analyze_printf::OptionalFlag &flag,
7857                                     const char *startSpecifier,
7858                                     unsigned specifierLen) {
7859   // Warn about pointless flag with a fixit removal.
7860   const analyze_printf::PrintfConversionSpecifier &CS =
7861     FS.getConversionSpecifier();
7862   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7863                          << flag.toString() << CS.toString(),
7864                        getLocationOfByte(flag.getPosition()),
7865                        /*IsStringLocation*/true,
7866                        getSpecifierRange(startSpecifier, specifierLen),
7867                        FixItHint::CreateRemoval(
7868                          getSpecifierRange(flag.getPosition(), 1)));
7869 }
7870 
7871 void CheckPrintfHandler::HandleIgnoredFlag(
7872                                 const analyze_printf::PrintfSpecifier &FS,
7873                                 const analyze_printf::OptionalFlag &ignoredFlag,
7874                                 const analyze_printf::OptionalFlag &flag,
7875                                 const char *startSpecifier,
7876                                 unsigned specifierLen) {
7877   // Warn about ignored flag with a fixit removal.
7878   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7879                          << ignoredFlag.toString() << flag.toString(),
7880                        getLocationOfByte(ignoredFlag.getPosition()),
7881                        /*IsStringLocation*/true,
7882                        getSpecifierRange(startSpecifier, specifierLen),
7883                        FixItHint::CreateRemoval(
7884                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7885 }
7886 
7887 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7888                                                      unsigned flagLen) {
7889   // Warn about an empty flag.
7890   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7891                        getLocationOfByte(startFlag),
7892                        /*IsStringLocation*/true,
7893                        getSpecifierRange(startFlag, flagLen));
7894 }
7895 
7896 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7897                                                        unsigned flagLen) {
7898   // Warn about an invalid flag.
7899   auto Range = getSpecifierRange(startFlag, flagLen);
7900   StringRef flag(startFlag, flagLen);
7901   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7902                       getLocationOfByte(startFlag),
7903                       /*IsStringLocation*/true,
7904                       Range, FixItHint::CreateRemoval(Range));
7905 }
7906 
7907 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7908     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7909     // Warn about using '[...]' without a '@' conversion.
7910     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7911     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7912     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7913                          getLocationOfByte(conversionPosition),
7914                          /*IsStringLocation*/true,
7915                          Range, FixItHint::CreateRemoval(Range));
7916 }
7917 
7918 // Determines if the specified is a C++ class or struct containing
7919 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7920 // "c_str()").
7921 template<typename MemberKind>
7922 static llvm::SmallPtrSet<MemberKind*, 1>
7923 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7924   const RecordType *RT = Ty->getAs<RecordType>();
7925   llvm::SmallPtrSet<MemberKind*, 1> Results;
7926 
7927   if (!RT)
7928     return Results;
7929   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7930   if (!RD || !RD->getDefinition())
7931     return Results;
7932 
7933   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7934                  Sema::LookupMemberName);
7935   R.suppressDiagnostics();
7936 
7937   // We just need to include all members of the right kind turned up by the
7938   // filter, at this point.
7939   if (S.LookupQualifiedName(R, RT->getDecl()))
7940     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7941       NamedDecl *decl = (*I)->getUnderlyingDecl();
7942       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7943         Results.insert(FK);
7944     }
7945   return Results;
7946 }
7947 
7948 /// Check if we could call '.c_str()' on an object.
7949 ///
7950 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7951 /// allow the call, or if it would be ambiguous).
7952 bool Sema::hasCStrMethod(const Expr *E) {
7953   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7954 
7955   MethodSet Results =
7956       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7957   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7958        MI != ME; ++MI)
7959     if ((*MI)->getMinRequiredArguments() == 0)
7960       return true;
7961   return false;
7962 }
7963 
7964 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7965 // better diagnostic if so. AT is assumed to be valid.
7966 // Returns true when a c_str() conversion method is found.
7967 bool CheckPrintfHandler::checkForCStrMembers(
7968     const analyze_printf::ArgType &AT, const Expr *E) {
7969   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7970 
7971   MethodSet Results =
7972       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7973 
7974   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7975        MI != ME; ++MI) {
7976     const CXXMethodDecl *Method = *MI;
7977     if (Method->getMinRequiredArguments() == 0 &&
7978         AT.matchesType(S.Context, Method->getReturnType())) {
7979       // FIXME: Suggest parens if the expression needs them.
7980       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7981       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7982           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7983       return true;
7984     }
7985   }
7986 
7987   return false;
7988 }
7989 
7990 bool
7991 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7992                                             &FS,
7993                                           const char *startSpecifier,
7994                                           unsigned specifierLen) {
7995   using namespace analyze_format_string;
7996   using namespace analyze_printf;
7997 
7998   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7999 
8000   if (FS.consumesDataArgument()) {
8001     if (atFirstArg) {
8002         atFirstArg = false;
8003         usesPositionalArgs = FS.usesPositionalArg();
8004     }
8005     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8006       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8007                                         startSpecifier, specifierLen);
8008       return false;
8009     }
8010   }
8011 
8012   // First check if the field width, precision, and conversion specifier
8013   // have matching data arguments.
8014   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8015                     startSpecifier, specifierLen)) {
8016     return false;
8017   }
8018 
8019   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8020                     startSpecifier, specifierLen)) {
8021     return false;
8022   }
8023 
8024   if (!CS.consumesDataArgument()) {
8025     // FIXME: Technically specifying a precision or field width here
8026     // makes no sense.  Worth issuing a warning at some point.
8027     return true;
8028   }
8029 
8030   // Consume the argument.
8031   unsigned argIndex = FS.getArgIndex();
8032   if (argIndex < NumDataArgs) {
8033     // The check to see if the argIndex is valid will come later.
8034     // We set the bit here because we may exit early from this
8035     // function if we encounter some other error.
8036     CoveredArgs.set(argIndex);
8037   }
8038 
8039   // FreeBSD kernel extensions.
8040   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8041       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8042     // We need at least two arguments.
8043     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8044       return false;
8045 
8046     // Claim the second argument.
8047     CoveredArgs.set(argIndex + 1);
8048 
8049     // Type check the first argument (int for %b, pointer for %D)
8050     const Expr *Ex = getDataArg(argIndex);
8051     const analyze_printf::ArgType &AT =
8052       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8053         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8054     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8055       EmitFormatDiagnostic(
8056           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8057               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8058               << false << Ex->getSourceRange(),
8059           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8060           getSpecifierRange(startSpecifier, specifierLen));
8061 
8062     // Type check the second argument (char * for both %b and %D)
8063     Ex = getDataArg(argIndex + 1);
8064     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8065     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8066       EmitFormatDiagnostic(
8067           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8068               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8069               << false << Ex->getSourceRange(),
8070           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8071           getSpecifierRange(startSpecifier, specifierLen));
8072 
8073      return true;
8074   }
8075 
8076   // Check for using an Objective-C specific conversion specifier
8077   // in a non-ObjC literal.
8078   if (!allowsObjCArg() && CS.isObjCArg()) {
8079     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8080                                                   specifierLen);
8081   }
8082 
8083   // %P can only be used with os_log.
8084   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8085     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8086                                                   specifierLen);
8087   }
8088 
8089   // %n is not allowed with os_log.
8090   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8091     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8092                          getLocationOfByte(CS.getStart()),
8093                          /*IsStringLocation*/ false,
8094                          getSpecifierRange(startSpecifier, specifierLen));
8095 
8096     return true;
8097   }
8098 
8099   // Only scalars are allowed for os_trace.
8100   if (FSType == Sema::FST_OSTrace &&
8101       (CS.getKind() == ConversionSpecifier::PArg ||
8102        CS.getKind() == ConversionSpecifier::sArg ||
8103        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8104     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8105                                                   specifierLen);
8106   }
8107 
8108   // Check for use of public/private annotation outside of os_log().
8109   if (FSType != Sema::FST_OSLog) {
8110     if (FS.isPublic().isSet()) {
8111       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8112                                << "public",
8113                            getLocationOfByte(FS.isPublic().getPosition()),
8114                            /*IsStringLocation*/ false,
8115                            getSpecifierRange(startSpecifier, specifierLen));
8116     }
8117     if (FS.isPrivate().isSet()) {
8118       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8119                                << "private",
8120                            getLocationOfByte(FS.isPrivate().getPosition()),
8121                            /*IsStringLocation*/ false,
8122                            getSpecifierRange(startSpecifier, specifierLen));
8123     }
8124   }
8125 
8126   // Check for invalid use of field width
8127   if (!FS.hasValidFieldWidth()) {
8128     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8129         startSpecifier, specifierLen);
8130   }
8131 
8132   // Check for invalid use of precision
8133   if (!FS.hasValidPrecision()) {
8134     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8135         startSpecifier, specifierLen);
8136   }
8137 
8138   // Precision is mandatory for %P specifier.
8139   if (CS.getKind() == ConversionSpecifier::PArg &&
8140       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8141     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8142                          getLocationOfByte(startSpecifier),
8143                          /*IsStringLocation*/ false,
8144                          getSpecifierRange(startSpecifier, specifierLen));
8145   }
8146 
8147   // Check each flag does not conflict with any other component.
8148   if (!FS.hasValidThousandsGroupingPrefix())
8149     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8150   if (!FS.hasValidLeadingZeros())
8151     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8152   if (!FS.hasValidPlusPrefix())
8153     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8154   if (!FS.hasValidSpacePrefix())
8155     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8156   if (!FS.hasValidAlternativeForm())
8157     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8158   if (!FS.hasValidLeftJustified())
8159     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8160 
8161   // Check that flags are not ignored by another flag
8162   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8163     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8164         startSpecifier, specifierLen);
8165   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8166     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8167             startSpecifier, specifierLen);
8168 
8169   // Check the length modifier is valid with the given conversion specifier.
8170   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8171                                  S.getLangOpts()))
8172     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8173                                 diag::warn_format_nonsensical_length);
8174   else if (!FS.hasStandardLengthModifier())
8175     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8176   else if (!FS.hasStandardLengthConversionCombination())
8177     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8178                                 diag::warn_format_non_standard_conversion_spec);
8179 
8180   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8181     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8182 
8183   // The remaining checks depend on the data arguments.
8184   if (HasVAListArg)
8185     return true;
8186 
8187   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8188     return false;
8189 
8190   const Expr *Arg = getDataArg(argIndex);
8191   if (!Arg)
8192     return true;
8193 
8194   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8195 }
8196 
8197 static bool requiresParensToAddCast(const Expr *E) {
8198   // FIXME: We should have a general way to reason about operator
8199   // precedence and whether parens are actually needed here.
8200   // Take care of a few common cases where they aren't.
8201   const Expr *Inside = E->IgnoreImpCasts();
8202   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8203     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8204 
8205   switch (Inside->getStmtClass()) {
8206   case Stmt::ArraySubscriptExprClass:
8207   case Stmt::CallExprClass:
8208   case Stmt::CharacterLiteralClass:
8209   case Stmt::CXXBoolLiteralExprClass:
8210   case Stmt::DeclRefExprClass:
8211   case Stmt::FloatingLiteralClass:
8212   case Stmt::IntegerLiteralClass:
8213   case Stmt::MemberExprClass:
8214   case Stmt::ObjCArrayLiteralClass:
8215   case Stmt::ObjCBoolLiteralExprClass:
8216   case Stmt::ObjCBoxedExprClass:
8217   case Stmt::ObjCDictionaryLiteralClass:
8218   case Stmt::ObjCEncodeExprClass:
8219   case Stmt::ObjCIvarRefExprClass:
8220   case Stmt::ObjCMessageExprClass:
8221   case Stmt::ObjCPropertyRefExprClass:
8222   case Stmt::ObjCStringLiteralClass:
8223   case Stmt::ObjCSubscriptRefExprClass:
8224   case Stmt::ParenExprClass:
8225   case Stmt::StringLiteralClass:
8226   case Stmt::UnaryOperatorClass:
8227     return false;
8228   default:
8229     return true;
8230   }
8231 }
8232 
8233 static std::pair<QualType, StringRef>
8234 shouldNotPrintDirectly(const ASTContext &Context,
8235                        QualType IntendedTy,
8236                        const Expr *E) {
8237   // Use a 'while' to peel off layers of typedefs.
8238   QualType TyTy = IntendedTy;
8239   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8240     StringRef Name = UserTy->getDecl()->getName();
8241     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8242       .Case("CFIndex", Context.getNSIntegerType())
8243       .Case("NSInteger", Context.getNSIntegerType())
8244       .Case("NSUInteger", Context.getNSUIntegerType())
8245       .Case("SInt32", Context.IntTy)
8246       .Case("UInt32", Context.UnsignedIntTy)
8247       .Default(QualType());
8248 
8249     if (!CastTy.isNull())
8250       return std::make_pair(CastTy, Name);
8251 
8252     TyTy = UserTy->desugar();
8253   }
8254 
8255   // Strip parens if necessary.
8256   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8257     return shouldNotPrintDirectly(Context,
8258                                   PE->getSubExpr()->getType(),
8259                                   PE->getSubExpr());
8260 
8261   // If this is a conditional expression, then its result type is constructed
8262   // via usual arithmetic conversions and thus there might be no necessary
8263   // typedef sugar there.  Recurse to operands to check for NSInteger &
8264   // Co. usage condition.
8265   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8266     QualType TrueTy, FalseTy;
8267     StringRef TrueName, FalseName;
8268 
8269     std::tie(TrueTy, TrueName) =
8270       shouldNotPrintDirectly(Context,
8271                              CO->getTrueExpr()->getType(),
8272                              CO->getTrueExpr());
8273     std::tie(FalseTy, FalseName) =
8274       shouldNotPrintDirectly(Context,
8275                              CO->getFalseExpr()->getType(),
8276                              CO->getFalseExpr());
8277 
8278     if (TrueTy == FalseTy)
8279       return std::make_pair(TrueTy, TrueName);
8280     else if (TrueTy.isNull())
8281       return std::make_pair(FalseTy, FalseName);
8282     else if (FalseTy.isNull())
8283       return std::make_pair(TrueTy, TrueName);
8284   }
8285 
8286   return std::make_pair(QualType(), StringRef());
8287 }
8288 
8289 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8290 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8291 /// type do not count.
8292 static bool
8293 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8294   QualType From = ICE->getSubExpr()->getType();
8295   QualType To = ICE->getType();
8296   // It's an integer promotion if the destination type is the promoted
8297   // source type.
8298   if (ICE->getCastKind() == CK_IntegralCast &&
8299       From->isPromotableIntegerType() &&
8300       S.Context.getPromotedIntegerType(From) == To)
8301     return true;
8302   // Look through vector types, since we do default argument promotion for
8303   // those in OpenCL.
8304   if (const auto *VecTy = From->getAs<ExtVectorType>())
8305     From = VecTy->getElementType();
8306   if (const auto *VecTy = To->getAs<ExtVectorType>())
8307     To = VecTy->getElementType();
8308   // It's a floating promotion if the source type is a lower rank.
8309   return ICE->getCastKind() == CK_FloatingCast &&
8310          S.Context.getFloatingTypeOrder(From, To) < 0;
8311 }
8312 
8313 bool
8314 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8315                                     const char *StartSpecifier,
8316                                     unsigned SpecifierLen,
8317                                     const Expr *E) {
8318   using namespace analyze_format_string;
8319   using namespace analyze_printf;
8320 
8321   // Now type check the data expression that matches the
8322   // format specifier.
8323   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8324   if (!AT.isValid())
8325     return true;
8326 
8327   QualType ExprTy = E->getType();
8328   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8329     ExprTy = TET->getUnderlyingExpr()->getType();
8330   }
8331 
8332   // Diagnose attempts to print a boolean value as a character. Unlike other
8333   // -Wformat diagnostics, this is fine from a type perspective, but it still
8334   // doesn't make sense.
8335   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8336       E->isKnownToHaveBooleanValue()) {
8337     const CharSourceRange &CSR =
8338         getSpecifierRange(StartSpecifier, SpecifierLen);
8339     SmallString<4> FSString;
8340     llvm::raw_svector_ostream os(FSString);
8341     FS.toString(os);
8342     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8343                              << FSString,
8344                          E->getExprLoc(), false, CSR);
8345     return true;
8346   }
8347 
8348   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8349   if (Match == analyze_printf::ArgType::Match)
8350     return true;
8351 
8352   // Look through argument promotions for our error message's reported type.
8353   // This includes the integral and floating promotions, but excludes array
8354   // and function pointer decay (seeing that an argument intended to be a
8355   // string has type 'char [6]' is probably more confusing than 'char *') and
8356   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8357   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8358     if (isArithmeticArgumentPromotion(S, ICE)) {
8359       E = ICE->getSubExpr();
8360       ExprTy = E->getType();
8361 
8362       // Check if we didn't match because of an implicit cast from a 'char'
8363       // or 'short' to an 'int'.  This is done because printf is a varargs
8364       // function.
8365       if (ICE->getType() == S.Context.IntTy ||
8366           ICE->getType() == S.Context.UnsignedIntTy) {
8367         // All further checking is done on the subexpression
8368         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8369             AT.matchesType(S.Context, ExprTy);
8370         if (ImplicitMatch == analyze_printf::ArgType::Match)
8371           return true;
8372         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8373             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8374           Match = ImplicitMatch;
8375       }
8376     }
8377   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8378     // Special case for 'a', which has type 'int' in C.
8379     // Note, however, that we do /not/ want to treat multibyte constants like
8380     // 'MooV' as characters! This form is deprecated but still exists.
8381     if (ExprTy == S.Context.IntTy)
8382       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8383         ExprTy = S.Context.CharTy;
8384   }
8385 
8386   // Look through enums to their underlying type.
8387   bool IsEnum = false;
8388   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8389     ExprTy = EnumTy->getDecl()->getIntegerType();
8390     IsEnum = true;
8391   }
8392 
8393   // %C in an Objective-C context prints a unichar, not a wchar_t.
8394   // If the argument is an integer of some kind, believe the %C and suggest
8395   // a cast instead of changing the conversion specifier.
8396   QualType IntendedTy = ExprTy;
8397   if (isObjCContext() &&
8398       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8399     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8400         !ExprTy->isCharType()) {
8401       // 'unichar' is defined as a typedef of unsigned short, but we should
8402       // prefer using the typedef if it is visible.
8403       IntendedTy = S.Context.UnsignedShortTy;
8404 
8405       // While we are here, check if the value is an IntegerLiteral that happens
8406       // to be within the valid range.
8407       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8408         const llvm::APInt &V = IL->getValue();
8409         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8410           return true;
8411       }
8412 
8413       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8414                           Sema::LookupOrdinaryName);
8415       if (S.LookupName(Result, S.getCurScope())) {
8416         NamedDecl *ND = Result.getFoundDecl();
8417         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8418           if (TD->getUnderlyingType() == IntendedTy)
8419             IntendedTy = S.Context.getTypedefType(TD);
8420       }
8421     }
8422   }
8423 
8424   // Special-case some of Darwin's platform-independence types by suggesting
8425   // casts to primitive types that are known to be large enough.
8426   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8427   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8428     QualType CastTy;
8429     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8430     if (!CastTy.isNull()) {
8431       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8432       // (long in ASTContext). Only complain to pedants.
8433       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8434           (AT.isSizeT() || AT.isPtrdiffT()) &&
8435           AT.matchesType(S.Context, CastTy))
8436         Match = ArgType::NoMatchPedantic;
8437       IntendedTy = CastTy;
8438       ShouldNotPrintDirectly = true;
8439     }
8440   }
8441 
8442   // We may be able to offer a FixItHint if it is a supported type.
8443   PrintfSpecifier fixedFS = FS;
8444   bool Success =
8445       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8446 
8447   if (Success) {
8448     // Get the fix string from the fixed format specifier
8449     SmallString<16> buf;
8450     llvm::raw_svector_ostream os(buf);
8451     fixedFS.toString(os);
8452 
8453     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8454 
8455     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8456       unsigned Diag;
8457       switch (Match) {
8458       case ArgType::Match: llvm_unreachable("expected non-matching");
8459       case ArgType::NoMatchPedantic:
8460         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8461         break;
8462       case ArgType::NoMatchTypeConfusion:
8463         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8464         break;
8465       case ArgType::NoMatch:
8466         Diag = diag::warn_format_conversion_argument_type_mismatch;
8467         break;
8468       }
8469 
8470       // In this case, the specifier is wrong and should be changed to match
8471       // the argument.
8472       EmitFormatDiagnostic(S.PDiag(Diag)
8473                                << AT.getRepresentativeTypeName(S.Context)
8474                                << IntendedTy << IsEnum << E->getSourceRange(),
8475                            E->getBeginLoc(),
8476                            /*IsStringLocation*/ false, SpecRange,
8477                            FixItHint::CreateReplacement(SpecRange, os.str()));
8478     } else {
8479       // The canonical type for formatting this value is different from the
8480       // actual type of the expression. (This occurs, for example, with Darwin's
8481       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8482       // should be printed as 'long' for 64-bit compatibility.)
8483       // Rather than emitting a normal format/argument mismatch, we want to
8484       // add a cast to the recommended type (and correct the format string
8485       // if necessary).
8486       SmallString<16> CastBuf;
8487       llvm::raw_svector_ostream CastFix(CastBuf);
8488       CastFix << "(";
8489       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8490       CastFix << ")";
8491 
8492       SmallVector<FixItHint,4> Hints;
8493       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8494         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8495 
8496       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8497         // If there's already a cast present, just replace it.
8498         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8499         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8500 
8501       } else if (!requiresParensToAddCast(E)) {
8502         // If the expression has high enough precedence,
8503         // just write the C-style cast.
8504         Hints.push_back(
8505             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8506       } else {
8507         // Otherwise, add parens around the expression as well as the cast.
8508         CastFix << "(";
8509         Hints.push_back(
8510             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8511 
8512         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8513         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8514       }
8515 
8516       if (ShouldNotPrintDirectly) {
8517         // The expression has a type that should not be printed directly.
8518         // We extract the name from the typedef because we don't want to show
8519         // the underlying type in the diagnostic.
8520         StringRef Name;
8521         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8522           Name = TypedefTy->getDecl()->getName();
8523         else
8524           Name = CastTyName;
8525         unsigned Diag = Match == ArgType::NoMatchPedantic
8526                             ? diag::warn_format_argument_needs_cast_pedantic
8527                             : diag::warn_format_argument_needs_cast;
8528         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8529                                            << E->getSourceRange(),
8530                              E->getBeginLoc(), /*IsStringLocation=*/false,
8531                              SpecRange, Hints);
8532       } else {
8533         // In this case, the expression could be printed using a different
8534         // specifier, but we've decided that the specifier is probably correct
8535         // and we should cast instead. Just use the normal warning message.
8536         EmitFormatDiagnostic(
8537             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8538                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8539                 << E->getSourceRange(),
8540             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8541       }
8542     }
8543   } else {
8544     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8545                                                    SpecifierLen);
8546     // Since the warning for passing non-POD types to variadic functions
8547     // was deferred until now, we emit a warning for non-POD
8548     // arguments here.
8549     switch (S.isValidVarArgType(ExprTy)) {
8550     case Sema::VAK_Valid:
8551     case Sema::VAK_ValidInCXX11: {
8552       unsigned Diag;
8553       switch (Match) {
8554       case ArgType::Match: llvm_unreachable("expected non-matching");
8555       case ArgType::NoMatchPedantic:
8556         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8557         break;
8558       case ArgType::NoMatchTypeConfusion:
8559         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8560         break;
8561       case ArgType::NoMatch:
8562         Diag = diag::warn_format_conversion_argument_type_mismatch;
8563         break;
8564       }
8565 
8566       EmitFormatDiagnostic(
8567           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8568                         << IsEnum << CSR << E->getSourceRange(),
8569           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8570       break;
8571     }
8572     case Sema::VAK_Undefined:
8573     case Sema::VAK_MSVCUndefined:
8574       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8575                                << S.getLangOpts().CPlusPlus11 << ExprTy
8576                                << CallType
8577                                << AT.getRepresentativeTypeName(S.Context) << CSR
8578                                << E->getSourceRange(),
8579                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8580       checkForCStrMembers(AT, E);
8581       break;
8582 
8583     case Sema::VAK_Invalid:
8584       if (ExprTy->isObjCObjectType())
8585         EmitFormatDiagnostic(
8586             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8587                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8588                 << AT.getRepresentativeTypeName(S.Context) << CSR
8589                 << E->getSourceRange(),
8590             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8591       else
8592         // FIXME: If this is an initializer list, suggest removing the braces
8593         // or inserting a cast to the target type.
8594         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8595             << isa<InitListExpr>(E) << ExprTy << CallType
8596             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8597       break;
8598     }
8599 
8600     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8601            "format string specifier index out of range");
8602     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8603   }
8604 
8605   return true;
8606 }
8607 
8608 //===--- CHECK: Scanf format string checking ------------------------------===//
8609 
8610 namespace {
8611 
8612 class CheckScanfHandler : public CheckFormatHandler {
8613 public:
8614   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8615                     const Expr *origFormatExpr, Sema::FormatStringType type,
8616                     unsigned firstDataArg, unsigned numDataArgs,
8617                     const char *beg, bool hasVAListArg,
8618                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8619                     bool inFunctionCall, Sema::VariadicCallType CallType,
8620                     llvm::SmallBitVector &CheckedVarArgs,
8621                     UncoveredArgHandler &UncoveredArg)
8622       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8623                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8624                            inFunctionCall, CallType, CheckedVarArgs,
8625                            UncoveredArg) {}
8626 
8627   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8628                             const char *startSpecifier,
8629                             unsigned specifierLen) override;
8630 
8631   bool HandleInvalidScanfConversionSpecifier(
8632           const analyze_scanf::ScanfSpecifier &FS,
8633           const char *startSpecifier,
8634           unsigned specifierLen) override;
8635 
8636   void HandleIncompleteScanList(const char *start, const char *end) override;
8637 };
8638 
8639 } // namespace
8640 
8641 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8642                                                  const char *end) {
8643   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8644                        getLocationOfByte(end), /*IsStringLocation*/true,
8645                        getSpecifierRange(start, end - start));
8646 }
8647 
8648 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8649                                         const analyze_scanf::ScanfSpecifier &FS,
8650                                         const char *startSpecifier,
8651                                         unsigned specifierLen) {
8652   const analyze_scanf::ScanfConversionSpecifier &CS =
8653     FS.getConversionSpecifier();
8654 
8655   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8656                                           getLocationOfByte(CS.getStart()),
8657                                           startSpecifier, specifierLen,
8658                                           CS.getStart(), CS.getLength());
8659 }
8660 
8661 bool CheckScanfHandler::HandleScanfSpecifier(
8662                                        const analyze_scanf::ScanfSpecifier &FS,
8663                                        const char *startSpecifier,
8664                                        unsigned specifierLen) {
8665   using namespace analyze_scanf;
8666   using namespace analyze_format_string;
8667 
8668   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8669 
8670   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8671   // be used to decide if we are using positional arguments consistently.
8672   if (FS.consumesDataArgument()) {
8673     if (atFirstArg) {
8674       atFirstArg = false;
8675       usesPositionalArgs = FS.usesPositionalArg();
8676     }
8677     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8678       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8679                                         startSpecifier, specifierLen);
8680       return false;
8681     }
8682   }
8683 
8684   // Check if the field with is non-zero.
8685   const OptionalAmount &Amt = FS.getFieldWidth();
8686   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8687     if (Amt.getConstantAmount() == 0) {
8688       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8689                                                    Amt.getConstantLength());
8690       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8691                            getLocationOfByte(Amt.getStart()),
8692                            /*IsStringLocation*/true, R,
8693                            FixItHint::CreateRemoval(R));
8694     }
8695   }
8696 
8697   if (!FS.consumesDataArgument()) {
8698     // FIXME: Technically specifying a precision or field width here
8699     // makes no sense.  Worth issuing a warning at some point.
8700     return true;
8701   }
8702 
8703   // Consume the argument.
8704   unsigned argIndex = FS.getArgIndex();
8705   if (argIndex < NumDataArgs) {
8706       // The check to see if the argIndex is valid will come later.
8707       // We set the bit here because we may exit early from this
8708       // function if we encounter some other error.
8709     CoveredArgs.set(argIndex);
8710   }
8711 
8712   // Check the length modifier is valid with the given conversion specifier.
8713   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8714                                  S.getLangOpts()))
8715     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8716                                 diag::warn_format_nonsensical_length);
8717   else if (!FS.hasStandardLengthModifier())
8718     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8719   else if (!FS.hasStandardLengthConversionCombination())
8720     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8721                                 diag::warn_format_non_standard_conversion_spec);
8722 
8723   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8724     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8725 
8726   // The remaining checks depend on the data arguments.
8727   if (HasVAListArg)
8728     return true;
8729 
8730   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8731     return false;
8732 
8733   // Check that the argument type matches the format specifier.
8734   const Expr *Ex = getDataArg(argIndex);
8735   if (!Ex)
8736     return true;
8737 
8738   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8739 
8740   if (!AT.isValid()) {
8741     return true;
8742   }
8743 
8744   analyze_format_string::ArgType::MatchKind Match =
8745       AT.matchesType(S.Context, Ex->getType());
8746   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8747   if (Match == analyze_format_string::ArgType::Match)
8748     return true;
8749 
8750   ScanfSpecifier fixedFS = FS;
8751   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8752                                  S.getLangOpts(), S.Context);
8753 
8754   unsigned Diag =
8755       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8756                : diag::warn_format_conversion_argument_type_mismatch;
8757 
8758   if (Success) {
8759     // Get the fix string from the fixed format specifier.
8760     SmallString<128> buf;
8761     llvm::raw_svector_ostream os(buf);
8762     fixedFS.toString(os);
8763 
8764     EmitFormatDiagnostic(
8765         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8766                       << Ex->getType() << false << Ex->getSourceRange(),
8767         Ex->getBeginLoc(),
8768         /*IsStringLocation*/ false,
8769         getSpecifierRange(startSpecifier, specifierLen),
8770         FixItHint::CreateReplacement(
8771             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8772   } else {
8773     EmitFormatDiagnostic(S.PDiag(Diag)
8774                              << AT.getRepresentativeTypeName(S.Context)
8775                              << Ex->getType() << false << Ex->getSourceRange(),
8776                          Ex->getBeginLoc(),
8777                          /*IsStringLocation*/ false,
8778                          getSpecifierRange(startSpecifier, specifierLen));
8779   }
8780 
8781   return true;
8782 }
8783 
8784 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8785                               const Expr *OrigFormatExpr,
8786                               ArrayRef<const Expr *> Args,
8787                               bool HasVAListArg, unsigned format_idx,
8788                               unsigned firstDataArg,
8789                               Sema::FormatStringType Type,
8790                               bool inFunctionCall,
8791                               Sema::VariadicCallType CallType,
8792                               llvm::SmallBitVector &CheckedVarArgs,
8793                               UncoveredArgHandler &UncoveredArg,
8794                               bool IgnoreStringsWithoutSpecifiers) {
8795   // CHECK: is the format string a wide literal?
8796   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8797     CheckFormatHandler::EmitFormatDiagnostic(
8798         S, inFunctionCall, Args[format_idx],
8799         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8800         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8801     return;
8802   }
8803 
8804   // Str - The format string.  NOTE: this is NOT null-terminated!
8805   StringRef StrRef = FExpr->getString();
8806   const char *Str = StrRef.data();
8807   // Account for cases where the string literal is truncated in a declaration.
8808   const ConstantArrayType *T =
8809     S.Context.getAsConstantArrayType(FExpr->getType());
8810   assert(T && "String literal not of constant array type!");
8811   size_t TypeSize = T->getSize().getZExtValue();
8812   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8813   const unsigned numDataArgs = Args.size() - firstDataArg;
8814 
8815   if (IgnoreStringsWithoutSpecifiers &&
8816       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8817           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8818     return;
8819 
8820   // Emit a warning if the string literal is truncated and does not contain an
8821   // embedded null character.
8822   if (TypeSize <= StrRef.size() &&
8823       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8824     CheckFormatHandler::EmitFormatDiagnostic(
8825         S, inFunctionCall, Args[format_idx],
8826         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8827         FExpr->getBeginLoc(),
8828         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8829     return;
8830   }
8831 
8832   // CHECK: empty format string?
8833   if (StrLen == 0 && numDataArgs > 0) {
8834     CheckFormatHandler::EmitFormatDiagnostic(
8835         S, inFunctionCall, Args[format_idx],
8836         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8837         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8838     return;
8839   }
8840 
8841   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8842       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8843       Type == Sema::FST_OSTrace) {
8844     CheckPrintfHandler H(
8845         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8846         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8847         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8848         CheckedVarArgs, UncoveredArg);
8849 
8850     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8851                                                   S.getLangOpts(),
8852                                                   S.Context.getTargetInfo(),
8853                                             Type == Sema::FST_FreeBSDKPrintf))
8854       H.DoneProcessing();
8855   } else if (Type == Sema::FST_Scanf) {
8856     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8857                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8858                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8859 
8860     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8861                                                  S.getLangOpts(),
8862                                                  S.Context.getTargetInfo()))
8863       H.DoneProcessing();
8864   } // TODO: handle other formats
8865 }
8866 
8867 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8868   // Str - The format string.  NOTE: this is NOT null-terminated!
8869   StringRef StrRef = FExpr->getString();
8870   const char *Str = StrRef.data();
8871   // Account for cases where the string literal is truncated in a declaration.
8872   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8873   assert(T && "String literal not of constant array type!");
8874   size_t TypeSize = T->getSize().getZExtValue();
8875   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8876   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8877                                                          getLangOpts(),
8878                                                          Context.getTargetInfo());
8879 }
8880 
8881 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8882 
8883 // Returns the related absolute value function that is larger, of 0 if one
8884 // does not exist.
8885 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8886   switch (AbsFunction) {
8887   default:
8888     return 0;
8889 
8890   case Builtin::BI__builtin_abs:
8891     return Builtin::BI__builtin_labs;
8892   case Builtin::BI__builtin_labs:
8893     return Builtin::BI__builtin_llabs;
8894   case Builtin::BI__builtin_llabs:
8895     return 0;
8896 
8897   case Builtin::BI__builtin_fabsf:
8898     return Builtin::BI__builtin_fabs;
8899   case Builtin::BI__builtin_fabs:
8900     return Builtin::BI__builtin_fabsl;
8901   case Builtin::BI__builtin_fabsl:
8902     return 0;
8903 
8904   case Builtin::BI__builtin_cabsf:
8905     return Builtin::BI__builtin_cabs;
8906   case Builtin::BI__builtin_cabs:
8907     return Builtin::BI__builtin_cabsl;
8908   case Builtin::BI__builtin_cabsl:
8909     return 0;
8910 
8911   case Builtin::BIabs:
8912     return Builtin::BIlabs;
8913   case Builtin::BIlabs:
8914     return Builtin::BIllabs;
8915   case Builtin::BIllabs:
8916     return 0;
8917 
8918   case Builtin::BIfabsf:
8919     return Builtin::BIfabs;
8920   case Builtin::BIfabs:
8921     return Builtin::BIfabsl;
8922   case Builtin::BIfabsl:
8923     return 0;
8924 
8925   case Builtin::BIcabsf:
8926    return Builtin::BIcabs;
8927   case Builtin::BIcabs:
8928     return Builtin::BIcabsl;
8929   case Builtin::BIcabsl:
8930     return 0;
8931   }
8932 }
8933 
8934 // Returns the argument type of the absolute value function.
8935 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8936                                              unsigned AbsType) {
8937   if (AbsType == 0)
8938     return QualType();
8939 
8940   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8941   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8942   if (Error != ASTContext::GE_None)
8943     return QualType();
8944 
8945   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8946   if (!FT)
8947     return QualType();
8948 
8949   if (FT->getNumParams() != 1)
8950     return QualType();
8951 
8952   return FT->getParamType(0);
8953 }
8954 
8955 // Returns the best absolute value function, or zero, based on type and
8956 // current absolute value function.
8957 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8958                                    unsigned AbsFunctionKind) {
8959   unsigned BestKind = 0;
8960   uint64_t ArgSize = Context.getTypeSize(ArgType);
8961   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8962        Kind = getLargerAbsoluteValueFunction(Kind)) {
8963     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8964     if (Context.getTypeSize(ParamType) >= ArgSize) {
8965       if (BestKind == 0)
8966         BestKind = Kind;
8967       else if (Context.hasSameType(ParamType, ArgType)) {
8968         BestKind = Kind;
8969         break;
8970       }
8971     }
8972   }
8973   return BestKind;
8974 }
8975 
8976 enum AbsoluteValueKind {
8977   AVK_Integer,
8978   AVK_Floating,
8979   AVK_Complex
8980 };
8981 
8982 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8983   if (T->isIntegralOrEnumerationType())
8984     return AVK_Integer;
8985   if (T->isRealFloatingType())
8986     return AVK_Floating;
8987   if (T->isAnyComplexType())
8988     return AVK_Complex;
8989 
8990   llvm_unreachable("Type not integer, floating, or complex");
8991 }
8992 
8993 // Changes the absolute value function to a different type.  Preserves whether
8994 // the function is a builtin.
8995 static unsigned changeAbsFunction(unsigned AbsKind,
8996                                   AbsoluteValueKind ValueKind) {
8997   switch (ValueKind) {
8998   case AVK_Integer:
8999     switch (AbsKind) {
9000     default:
9001       return 0;
9002     case Builtin::BI__builtin_fabsf:
9003     case Builtin::BI__builtin_fabs:
9004     case Builtin::BI__builtin_fabsl:
9005     case Builtin::BI__builtin_cabsf:
9006     case Builtin::BI__builtin_cabs:
9007     case Builtin::BI__builtin_cabsl:
9008       return Builtin::BI__builtin_abs;
9009     case Builtin::BIfabsf:
9010     case Builtin::BIfabs:
9011     case Builtin::BIfabsl:
9012     case Builtin::BIcabsf:
9013     case Builtin::BIcabs:
9014     case Builtin::BIcabsl:
9015       return Builtin::BIabs;
9016     }
9017   case AVK_Floating:
9018     switch (AbsKind) {
9019     default:
9020       return 0;
9021     case Builtin::BI__builtin_abs:
9022     case Builtin::BI__builtin_labs:
9023     case Builtin::BI__builtin_llabs:
9024     case Builtin::BI__builtin_cabsf:
9025     case Builtin::BI__builtin_cabs:
9026     case Builtin::BI__builtin_cabsl:
9027       return Builtin::BI__builtin_fabsf;
9028     case Builtin::BIabs:
9029     case Builtin::BIlabs:
9030     case Builtin::BIllabs:
9031     case Builtin::BIcabsf:
9032     case Builtin::BIcabs:
9033     case Builtin::BIcabsl:
9034       return Builtin::BIfabsf;
9035     }
9036   case AVK_Complex:
9037     switch (AbsKind) {
9038     default:
9039       return 0;
9040     case Builtin::BI__builtin_abs:
9041     case Builtin::BI__builtin_labs:
9042     case Builtin::BI__builtin_llabs:
9043     case Builtin::BI__builtin_fabsf:
9044     case Builtin::BI__builtin_fabs:
9045     case Builtin::BI__builtin_fabsl:
9046       return Builtin::BI__builtin_cabsf;
9047     case Builtin::BIabs:
9048     case Builtin::BIlabs:
9049     case Builtin::BIllabs:
9050     case Builtin::BIfabsf:
9051     case Builtin::BIfabs:
9052     case Builtin::BIfabsl:
9053       return Builtin::BIcabsf;
9054     }
9055   }
9056   llvm_unreachable("Unable to convert function");
9057 }
9058 
9059 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9060   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9061   if (!FnInfo)
9062     return 0;
9063 
9064   switch (FDecl->getBuiltinID()) {
9065   default:
9066     return 0;
9067   case Builtin::BI__builtin_abs:
9068   case Builtin::BI__builtin_fabs:
9069   case Builtin::BI__builtin_fabsf:
9070   case Builtin::BI__builtin_fabsl:
9071   case Builtin::BI__builtin_labs:
9072   case Builtin::BI__builtin_llabs:
9073   case Builtin::BI__builtin_cabs:
9074   case Builtin::BI__builtin_cabsf:
9075   case Builtin::BI__builtin_cabsl:
9076   case Builtin::BIabs:
9077   case Builtin::BIlabs:
9078   case Builtin::BIllabs:
9079   case Builtin::BIfabs:
9080   case Builtin::BIfabsf:
9081   case Builtin::BIfabsl:
9082   case Builtin::BIcabs:
9083   case Builtin::BIcabsf:
9084   case Builtin::BIcabsl:
9085     return FDecl->getBuiltinID();
9086   }
9087   llvm_unreachable("Unknown Builtin type");
9088 }
9089 
9090 // If the replacement is valid, emit a note with replacement function.
9091 // Additionally, suggest including the proper header if not already included.
9092 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9093                             unsigned AbsKind, QualType ArgType) {
9094   bool EmitHeaderHint = true;
9095   const char *HeaderName = nullptr;
9096   const char *FunctionName = nullptr;
9097   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9098     FunctionName = "std::abs";
9099     if (ArgType->isIntegralOrEnumerationType()) {
9100       HeaderName = "cstdlib";
9101     } else if (ArgType->isRealFloatingType()) {
9102       HeaderName = "cmath";
9103     } else {
9104       llvm_unreachable("Invalid Type");
9105     }
9106 
9107     // Lookup all std::abs
9108     if (NamespaceDecl *Std = S.getStdNamespace()) {
9109       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9110       R.suppressDiagnostics();
9111       S.LookupQualifiedName(R, Std);
9112 
9113       for (const auto *I : R) {
9114         const FunctionDecl *FDecl = nullptr;
9115         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9116           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9117         } else {
9118           FDecl = dyn_cast<FunctionDecl>(I);
9119         }
9120         if (!FDecl)
9121           continue;
9122 
9123         // Found std::abs(), check that they are the right ones.
9124         if (FDecl->getNumParams() != 1)
9125           continue;
9126 
9127         // Check that the parameter type can handle the argument.
9128         QualType ParamType = FDecl->getParamDecl(0)->getType();
9129         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9130             S.Context.getTypeSize(ArgType) <=
9131                 S.Context.getTypeSize(ParamType)) {
9132           // Found a function, don't need the header hint.
9133           EmitHeaderHint = false;
9134           break;
9135         }
9136       }
9137     }
9138   } else {
9139     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9140     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9141 
9142     if (HeaderName) {
9143       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9144       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9145       R.suppressDiagnostics();
9146       S.LookupName(R, S.getCurScope());
9147 
9148       if (R.isSingleResult()) {
9149         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9150         if (FD && FD->getBuiltinID() == AbsKind) {
9151           EmitHeaderHint = false;
9152         } else {
9153           return;
9154         }
9155       } else if (!R.empty()) {
9156         return;
9157       }
9158     }
9159   }
9160 
9161   S.Diag(Loc, diag::note_replace_abs_function)
9162       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9163 
9164   if (!HeaderName)
9165     return;
9166 
9167   if (!EmitHeaderHint)
9168     return;
9169 
9170   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9171                                                     << FunctionName;
9172 }
9173 
9174 template <std::size_t StrLen>
9175 static bool IsStdFunction(const FunctionDecl *FDecl,
9176                           const char (&Str)[StrLen]) {
9177   if (!FDecl)
9178     return false;
9179   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9180     return false;
9181   if (!FDecl->isInStdNamespace())
9182     return false;
9183 
9184   return true;
9185 }
9186 
9187 // Warn when using the wrong abs() function.
9188 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9189                                       const FunctionDecl *FDecl) {
9190   if (Call->getNumArgs() != 1)
9191     return;
9192 
9193   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9194   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9195   if (AbsKind == 0 && !IsStdAbs)
9196     return;
9197 
9198   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9199   QualType ParamType = Call->getArg(0)->getType();
9200 
9201   // Unsigned types cannot be negative.  Suggest removing the absolute value
9202   // function call.
9203   if (ArgType->isUnsignedIntegerType()) {
9204     const char *FunctionName =
9205         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9206     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9207     Diag(Call->getExprLoc(), diag::note_remove_abs)
9208         << FunctionName
9209         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9210     return;
9211   }
9212 
9213   // Taking the absolute value of a pointer is very suspicious, they probably
9214   // wanted to index into an array, dereference a pointer, call a function, etc.
9215   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9216     unsigned DiagType = 0;
9217     if (ArgType->isFunctionType())
9218       DiagType = 1;
9219     else if (ArgType->isArrayType())
9220       DiagType = 2;
9221 
9222     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9223     return;
9224   }
9225 
9226   // std::abs has overloads which prevent most of the absolute value problems
9227   // from occurring.
9228   if (IsStdAbs)
9229     return;
9230 
9231   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9232   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9233 
9234   // The argument and parameter are the same kind.  Check if they are the right
9235   // size.
9236   if (ArgValueKind == ParamValueKind) {
9237     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9238       return;
9239 
9240     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9241     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9242         << FDecl << ArgType << ParamType;
9243 
9244     if (NewAbsKind == 0)
9245       return;
9246 
9247     emitReplacement(*this, Call->getExprLoc(),
9248                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9249     return;
9250   }
9251 
9252   // ArgValueKind != ParamValueKind
9253   // The wrong type of absolute value function was used.  Attempt to find the
9254   // proper one.
9255   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9256   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9257   if (NewAbsKind == 0)
9258     return;
9259 
9260   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9261       << FDecl << ParamValueKind << ArgValueKind;
9262 
9263   emitReplacement(*this, Call->getExprLoc(),
9264                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9265 }
9266 
9267 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9268 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9269                                 const FunctionDecl *FDecl) {
9270   if (!Call || !FDecl) return;
9271 
9272   // Ignore template specializations and macros.
9273   if (inTemplateInstantiation()) return;
9274   if (Call->getExprLoc().isMacroID()) return;
9275 
9276   // Only care about the one template argument, two function parameter std::max
9277   if (Call->getNumArgs() != 2) return;
9278   if (!IsStdFunction(FDecl, "max")) return;
9279   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9280   if (!ArgList) return;
9281   if (ArgList->size() != 1) return;
9282 
9283   // Check that template type argument is unsigned integer.
9284   const auto& TA = ArgList->get(0);
9285   if (TA.getKind() != TemplateArgument::Type) return;
9286   QualType ArgType = TA.getAsType();
9287   if (!ArgType->isUnsignedIntegerType()) return;
9288 
9289   // See if either argument is a literal zero.
9290   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9291     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9292     if (!MTE) return false;
9293     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9294     if (!Num) return false;
9295     if (Num->getValue() != 0) return false;
9296     return true;
9297   };
9298 
9299   const Expr *FirstArg = Call->getArg(0);
9300   const Expr *SecondArg = Call->getArg(1);
9301   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9302   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9303 
9304   // Only warn when exactly one argument is zero.
9305   if (IsFirstArgZero == IsSecondArgZero) return;
9306 
9307   SourceRange FirstRange = FirstArg->getSourceRange();
9308   SourceRange SecondRange = SecondArg->getSourceRange();
9309 
9310   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9311 
9312   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9313       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9314 
9315   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9316   SourceRange RemovalRange;
9317   if (IsFirstArgZero) {
9318     RemovalRange = SourceRange(FirstRange.getBegin(),
9319                                SecondRange.getBegin().getLocWithOffset(-1));
9320   } else {
9321     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9322                                SecondRange.getEnd());
9323   }
9324 
9325   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9326         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9327         << FixItHint::CreateRemoval(RemovalRange);
9328 }
9329 
9330 //===--- CHECK: Standard memory functions ---------------------------------===//
9331 
9332 /// Takes the expression passed to the size_t parameter of functions
9333 /// such as memcmp, strncat, etc and warns if it's a comparison.
9334 ///
9335 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9336 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9337                                            IdentifierInfo *FnName,
9338                                            SourceLocation FnLoc,
9339                                            SourceLocation RParenLoc) {
9340   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9341   if (!Size)
9342     return false;
9343 
9344   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9345   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9346     return false;
9347 
9348   SourceRange SizeRange = Size->getSourceRange();
9349   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9350       << SizeRange << FnName;
9351   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9352       << FnName
9353       << FixItHint::CreateInsertion(
9354              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9355       << FixItHint::CreateRemoval(RParenLoc);
9356   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9357       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9358       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9359                                     ")");
9360 
9361   return true;
9362 }
9363 
9364 /// Determine whether the given type is or contains a dynamic class type
9365 /// (e.g., whether it has a vtable).
9366 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9367                                                      bool &IsContained) {
9368   // Look through array types while ignoring qualifiers.
9369   const Type *Ty = T->getBaseElementTypeUnsafe();
9370   IsContained = false;
9371 
9372   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9373   RD = RD ? RD->getDefinition() : nullptr;
9374   if (!RD || RD->isInvalidDecl())
9375     return nullptr;
9376 
9377   if (RD->isDynamicClass())
9378     return RD;
9379 
9380   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9381   // It's impossible for a class to transitively contain itself by value, so
9382   // infinite recursion is impossible.
9383   for (auto *FD : RD->fields()) {
9384     bool SubContained;
9385     if (const CXXRecordDecl *ContainedRD =
9386             getContainedDynamicClass(FD->getType(), SubContained)) {
9387       IsContained = true;
9388       return ContainedRD;
9389     }
9390   }
9391 
9392   return nullptr;
9393 }
9394 
9395 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9396   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9397     if (Unary->getKind() == UETT_SizeOf)
9398       return Unary;
9399   return nullptr;
9400 }
9401 
9402 /// If E is a sizeof expression, returns its argument expression,
9403 /// otherwise returns NULL.
9404 static const Expr *getSizeOfExprArg(const Expr *E) {
9405   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9406     if (!SizeOf->isArgumentType())
9407       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9408   return nullptr;
9409 }
9410 
9411 /// If E is a sizeof expression, returns its argument type.
9412 static QualType getSizeOfArgType(const Expr *E) {
9413   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9414     return SizeOf->getTypeOfArgument();
9415   return QualType();
9416 }
9417 
9418 namespace {
9419 
9420 struct SearchNonTrivialToInitializeField
9421     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9422   using Super =
9423       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9424 
9425   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9426 
9427   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9428                      SourceLocation SL) {
9429     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9430       asDerived().visitArray(PDIK, AT, SL);
9431       return;
9432     }
9433 
9434     Super::visitWithKind(PDIK, FT, SL);
9435   }
9436 
9437   void visitARCStrong(QualType FT, SourceLocation SL) {
9438     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9439   }
9440   void visitARCWeak(QualType FT, SourceLocation SL) {
9441     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9442   }
9443   void visitStruct(QualType FT, SourceLocation SL) {
9444     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9445       visit(FD->getType(), FD->getLocation());
9446   }
9447   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9448                   const ArrayType *AT, SourceLocation SL) {
9449     visit(getContext().getBaseElementType(AT), SL);
9450   }
9451   void visitTrivial(QualType FT, SourceLocation SL) {}
9452 
9453   static void diag(QualType RT, const Expr *E, Sema &S) {
9454     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9455   }
9456 
9457   ASTContext &getContext() { return S.getASTContext(); }
9458 
9459   const Expr *E;
9460   Sema &S;
9461 };
9462 
9463 struct SearchNonTrivialToCopyField
9464     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9465   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9466 
9467   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9468 
9469   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9470                      SourceLocation SL) {
9471     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9472       asDerived().visitArray(PCK, AT, SL);
9473       return;
9474     }
9475 
9476     Super::visitWithKind(PCK, FT, SL);
9477   }
9478 
9479   void visitARCStrong(QualType FT, SourceLocation SL) {
9480     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9481   }
9482   void visitARCWeak(QualType FT, SourceLocation SL) {
9483     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9484   }
9485   void visitStruct(QualType FT, SourceLocation SL) {
9486     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9487       visit(FD->getType(), FD->getLocation());
9488   }
9489   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9490                   SourceLocation SL) {
9491     visit(getContext().getBaseElementType(AT), SL);
9492   }
9493   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9494                 SourceLocation SL) {}
9495   void visitTrivial(QualType FT, SourceLocation SL) {}
9496   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9497 
9498   static void diag(QualType RT, const Expr *E, Sema &S) {
9499     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9500   }
9501 
9502   ASTContext &getContext() { return S.getASTContext(); }
9503 
9504   const Expr *E;
9505   Sema &S;
9506 };
9507 
9508 }
9509 
9510 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9511 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9512   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9513 
9514   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9515     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9516       return false;
9517 
9518     return doesExprLikelyComputeSize(BO->getLHS()) ||
9519            doesExprLikelyComputeSize(BO->getRHS());
9520   }
9521 
9522   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9523 }
9524 
9525 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9526 ///
9527 /// \code
9528 ///   #define MACRO 0
9529 ///   foo(MACRO);
9530 ///   foo(0);
9531 /// \endcode
9532 ///
9533 /// This should return true for the first call to foo, but not for the second
9534 /// (regardless of whether foo is a macro or function).
9535 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9536                                         SourceLocation CallLoc,
9537                                         SourceLocation ArgLoc) {
9538   if (!CallLoc.isMacroID())
9539     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9540 
9541   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9542          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9543 }
9544 
9545 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9546 /// last two arguments transposed.
9547 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9548   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9549     return;
9550 
9551   const Expr *SizeArg =
9552     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9553 
9554   auto isLiteralZero = [](const Expr *E) {
9555     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9556   };
9557 
9558   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9559   SourceLocation CallLoc = Call->getRParenLoc();
9560   SourceManager &SM = S.getSourceManager();
9561   if (isLiteralZero(SizeArg) &&
9562       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9563 
9564     SourceLocation DiagLoc = SizeArg->getExprLoc();
9565 
9566     // Some platforms #define bzero to __builtin_memset. See if this is the
9567     // case, and if so, emit a better diagnostic.
9568     if (BId == Builtin::BIbzero ||
9569         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9570                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9571       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9572       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9573     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9574       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9575       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9576     }
9577     return;
9578   }
9579 
9580   // If the second argument to a memset is a sizeof expression and the third
9581   // isn't, this is also likely an error. This should catch
9582   // 'memset(buf, sizeof(buf), 0xff)'.
9583   if (BId == Builtin::BImemset &&
9584       doesExprLikelyComputeSize(Call->getArg(1)) &&
9585       !doesExprLikelyComputeSize(Call->getArg(2))) {
9586     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9587     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9588     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9589     return;
9590   }
9591 }
9592 
9593 /// Check for dangerous or invalid arguments to memset().
9594 ///
9595 /// This issues warnings on known problematic, dangerous or unspecified
9596 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9597 /// function calls.
9598 ///
9599 /// \param Call The call expression to diagnose.
9600 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9601                                    unsigned BId,
9602                                    IdentifierInfo *FnName) {
9603   assert(BId != 0);
9604 
9605   // It is possible to have a non-standard definition of memset.  Validate
9606   // we have enough arguments, and if not, abort further checking.
9607   unsigned ExpectedNumArgs =
9608       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9609   if (Call->getNumArgs() < ExpectedNumArgs)
9610     return;
9611 
9612   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9613                       BId == Builtin::BIstrndup ? 1 : 2);
9614   unsigned LenArg =
9615       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9616   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9617 
9618   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9619                                      Call->getBeginLoc(), Call->getRParenLoc()))
9620     return;
9621 
9622   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9623   CheckMemaccessSize(*this, BId, Call);
9624 
9625   // We have special checking when the length is a sizeof expression.
9626   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9627   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9628   llvm::FoldingSetNodeID SizeOfArgID;
9629 
9630   // Although widely used, 'bzero' is not a standard function. Be more strict
9631   // with the argument types before allowing diagnostics and only allow the
9632   // form bzero(ptr, sizeof(...)).
9633   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9634   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9635     return;
9636 
9637   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9638     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9639     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9640 
9641     QualType DestTy = Dest->getType();
9642     QualType PointeeTy;
9643     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9644       PointeeTy = DestPtrTy->getPointeeType();
9645 
9646       // Never warn about void type pointers. This can be used to suppress
9647       // false positives.
9648       if (PointeeTy->isVoidType())
9649         continue;
9650 
9651       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9652       // actually comparing the expressions for equality. Because computing the
9653       // expression IDs can be expensive, we only do this if the diagnostic is
9654       // enabled.
9655       if (SizeOfArg &&
9656           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9657                            SizeOfArg->getExprLoc())) {
9658         // We only compute IDs for expressions if the warning is enabled, and
9659         // cache the sizeof arg's ID.
9660         if (SizeOfArgID == llvm::FoldingSetNodeID())
9661           SizeOfArg->Profile(SizeOfArgID, Context, true);
9662         llvm::FoldingSetNodeID DestID;
9663         Dest->Profile(DestID, Context, true);
9664         if (DestID == SizeOfArgID) {
9665           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9666           //       over sizeof(src) as well.
9667           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9668           StringRef ReadableName = FnName->getName();
9669 
9670           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9671             if (UnaryOp->getOpcode() == UO_AddrOf)
9672               ActionIdx = 1; // If its an address-of operator, just remove it.
9673           if (!PointeeTy->isIncompleteType() &&
9674               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9675             ActionIdx = 2; // If the pointee's size is sizeof(char),
9676                            // suggest an explicit length.
9677 
9678           // If the function is defined as a builtin macro, do not show macro
9679           // expansion.
9680           SourceLocation SL = SizeOfArg->getExprLoc();
9681           SourceRange DSR = Dest->getSourceRange();
9682           SourceRange SSR = SizeOfArg->getSourceRange();
9683           SourceManager &SM = getSourceManager();
9684 
9685           if (SM.isMacroArgExpansion(SL)) {
9686             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9687             SL = SM.getSpellingLoc(SL);
9688             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9689                              SM.getSpellingLoc(DSR.getEnd()));
9690             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9691                              SM.getSpellingLoc(SSR.getEnd()));
9692           }
9693 
9694           DiagRuntimeBehavior(SL, SizeOfArg,
9695                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9696                                 << ReadableName
9697                                 << PointeeTy
9698                                 << DestTy
9699                                 << DSR
9700                                 << SSR);
9701           DiagRuntimeBehavior(SL, SizeOfArg,
9702                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9703                                 << ActionIdx
9704                                 << SSR);
9705 
9706           break;
9707         }
9708       }
9709 
9710       // Also check for cases where the sizeof argument is the exact same
9711       // type as the memory argument, and where it points to a user-defined
9712       // record type.
9713       if (SizeOfArgTy != QualType()) {
9714         if (PointeeTy->isRecordType() &&
9715             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9716           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9717                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9718                                 << FnName << SizeOfArgTy << ArgIdx
9719                                 << PointeeTy << Dest->getSourceRange()
9720                                 << LenExpr->getSourceRange());
9721           break;
9722         }
9723       }
9724     } else if (DestTy->isArrayType()) {
9725       PointeeTy = DestTy;
9726     }
9727 
9728     if (PointeeTy == QualType())
9729       continue;
9730 
9731     // Always complain about dynamic classes.
9732     bool IsContained;
9733     if (const CXXRecordDecl *ContainedRD =
9734             getContainedDynamicClass(PointeeTy, IsContained)) {
9735 
9736       unsigned OperationType = 0;
9737       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9738       // "overwritten" if we're warning about the destination for any call
9739       // but memcmp; otherwise a verb appropriate to the call.
9740       if (ArgIdx != 0 || IsCmp) {
9741         if (BId == Builtin::BImemcpy)
9742           OperationType = 1;
9743         else if(BId == Builtin::BImemmove)
9744           OperationType = 2;
9745         else if (IsCmp)
9746           OperationType = 3;
9747       }
9748 
9749       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9750                           PDiag(diag::warn_dyn_class_memaccess)
9751                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9752                               << IsContained << ContainedRD << OperationType
9753                               << Call->getCallee()->getSourceRange());
9754     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9755              BId != Builtin::BImemset)
9756       DiagRuntimeBehavior(
9757         Dest->getExprLoc(), Dest,
9758         PDiag(diag::warn_arc_object_memaccess)
9759           << ArgIdx << FnName << PointeeTy
9760           << Call->getCallee()->getSourceRange());
9761     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9762       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9763           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9764         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9765                             PDiag(diag::warn_cstruct_memaccess)
9766                                 << ArgIdx << FnName << PointeeTy << 0);
9767         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9768       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9769                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9770         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9771                             PDiag(diag::warn_cstruct_memaccess)
9772                                 << ArgIdx << FnName << PointeeTy << 1);
9773         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9774       } else {
9775         continue;
9776       }
9777     } else
9778       continue;
9779 
9780     DiagRuntimeBehavior(
9781       Dest->getExprLoc(), Dest,
9782       PDiag(diag::note_bad_memaccess_silence)
9783         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9784     break;
9785   }
9786 }
9787 
9788 // A little helper routine: ignore addition and subtraction of integer literals.
9789 // This intentionally does not ignore all integer constant expressions because
9790 // we don't want to remove sizeof().
9791 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9792   Ex = Ex->IgnoreParenCasts();
9793 
9794   while (true) {
9795     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9796     if (!BO || !BO->isAdditiveOp())
9797       break;
9798 
9799     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9800     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9801 
9802     if (isa<IntegerLiteral>(RHS))
9803       Ex = LHS;
9804     else if (isa<IntegerLiteral>(LHS))
9805       Ex = RHS;
9806     else
9807       break;
9808   }
9809 
9810   return Ex;
9811 }
9812 
9813 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9814                                                       ASTContext &Context) {
9815   // Only handle constant-sized or VLAs, but not flexible members.
9816   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9817     // Only issue the FIXIT for arrays of size > 1.
9818     if (CAT->getSize().getSExtValue() <= 1)
9819       return false;
9820   } else if (!Ty->isVariableArrayType()) {
9821     return false;
9822   }
9823   return true;
9824 }
9825 
9826 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9827 // be the size of the source, instead of the destination.
9828 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9829                                     IdentifierInfo *FnName) {
9830 
9831   // Don't crash if the user has the wrong number of arguments
9832   unsigned NumArgs = Call->getNumArgs();
9833   if ((NumArgs != 3) && (NumArgs != 4))
9834     return;
9835 
9836   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9837   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9838   const Expr *CompareWithSrc = nullptr;
9839 
9840   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9841                                      Call->getBeginLoc(), Call->getRParenLoc()))
9842     return;
9843 
9844   // Look for 'strlcpy(dst, x, sizeof(x))'
9845   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9846     CompareWithSrc = Ex;
9847   else {
9848     // Look for 'strlcpy(dst, x, strlen(x))'
9849     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9850       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9851           SizeCall->getNumArgs() == 1)
9852         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9853     }
9854   }
9855 
9856   if (!CompareWithSrc)
9857     return;
9858 
9859   // Determine if the argument to sizeof/strlen is equal to the source
9860   // argument.  In principle there's all kinds of things you could do
9861   // here, for instance creating an == expression and evaluating it with
9862   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9863   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9864   if (!SrcArgDRE)
9865     return;
9866 
9867   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9868   if (!CompareWithSrcDRE ||
9869       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9870     return;
9871 
9872   const Expr *OriginalSizeArg = Call->getArg(2);
9873   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9874       << OriginalSizeArg->getSourceRange() << FnName;
9875 
9876   // Output a FIXIT hint if the destination is an array (rather than a
9877   // pointer to an array).  This could be enhanced to handle some
9878   // pointers if we know the actual size, like if DstArg is 'array+2'
9879   // we could say 'sizeof(array)-2'.
9880   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9881   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9882     return;
9883 
9884   SmallString<128> sizeString;
9885   llvm::raw_svector_ostream OS(sizeString);
9886   OS << "sizeof(";
9887   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9888   OS << ")";
9889 
9890   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9891       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9892                                       OS.str());
9893 }
9894 
9895 /// Check if two expressions refer to the same declaration.
9896 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9897   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9898     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9899       return D1->getDecl() == D2->getDecl();
9900   return false;
9901 }
9902 
9903 static const Expr *getStrlenExprArg(const Expr *E) {
9904   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9905     const FunctionDecl *FD = CE->getDirectCallee();
9906     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9907       return nullptr;
9908     return CE->getArg(0)->IgnoreParenCasts();
9909   }
9910   return nullptr;
9911 }
9912 
9913 // Warn on anti-patterns as the 'size' argument to strncat.
9914 // The correct size argument should look like following:
9915 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9916 void Sema::CheckStrncatArguments(const CallExpr *CE,
9917                                  IdentifierInfo *FnName) {
9918   // Don't crash if the user has the wrong number of arguments.
9919   if (CE->getNumArgs() < 3)
9920     return;
9921   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9922   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9923   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9924 
9925   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9926                                      CE->getRParenLoc()))
9927     return;
9928 
9929   // Identify common expressions, which are wrongly used as the size argument
9930   // to strncat and may lead to buffer overflows.
9931   unsigned PatternType = 0;
9932   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9933     // - sizeof(dst)
9934     if (referToTheSameDecl(SizeOfArg, DstArg))
9935       PatternType = 1;
9936     // - sizeof(src)
9937     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9938       PatternType = 2;
9939   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9940     if (BE->getOpcode() == BO_Sub) {
9941       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9942       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9943       // - sizeof(dst) - strlen(dst)
9944       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9945           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9946         PatternType = 1;
9947       // - sizeof(src) - (anything)
9948       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9949         PatternType = 2;
9950     }
9951   }
9952 
9953   if (PatternType == 0)
9954     return;
9955 
9956   // Generate the diagnostic.
9957   SourceLocation SL = LenArg->getBeginLoc();
9958   SourceRange SR = LenArg->getSourceRange();
9959   SourceManager &SM = getSourceManager();
9960 
9961   // If the function is defined as a builtin macro, do not show macro expansion.
9962   if (SM.isMacroArgExpansion(SL)) {
9963     SL = SM.getSpellingLoc(SL);
9964     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9965                      SM.getSpellingLoc(SR.getEnd()));
9966   }
9967 
9968   // Check if the destination is an array (rather than a pointer to an array).
9969   QualType DstTy = DstArg->getType();
9970   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9971                                                                     Context);
9972   if (!isKnownSizeArray) {
9973     if (PatternType == 1)
9974       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9975     else
9976       Diag(SL, diag::warn_strncat_src_size) << SR;
9977     return;
9978   }
9979 
9980   if (PatternType == 1)
9981     Diag(SL, diag::warn_strncat_large_size) << SR;
9982   else
9983     Diag(SL, diag::warn_strncat_src_size) << SR;
9984 
9985   SmallString<128> sizeString;
9986   llvm::raw_svector_ostream OS(sizeString);
9987   OS << "sizeof(";
9988   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9989   OS << ") - ";
9990   OS << "strlen(";
9991   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9992   OS << ") - 1";
9993 
9994   Diag(SL, diag::note_strncat_wrong_size)
9995     << FixItHint::CreateReplacement(SR, OS.str());
9996 }
9997 
9998 void
9999 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10000                          SourceLocation ReturnLoc,
10001                          bool isObjCMethod,
10002                          const AttrVec *Attrs,
10003                          const FunctionDecl *FD) {
10004   // Check if the return value is null but should not be.
10005   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10006        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10007       CheckNonNullExpr(*this, RetValExp))
10008     Diag(ReturnLoc, diag::warn_null_ret)
10009       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10010 
10011   // C++11 [basic.stc.dynamic.allocation]p4:
10012   //   If an allocation function declared with a non-throwing
10013   //   exception-specification fails to allocate storage, it shall return
10014   //   a null pointer. Any other allocation function that fails to allocate
10015   //   storage shall indicate failure only by throwing an exception [...]
10016   if (FD) {
10017     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10018     if (Op == OO_New || Op == OO_Array_New) {
10019       const FunctionProtoType *Proto
10020         = FD->getType()->castAs<FunctionProtoType>();
10021       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10022           CheckNonNullExpr(*this, RetValExp))
10023         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10024           << FD << getLangOpts().CPlusPlus11;
10025     }
10026   }
10027 }
10028 
10029 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10030 
10031 /// Check for comparisons of floating point operands using != and ==.
10032 /// Issue a warning if these are no self-comparisons, as they are not likely
10033 /// to do what the programmer intended.
10034 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10035   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10036   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10037 
10038   // Special case: check for x == x (which is OK).
10039   // Do not emit warnings for such cases.
10040   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10041     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10042       if (DRL->getDecl() == DRR->getDecl())
10043         return;
10044 
10045   // Special case: check for comparisons against literals that can be exactly
10046   //  represented by APFloat.  In such cases, do not emit a warning.  This
10047   //  is a heuristic: often comparison against such literals are used to
10048   //  detect if a value in a variable has not changed.  This clearly can
10049   //  lead to false negatives.
10050   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10051     if (FLL->isExact())
10052       return;
10053   } else
10054     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10055       if (FLR->isExact())
10056         return;
10057 
10058   // Check for comparisons with builtin types.
10059   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10060     if (CL->getBuiltinCallee())
10061       return;
10062 
10063   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10064     if (CR->getBuiltinCallee())
10065       return;
10066 
10067   // Emit the diagnostic.
10068   Diag(Loc, diag::warn_floatingpoint_eq)
10069     << LHS->getSourceRange() << RHS->getSourceRange();
10070 }
10071 
10072 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10073 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10074 
10075 namespace {
10076 
10077 /// Structure recording the 'active' range of an integer-valued
10078 /// expression.
10079 struct IntRange {
10080   /// The number of bits active in the int.
10081   unsigned Width;
10082 
10083   /// True if the int is known not to have negative values.
10084   bool NonNegative;
10085 
10086   IntRange(unsigned Width, bool NonNegative)
10087       : Width(Width), NonNegative(NonNegative) {}
10088 
10089   /// Returns the range of the bool type.
10090   static IntRange forBoolType() {
10091     return IntRange(1, true);
10092   }
10093 
10094   /// Returns the range of an opaque value of the given integral type.
10095   static IntRange forValueOfType(ASTContext &C, QualType T) {
10096     return forValueOfCanonicalType(C,
10097                           T->getCanonicalTypeInternal().getTypePtr());
10098   }
10099 
10100   /// Returns the range of an opaque value of a canonical integral type.
10101   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10102     assert(T->isCanonicalUnqualified());
10103 
10104     if (const VectorType *VT = dyn_cast<VectorType>(T))
10105       T = VT->getElementType().getTypePtr();
10106     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10107       T = CT->getElementType().getTypePtr();
10108     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10109       T = AT->getValueType().getTypePtr();
10110 
10111     if (!C.getLangOpts().CPlusPlus) {
10112       // For enum types in C code, use the underlying datatype.
10113       if (const EnumType *ET = dyn_cast<EnumType>(T))
10114         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10115     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10116       // For enum types in C++, use the known bit width of the enumerators.
10117       EnumDecl *Enum = ET->getDecl();
10118       // In C++11, enums can have a fixed underlying type. Use this type to
10119       // compute the range.
10120       if (Enum->isFixed()) {
10121         return IntRange(C.getIntWidth(QualType(T, 0)),
10122                         !ET->isSignedIntegerOrEnumerationType());
10123       }
10124 
10125       unsigned NumPositive = Enum->getNumPositiveBits();
10126       unsigned NumNegative = Enum->getNumNegativeBits();
10127 
10128       if (NumNegative == 0)
10129         return IntRange(NumPositive, true/*NonNegative*/);
10130       else
10131         return IntRange(std::max(NumPositive + 1, NumNegative),
10132                         false/*NonNegative*/);
10133     }
10134 
10135     const BuiltinType *BT = cast<BuiltinType>(T);
10136     assert(BT->isInteger());
10137 
10138     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10139   }
10140 
10141   /// Returns the "target" range of a canonical integral type, i.e.
10142   /// the range of values expressible in the type.
10143   ///
10144   /// This matches forValueOfCanonicalType except that enums have the
10145   /// full range of their type, not the range of their enumerators.
10146   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10147     assert(T->isCanonicalUnqualified());
10148 
10149     if (const VectorType *VT = dyn_cast<VectorType>(T))
10150       T = VT->getElementType().getTypePtr();
10151     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10152       T = CT->getElementType().getTypePtr();
10153     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10154       T = AT->getValueType().getTypePtr();
10155     if (const EnumType *ET = dyn_cast<EnumType>(T))
10156       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10157 
10158     const BuiltinType *BT = cast<BuiltinType>(T);
10159     assert(BT->isInteger());
10160 
10161     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10162   }
10163 
10164   /// Returns the supremum of two ranges: i.e. their conservative merge.
10165   static IntRange join(IntRange L, IntRange R) {
10166     return IntRange(std::max(L.Width, R.Width),
10167                     L.NonNegative && R.NonNegative);
10168   }
10169 
10170   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10171   static IntRange meet(IntRange L, IntRange R) {
10172     return IntRange(std::min(L.Width, R.Width),
10173                     L.NonNegative || R.NonNegative);
10174   }
10175 };
10176 
10177 } // namespace
10178 
10179 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10180                               unsigned MaxWidth) {
10181   if (value.isSigned() && value.isNegative())
10182     return IntRange(value.getMinSignedBits(), false);
10183 
10184   if (value.getBitWidth() > MaxWidth)
10185     value = value.trunc(MaxWidth);
10186 
10187   // isNonNegative() just checks the sign bit without considering
10188   // signedness.
10189   return IntRange(value.getActiveBits(), true);
10190 }
10191 
10192 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10193                               unsigned MaxWidth) {
10194   if (result.isInt())
10195     return GetValueRange(C, result.getInt(), MaxWidth);
10196 
10197   if (result.isVector()) {
10198     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10199     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10200       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10201       R = IntRange::join(R, El);
10202     }
10203     return R;
10204   }
10205 
10206   if (result.isComplexInt()) {
10207     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10208     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10209     return IntRange::join(R, I);
10210   }
10211 
10212   // This can happen with lossless casts to intptr_t of "based" lvalues.
10213   // Assume it might use arbitrary bits.
10214   // FIXME: The only reason we need to pass the type in here is to get
10215   // the sign right on this one case.  It would be nice if APValue
10216   // preserved this.
10217   assert(result.isLValue() || result.isAddrLabelDiff());
10218   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10219 }
10220 
10221 static QualType GetExprType(const Expr *E) {
10222   QualType Ty = E->getType();
10223   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10224     Ty = AtomicRHS->getValueType();
10225   return Ty;
10226 }
10227 
10228 /// Pseudo-evaluate the given integer expression, estimating the
10229 /// range of values it might take.
10230 ///
10231 /// \param MaxWidth - the width to which the value will be truncated
10232 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10233                              bool InConstantContext) {
10234   E = E->IgnoreParens();
10235 
10236   // Try a full evaluation first.
10237   Expr::EvalResult result;
10238   if (E->EvaluateAsRValue(result, C, InConstantContext))
10239     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10240 
10241   // I think we only want to look through implicit casts here; if the
10242   // user has an explicit widening cast, we should treat the value as
10243   // being of the new, wider type.
10244   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10245     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10246       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10247 
10248     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10249 
10250     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10251                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10252 
10253     // Assume that non-integer casts can span the full range of the type.
10254     if (!isIntegerCast)
10255       return OutputTypeRange;
10256 
10257     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10258                                      std::min(MaxWidth, OutputTypeRange.Width),
10259                                      InConstantContext);
10260 
10261     // Bail out if the subexpr's range is as wide as the cast type.
10262     if (SubRange.Width >= OutputTypeRange.Width)
10263       return OutputTypeRange;
10264 
10265     // Otherwise, we take the smaller width, and we're non-negative if
10266     // either the output type or the subexpr is.
10267     return IntRange(SubRange.Width,
10268                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10269   }
10270 
10271   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10272     // If we can fold the condition, just take that operand.
10273     bool CondResult;
10274     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10275       return GetExprRange(C,
10276                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10277                           MaxWidth, InConstantContext);
10278 
10279     // Otherwise, conservatively merge.
10280     IntRange L =
10281         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10282     IntRange R =
10283         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10284     return IntRange::join(L, R);
10285   }
10286 
10287   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10288     switch (BO->getOpcode()) {
10289     case BO_Cmp:
10290       llvm_unreachable("builtin <=> should have class type");
10291 
10292     // Boolean-valued operations are single-bit and positive.
10293     case BO_LAnd:
10294     case BO_LOr:
10295     case BO_LT:
10296     case BO_GT:
10297     case BO_LE:
10298     case BO_GE:
10299     case BO_EQ:
10300     case BO_NE:
10301       return IntRange::forBoolType();
10302 
10303     // The type of the assignments is the type of the LHS, so the RHS
10304     // is not necessarily the same type.
10305     case BO_MulAssign:
10306     case BO_DivAssign:
10307     case BO_RemAssign:
10308     case BO_AddAssign:
10309     case BO_SubAssign:
10310     case BO_XorAssign:
10311     case BO_OrAssign:
10312       // TODO: bitfields?
10313       return IntRange::forValueOfType(C, GetExprType(E));
10314 
10315     // Simple assignments just pass through the RHS, which will have
10316     // been coerced to the LHS type.
10317     case BO_Assign:
10318       // TODO: bitfields?
10319       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10320 
10321     // Operations with opaque sources are black-listed.
10322     case BO_PtrMemD:
10323     case BO_PtrMemI:
10324       return IntRange::forValueOfType(C, GetExprType(E));
10325 
10326     // Bitwise-and uses the *infinum* of the two source ranges.
10327     case BO_And:
10328     case BO_AndAssign:
10329       return IntRange::meet(
10330           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10331           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10332 
10333     // Left shift gets black-listed based on a judgement call.
10334     case BO_Shl:
10335       // ...except that we want to treat '1 << (blah)' as logically
10336       // positive.  It's an important idiom.
10337       if (IntegerLiteral *I
10338             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10339         if (I->getValue() == 1) {
10340           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10341           return IntRange(R.Width, /*NonNegative*/ true);
10342         }
10343       }
10344       LLVM_FALLTHROUGH;
10345 
10346     case BO_ShlAssign:
10347       return IntRange::forValueOfType(C, GetExprType(E));
10348 
10349     // Right shift by a constant can narrow its left argument.
10350     case BO_Shr:
10351     case BO_ShrAssign: {
10352       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10353 
10354       // If the shift amount is a positive constant, drop the width by
10355       // that much.
10356       llvm::APSInt shift;
10357       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10358           shift.isNonNegative()) {
10359         unsigned zext = shift.getZExtValue();
10360         if (zext >= L.Width)
10361           L.Width = (L.NonNegative ? 0 : 1);
10362         else
10363           L.Width -= zext;
10364       }
10365 
10366       return L;
10367     }
10368 
10369     // Comma acts as its right operand.
10370     case BO_Comma:
10371       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10372 
10373     // Black-list pointer subtractions.
10374     case BO_Sub:
10375       if (BO->getLHS()->getType()->isPointerType())
10376         return IntRange::forValueOfType(C, GetExprType(E));
10377       break;
10378 
10379     // The width of a division result is mostly determined by the size
10380     // of the LHS.
10381     case BO_Div: {
10382       // Don't 'pre-truncate' the operands.
10383       unsigned opWidth = C.getIntWidth(GetExprType(E));
10384       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10385 
10386       // If the divisor is constant, use that.
10387       llvm::APSInt divisor;
10388       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10389         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10390         if (log2 >= L.Width)
10391           L.Width = (L.NonNegative ? 0 : 1);
10392         else
10393           L.Width = std::min(L.Width - log2, MaxWidth);
10394         return L;
10395       }
10396 
10397       // Otherwise, just use the LHS's width.
10398       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10399       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10400     }
10401 
10402     // The result of a remainder can't be larger than the result of
10403     // either side.
10404     case BO_Rem: {
10405       // Don't 'pre-truncate' the operands.
10406       unsigned opWidth = C.getIntWidth(GetExprType(E));
10407       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10408       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10409 
10410       IntRange meet = IntRange::meet(L, R);
10411       meet.Width = std::min(meet.Width, MaxWidth);
10412       return meet;
10413     }
10414 
10415     // The default behavior is okay for these.
10416     case BO_Mul:
10417     case BO_Add:
10418     case BO_Xor:
10419     case BO_Or:
10420       break;
10421     }
10422 
10423     // The default case is to treat the operation as if it were closed
10424     // on the narrowest type that encompasses both operands.
10425     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10426     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10427     return IntRange::join(L, R);
10428   }
10429 
10430   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10431     switch (UO->getOpcode()) {
10432     // Boolean-valued operations are white-listed.
10433     case UO_LNot:
10434       return IntRange::forBoolType();
10435 
10436     // Operations with opaque sources are black-listed.
10437     case UO_Deref:
10438     case UO_AddrOf: // should be impossible
10439       return IntRange::forValueOfType(C, GetExprType(E));
10440 
10441     default:
10442       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10443     }
10444   }
10445 
10446   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10447     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10448 
10449   if (const auto *BitField = E->getSourceBitField())
10450     return IntRange(BitField->getBitWidthValue(C),
10451                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10452 
10453   return IntRange::forValueOfType(C, GetExprType(E));
10454 }
10455 
10456 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10457                              bool InConstantContext) {
10458   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10459 }
10460 
10461 /// Checks whether the given value, which currently has the given
10462 /// source semantics, has the same value when coerced through the
10463 /// target semantics.
10464 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10465                                  const llvm::fltSemantics &Src,
10466                                  const llvm::fltSemantics &Tgt) {
10467   llvm::APFloat truncated = value;
10468 
10469   bool ignored;
10470   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10471   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10472 
10473   return truncated.bitwiseIsEqual(value);
10474 }
10475 
10476 /// Checks whether the given value, which currently has the given
10477 /// source semantics, has the same value when coerced through the
10478 /// target semantics.
10479 ///
10480 /// The value might be a vector of floats (or a complex number).
10481 static bool IsSameFloatAfterCast(const APValue &value,
10482                                  const llvm::fltSemantics &Src,
10483                                  const llvm::fltSemantics &Tgt) {
10484   if (value.isFloat())
10485     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10486 
10487   if (value.isVector()) {
10488     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10489       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10490         return false;
10491     return true;
10492   }
10493 
10494   assert(value.isComplexFloat());
10495   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10496           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10497 }
10498 
10499 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10500                                        bool IsListInit = false);
10501 
10502 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10503   // Suppress cases where we are comparing against an enum constant.
10504   if (const DeclRefExpr *DR =
10505       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10506     if (isa<EnumConstantDecl>(DR->getDecl()))
10507       return true;
10508 
10509   // Suppress cases where the value is expanded from a macro, unless that macro
10510   // is how a language represents a boolean literal. This is the case in both C
10511   // and Objective-C.
10512   SourceLocation BeginLoc = E->getBeginLoc();
10513   if (BeginLoc.isMacroID()) {
10514     StringRef MacroName = Lexer::getImmediateMacroName(
10515         BeginLoc, S.getSourceManager(), S.getLangOpts());
10516     return MacroName != "YES" && MacroName != "NO" &&
10517            MacroName != "true" && MacroName != "false";
10518   }
10519 
10520   return false;
10521 }
10522 
10523 static bool isKnownToHaveUnsignedValue(Expr *E) {
10524   return E->getType()->isIntegerType() &&
10525          (!E->getType()->isSignedIntegerType() ||
10526           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10527 }
10528 
10529 namespace {
10530 /// The promoted range of values of a type. In general this has the
10531 /// following structure:
10532 ///
10533 ///     |-----------| . . . |-----------|
10534 ///     ^           ^       ^           ^
10535 ///    Min       HoleMin  HoleMax      Max
10536 ///
10537 /// ... where there is only a hole if a signed type is promoted to unsigned
10538 /// (in which case Min and Max are the smallest and largest representable
10539 /// values).
10540 struct PromotedRange {
10541   // Min, or HoleMax if there is a hole.
10542   llvm::APSInt PromotedMin;
10543   // Max, or HoleMin if there is a hole.
10544   llvm::APSInt PromotedMax;
10545 
10546   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10547     if (R.Width == 0)
10548       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10549     else if (R.Width >= BitWidth && !Unsigned) {
10550       // Promotion made the type *narrower*. This happens when promoting
10551       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10552       // Treat all values of 'signed int' as being in range for now.
10553       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10554       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10555     } else {
10556       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10557                         .extOrTrunc(BitWidth);
10558       PromotedMin.setIsUnsigned(Unsigned);
10559 
10560       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10561                         .extOrTrunc(BitWidth);
10562       PromotedMax.setIsUnsigned(Unsigned);
10563     }
10564   }
10565 
10566   // Determine whether this range is contiguous (has no hole).
10567   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10568 
10569   // Where a constant value is within the range.
10570   enum ComparisonResult {
10571     LT = 0x1,
10572     LE = 0x2,
10573     GT = 0x4,
10574     GE = 0x8,
10575     EQ = 0x10,
10576     NE = 0x20,
10577     InRangeFlag = 0x40,
10578 
10579     Less = LE | LT | NE,
10580     Min = LE | InRangeFlag,
10581     InRange = InRangeFlag,
10582     Max = GE | InRangeFlag,
10583     Greater = GE | GT | NE,
10584 
10585     OnlyValue = LE | GE | EQ | InRangeFlag,
10586     InHole = NE
10587   };
10588 
10589   ComparisonResult compare(const llvm::APSInt &Value) const {
10590     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10591            Value.isUnsigned() == PromotedMin.isUnsigned());
10592     if (!isContiguous()) {
10593       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10594       if (Value.isMinValue()) return Min;
10595       if (Value.isMaxValue()) return Max;
10596       if (Value >= PromotedMin) return InRange;
10597       if (Value <= PromotedMax) return InRange;
10598       return InHole;
10599     }
10600 
10601     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10602     case -1: return Less;
10603     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10604     case 1:
10605       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10606       case -1: return InRange;
10607       case 0: return Max;
10608       case 1: return Greater;
10609       }
10610     }
10611 
10612     llvm_unreachable("impossible compare result");
10613   }
10614 
10615   static llvm::Optional<StringRef>
10616   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10617     if (Op == BO_Cmp) {
10618       ComparisonResult LTFlag = LT, GTFlag = GT;
10619       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10620 
10621       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10622       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10623       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10624       return llvm::None;
10625     }
10626 
10627     ComparisonResult TrueFlag, FalseFlag;
10628     if (Op == BO_EQ) {
10629       TrueFlag = EQ;
10630       FalseFlag = NE;
10631     } else if (Op == BO_NE) {
10632       TrueFlag = NE;
10633       FalseFlag = EQ;
10634     } else {
10635       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10636         TrueFlag = LT;
10637         FalseFlag = GE;
10638       } else {
10639         TrueFlag = GT;
10640         FalseFlag = LE;
10641       }
10642       if (Op == BO_GE || Op == BO_LE)
10643         std::swap(TrueFlag, FalseFlag);
10644     }
10645     if (R & TrueFlag)
10646       return StringRef("true");
10647     if (R & FalseFlag)
10648       return StringRef("false");
10649     return llvm::None;
10650   }
10651 };
10652 }
10653 
10654 static bool HasEnumType(Expr *E) {
10655   // Strip off implicit integral promotions.
10656   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10657     if (ICE->getCastKind() != CK_IntegralCast &&
10658         ICE->getCastKind() != CK_NoOp)
10659       break;
10660     E = ICE->getSubExpr();
10661   }
10662 
10663   return E->getType()->isEnumeralType();
10664 }
10665 
10666 static int classifyConstantValue(Expr *Constant) {
10667   // The values of this enumeration are used in the diagnostics
10668   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10669   enum ConstantValueKind {
10670     Miscellaneous = 0,
10671     LiteralTrue,
10672     LiteralFalse
10673   };
10674   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10675     return BL->getValue() ? ConstantValueKind::LiteralTrue
10676                           : ConstantValueKind::LiteralFalse;
10677   return ConstantValueKind::Miscellaneous;
10678 }
10679 
10680 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10681                                         Expr *Constant, Expr *Other,
10682                                         const llvm::APSInt &Value,
10683                                         bool RhsConstant) {
10684   if (S.inTemplateInstantiation())
10685     return false;
10686 
10687   Expr *OriginalOther = Other;
10688 
10689   Constant = Constant->IgnoreParenImpCasts();
10690   Other = Other->IgnoreParenImpCasts();
10691 
10692   // Suppress warnings on tautological comparisons between values of the same
10693   // enumeration type. There are only two ways we could warn on this:
10694   //  - If the constant is outside the range of representable values of
10695   //    the enumeration. In such a case, we should warn about the cast
10696   //    to enumeration type, not about the comparison.
10697   //  - If the constant is the maximum / minimum in-range value. For an
10698   //    enumeratin type, such comparisons can be meaningful and useful.
10699   if (Constant->getType()->isEnumeralType() &&
10700       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10701     return false;
10702 
10703   // TODO: Investigate using GetExprRange() to get tighter bounds
10704   // on the bit ranges.
10705   QualType OtherT = Other->getType();
10706   if (const auto *AT = OtherT->getAs<AtomicType>())
10707     OtherT = AT->getValueType();
10708   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10709 
10710   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10711   // (Namely, macOS).
10712   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10713                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10714                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10715 
10716   // Whether we're treating Other as being a bool because of the form of
10717   // expression despite it having another type (typically 'int' in C).
10718   bool OtherIsBooleanDespiteType =
10719       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10720   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10721     OtherRange = IntRange::forBoolType();
10722 
10723   // Determine the promoted range of the other type and see if a comparison of
10724   // the constant against that range is tautological.
10725   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10726                                    Value.isUnsigned());
10727   auto Cmp = OtherPromotedRange.compare(Value);
10728   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10729   if (!Result)
10730     return false;
10731 
10732   // Suppress the diagnostic for an in-range comparison if the constant comes
10733   // from a macro or enumerator. We don't want to diagnose
10734   //
10735   //   some_long_value <= INT_MAX
10736   //
10737   // when sizeof(int) == sizeof(long).
10738   bool InRange = Cmp & PromotedRange::InRangeFlag;
10739   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10740     return false;
10741 
10742   // If this is a comparison to an enum constant, include that
10743   // constant in the diagnostic.
10744   const EnumConstantDecl *ED = nullptr;
10745   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10746     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10747 
10748   // Should be enough for uint128 (39 decimal digits)
10749   SmallString<64> PrettySourceValue;
10750   llvm::raw_svector_ostream OS(PrettySourceValue);
10751   if (ED) {
10752     OS << '\'' << *ED << "' (" << Value << ")";
10753   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10754                Constant->IgnoreParenImpCasts())) {
10755     OS << (BL->getValue() ? "YES" : "NO");
10756   } else {
10757     OS << Value;
10758   }
10759 
10760   if (IsObjCSignedCharBool) {
10761     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10762                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10763                               << OS.str() << *Result);
10764     return true;
10765   }
10766 
10767   // FIXME: We use a somewhat different formatting for the in-range cases and
10768   // cases involving boolean values for historical reasons. We should pick a
10769   // consistent way of presenting these diagnostics.
10770   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10771 
10772     S.DiagRuntimeBehavior(
10773         E->getOperatorLoc(), E,
10774         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10775                          : diag::warn_tautological_bool_compare)
10776             << OS.str() << classifyConstantValue(Constant) << OtherT
10777             << OtherIsBooleanDespiteType << *Result
10778             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10779   } else {
10780     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10781                         ? (HasEnumType(OriginalOther)
10782                                ? diag::warn_unsigned_enum_always_true_comparison
10783                                : diag::warn_unsigned_always_true_comparison)
10784                         : diag::warn_tautological_constant_compare;
10785 
10786     S.Diag(E->getOperatorLoc(), Diag)
10787         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10788         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10789   }
10790 
10791   return true;
10792 }
10793 
10794 /// Analyze the operands of the given comparison.  Implements the
10795 /// fallback case from AnalyzeComparison.
10796 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10797   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10798   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10799 }
10800 
10801 /// Implements -Wsign-compare.
10802 ///
10803 /// \param E the binary operator to check for warnings
10804 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10805   // The type the comparison is being performed in.
10806   QualType T = E->getLHS()->getType();
10807 
10808   // Only analyze comparison operators where both sides have been converted to
10809   // the same type.
10810   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10811     return AnalyzeImpConvsInComparison(S, E);
10812 
10813   // Don't analyze value-dependent comparisons directly.
10814   if (E->isValueDependent())
10815     return AnalyzeImpConvsInComparison(S, E);
10816 
10817   Expr *LHS = E->getLHS();
10818   Expr *RHS = E->getRHS();
10819 
10820   if (T->isIntegralType(S.Context)) {
10821     llvm::APSInt RHSValue;
10822     llvm::APSInt LHSValue;
10823 
10824     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10825     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10826 
10827     // We don't care about expressions whose result is a constant.
10828     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10829       return AnalyzeImpConvsInComparison(S, E);
10830 
10831     // We only care about expressions where just one side is literal
10832     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10833       // Is the constant on the RHS or LHS?
10834       const bool RhsConstant = IsRHSIntegralLiteral;
10835       Expr *Const = RhsConstant ? RHS : LHS;
10836       Expr *Other = RhsConstant ? LHS : RHS;
10837       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10838 
10839       // Check whether an integer constant comparison results in a value
10840       // of 'true' or 'false'.
10841       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10842         return AnalyzeImpConvsInComparison(S, E);
10843     }
10844   }
10845 
10846   if (!T->hasUnsignedIntegerRepresentation()) {
10847     // We don't do anything special if this isn't an unsigned integral
10848     // comparison:  we're only interested in integral comparisons, and
10849     // signed comparisons only happen in cases we don't care to warn about.
10850     return AnalyzeImpConvsInComparison(S, E);
10851   }
10852 
10853   LHS = LHS->IgnoreParenImpCasts();
10854   RHS = RHS->IgnoreParenImpCasts();
10855 
10856   if (!S.getLangOpts().CPlusPlus) {
10857     // Avoid warning about comparison of integers with different signs when
10858     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10859     // the type of `E`.
10860     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10861       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10862     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10863       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10864   }
10865 
10866   // Check to see if one of the (unmodified) operands is of different
10867   // signedness.
10868   Expr *signedOperand, *unsignedOperand;
10869   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10870     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10871            "unsigned comparison between two signed integer expressions?");
10872     signedOperand = LHS;
10873     unsignedOperand = RHS;
10874   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10875     signedOperand = RHS;
10876     unsignedOperand = LHS;
10877   } else {
10878     return AnalyzeImpConvsInComparison(S, E);
10879   }
10880 
10881   // Otherwise, calculate the effective range of the signed operand.
10882   IntRange signedRange =
10883       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10884 
10885   // Go ahead and analyze implicit conversions in the operands.  Note
10886   // that we skip the implicit conversions on both sides.
10887   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10888   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10889 
10890   // If the signed range is non-negative, -Wsign-compare won't fire.
10891   if (signedRange.NonNegative)
10892     return;
10893 
10894   // For (in)equality comparisons, if the unsigned operand is a
10895   // constant which cannot collide with a overflowed signed operand,
10896   // then reinterpreting the signed operand as unsigned will not
10897   // change the result of the comparison.
10898   if (E->isEqualityOp()) {
10899     unsigned comparisonWidth = S.Context.getIntWidth(T);
10900     IntRange unsignedRange =
10901         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10902 
10903     // We should never be unable to prove that the unsigned operand is
10904     // non-negative.
10905     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10906 
10907     if (unsignedRange.Width < comparisonWidth)
10908       return;
10909   }
10910 
10911   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10912                         S.PDiag(diag::warn_mixed_sign_comparison)
10913                             << LHS->getType() << RHS->getType()
10914                             << LHS->getSourceRange() << RHS->getSourceRange());
10915 }
10916 
10917 /// Analyzes an attempt to assign the given value to a bitfield.
10918 ///
10919 /// Returns true if there was something fishy about the attempt.
10920 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10921                                       SourceLocation InitLoc) {
10922   assert(Bitfield->isBitField());
10923   if (Bitfield->isInvalidDecl())
10924     return false;
10925 
10926   // White-list bool bitfields.
10927   QualType BitfieldType = Bitfield->getType();
10928   if (BitfieldType->isBooleanType())
10929      return false;
10930 
10931   if (BitfieldType->isEnumeralType()) {
10932     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10933     // If the underlying enum type was not explicitly specified as an unsigned
10934     // type and the enum contain only positive values, MSVC++ will cause an
10935     // inconsistency by storing this as a signed type.
10936     if (S.getLangOpts().CPlusPlus11 &&
10937         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10938         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10939         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10940       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10941         << BitfieldEnumDecl->getNameAsString();
10942     }
10943   }
10944 
10945   if (Bitfield->getType()->isBooleanType())
10946     return false;
10947 
10948   // Ignore value- or type-dependent expressions.
10949   if (Bitfield->getBitWidth()->isValueDependent() ||
10950       Bitfield->getBitWidth()->isTypeDependent() ||
10951       Init->isValueDependent() ||
10952       Init->isTypeDependent())
10953     return false;
10954 
10955   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10956   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10957 
10958   Expr::EvalResult Result;
10959   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10960                                    Expr::SE_AllowSideEffects)) {
10961     // The RHS is not constant.  If the RHS has an enum type, make sure the
10962     // bitfield is wide enough to hold all the values of the enum without
10963     // truncation.
10964     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10965       EnumDecl *ED = EnumTy->getDecl();
10966       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10967 
10968       // Enum types are implicitly signed on Windows, so check if there are any
10969       // negative enumerators to see if the enum was intended to be signed or
10970       // not.
10971       bool SignedEnum = ED->getNumNegativeBits() > 0;
10972 
10973       // Check for surprising sign changes when assigning enum values to a
10974       // bitfield of different signedness.  If the bitfield is signed and we
10975       // have exactly the right number of bits to store this unsigned enum,
10976       // suggest changing the enum to an unsigned type. This typically happens
10977       // on Windows where unfixed enums always use an underlying type of 'int'.
10978       unsigned DiagID = 0;
10979       if (SignedEnum && !SignedBitfield) {
10980         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10981       } else if (SignedBitfield && !SignedEnum &&
10982                  ED->getNumPositiveBits() == FieldWidth) {
10983         DiagID = diag::warn_signed_bitfield_enum_conversion;
10984       }
10985 
10986       if (DiagID) {
10987         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10988         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10989         SourceRange TypeRange =
10990             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10991         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10992             << SignedEnum << TypeRange;
10993       }
10994 
10995       // Compute the required bitwidth. If the enum has negative values, we need
10996       // one more bit than the normal number of positive bits to represent the
10997       // sign bit.
10998       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10999                                                   ED->getNumNegativeBits())
11000                                        : ED->getNumPositiveBits();
11001 
11002       // Check the bitwidth.
11003       if (BitsNeeded > FieldWidth) {
11004         Expr *WidthExpr = Bitfield->getBitWidth();
11005         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11006             << Bitfield << ED;
11007         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11008             << BitsNeeded << ED << WidthExpr->getSourceRange();
11009       }
11010     }
11011 
11012     return false;
11013   }
11014 
11015   llvm::APSInt Value = Result.Val.getInt();
11016 
11017   unsigned OriginalWidth = Value.getBitWidth();
11018 
11019   if (!Value.isSigned() || Value.isNegative())
11020     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11021       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11022         OriginalWidth = Value.getMinSignedBits();
11023 
11024   if (OriginalWidth <= FieldWidth)
11025     return false;
11026 
11027   // Compute the value which the bitfield will contain.
11028   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11029   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11030 
11031   // Check whether the stored value is equal to the original value.
11032   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11033   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11034     return false;
11035 
11036   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11037   // therefore don't strictly fit into a signed bitfield of width 1.
11038   if (FieldWidth == 1 && Value == 1)
11039     return false;
11040 
11041   std::string PrettyValue = Value.toString(10);
11042   std::string PrettyTrunc = TruncatedValue.toString(10);
11043 
11044   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11045     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11046     << Init->getSourceRange();
11047 
11048   return true;
11049 }
11050 
11051 /// Analyze the given simple or compound assignment for warning-worthy
11052 /// operations.
11053 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11054   // Just recurse on the LHS.
11055   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11056 
11057   // We want to recurse on the RHS as normal unless we're assigning to
11058   // a bitfield.
11059   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11060     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11061                                   E->getOperatorLoc())) {
11062       // Recurse, ignoring any implicit conversions on the RHS.
11063       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11064                                         E->getOperatorLoc());
11065     }
11066   }
11067 
11068   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11069 
11070   // Diagnose implicitly sequentially-consistent atomic assignment.
11071   if (E->getLHS()->getType()->isAtomicType())
11072     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11073 }
11074 
11075 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11076 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11077                             SourceLocation CContext, unsigned diag,
11078                             bool pruneControlFlow = false) {
11079   if (pruneControlFlow) {
11080     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11081                           S.PDiag(diag)
11082                               << SourceType << T << E->getSourceRange()
11083                               << SourceRange(CContext));
11084     return;
11085   }
11086   S.Diag(E->getExprLoc(), diag)
11087     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11088 }
11089 
11090 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11091 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11092                             SourceLocation CContext,
11093                             unsigned diag, bool pruneControlFlow = false) {
11094   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11095 }
11096 
11097 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11098   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11099       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11100 }
11101 
11102 static void adornObjCBoolConversionDiagWithTernaryFixit(
11103     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11104   Expr *Ignored = SourceExpr->IgnoreImplicit();
11105   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11106     Ignored = OVE->getSourceExpr();
11107   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11108                      isa<BinaryOperator>(Ignored) ||
11109                      isa<CXXOperatorCallExpr>(Ignored);
11110   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11111   if (NeedsParens)
11112     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11113             << FixItHint::CreateInsertion(EndLoc, ")");
11114   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11115 }
11116 
11117 /// Diagnose an implicit cast from a floating point value to an integer value.
11118 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11119                                     SourceLocation CContext) {
11120   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11121   const bool PruneWarnings = S.inTemplateInstantiation();
11122 
11123   Expr *InnerE = E->IgnoreParenImpCasts();
11124   // We also want to warn on, e.g., "int i = -1.234"
11125   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11126     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11127       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11128 
11129   const bool IsLiteral =
11130       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11131 
11132   llvm::APFloat Value(0.0);
11133   bool IsConstant =
11134     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11135   if (!IsConstant) {
11136     if (isObjCSignedCharBool(S, T)) {
11137       return adornObjCBoolConversionDiagWithTernaryFixit(
11138           S, E,
11139           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11140               << E->getType());
11141     }
11142 
11143     return DiagnoseImpCast(S, E, T, CContext,
11144                            diag::warn_impcast_float_integer, PruneWarnings);
11145   }
11146 
11147   bool isExact = false;
11148 
11149   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11150                             T->hasUnsignedIntegerRepresentation());
11151   llvm::APFloat::opStatus Result = Value.convertToInteger(
11152       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11153 
11154   // FIXME: Force the precision of the source value down so we don't print
11155   // digits which are usually useless (we don't really care here if we
11156   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11157   // would automatically print the shortest representation, but it's a bit
11158   // tricky to implement.
11159   SmallString<16> PrettySourceValue;
11160   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11161   precision = (precision * 59 + 195) / 196;
11162   Value.toString(PrettySourceValue, precision);
11163 
11164   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11165     return adornObjCBoolConversionDiagWithTernaryFixit(
11166         S, E,
11167         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11168             << PrettySourceValue);
11169   }
11170 
11171   if (Result == llvm::APFloat::opOK && isExact) {
11172     if (IsLiteral) return;
11173     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11174                            PruneWarnings);
11175   }
11176 
11177   // Conversion of a floating-point value to a non-bool integer where the
11178   // integral part cannot be represented by the integer type is undefined.
11179   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11180     return DiagnoseImpCast(
11181         S, E, T, CContext,
11182         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11183                   : diag::warn_impcast_float_to_integer_out_of_range,
11184         PruneWarnings);
11185 
11186   unsigned DiagID = 0;
11187   if (IsLiteral) {
11188     // Warn on floating point literal to integer.
11189     DiagID = diag::warn_impcast_literal_float_to_integer;
11190   } else if (IntegerValue == 0) {
11191     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11192       return DiagnoseImpCast(S, E, T, CContext,
11193                              diag::warn_impcast_float_integer, PruneWarnings);
11194     }
11195     // Warn on non-zero to zero conversion.
11196     DiagID = diag::warn_impcast_float_to_integer_zero;
11197   } else {
11198     if (IntegerValue.isUnsigned()) {
11199       if (!IntegerValue.isMaxValue()) {
11200         return DiagnoseImpCast(S, E, T, CContext,
11201                                diag::warn_impcast_float_integer, PruneWarnings);
11202       }
11203     } else {  // IntegerValue.isSigned()
11204       if (!IntegerValue.isMaxSignedValue() &&
11205           !IntegerValue.isMinSignedValue()) {
11206         return DiagnoseImpCast(S, E, T, CContext,
11207                                diag::warn_impcast_float_integer, PruneWarnings);
11208       }
11209     }
11210     // Warn on evaluatable floating point expression to integer conversion.
11211     DiagID = diag::warn_impcast_float_to_integer;
11212   }
11213 
11214   SmallString<16> PrettyTargetValue;
11215   if (IsBool)
11216     PrettyTargetValue = Value.isZero() ? "false" : "true";
11217   else
11218     IntegerValue.toString(PrettyTargetValue);
11219 
11220   if (PruneWarnings) {
11221     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11222                           S.PDiag(DiagID)
11223                               << E->getType() << T.getUnqualifiedType()
11224                               << PrettySourceValue << PrettyTargetValue
11225                               << E->getSourceRange() << SourceRange(CContext));
11226   } else {
11227     S.Diag(E->getExprLoc(), DiagID)
11228         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11229         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11230   }
11231 }
11232 
11233 /// Analyze the given compound assignment for the possible losing of
11234 /// floating-point precision.
11235 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11236   assert(isa<CompoundAssignOperator>(E) &&
11237          "Must be compound assignment operation");
11238   // Recurse on the LHS and RHS in here
11239   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11240   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11241 
11242   if (E->getLHS()->getType()->isAtomicType())
11243     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11244 
11245   // Now check the outermost expression
11246   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11247   const auto *RBT = cast<CompoundAssignOperator>(E)
11248                         ->getComputationResultType()
11249                         ->getAs<BuiltinType>();
11250 
11251   // The below checks assume source is floating point.
11252   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11253 
11254   // If source is floating point but target is an integer.
11255   if (ResultBT->isInteger())
11256     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11257                            E->getExprLoc(), diag::warn_impcast_float_integer);
11258 
11259   if (!ResultBT->isFloatingPoint())
11260     return;
11261 
11262   // If both source and target are floating points, warn about losing precision.
11263   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11264       QualType(ResultBT, 0), QualType(RBT, 0));
11265   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11266     // warn about dropping FP rank.
11267     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11268                     diag::warn_impcast_float_result_precision);
11269 }
11270 
11271 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11272                                       IntRange Range) {
11273   if (!Range.Width) return "0";
11274 
11275   llvm::APSInt ValueInRange = Value;
11276   ValueInRange.setIsSigned(!Range.NonNegative);
11277   ValueInRange = ValueInRange.trunc(Range.Width);
11278   return ValueInRange.toString(10);
11279 }
11280 
11281 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11282   if (!isa<ImplicitCastExpr>(Ex))
11283     return false;
11284 
11285   Expr *InnerE = Ex->IgnoreParenImpCasts();
11286   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11287   const Type *Source =
11288     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11289   if (Target->isDependentType())
11290     return false;
11291 
11292   const BuiltinType *FloatCandidateBT =
11293     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11294   const Type *BoolCandidateType = ToBool ? Target : Source;
11295 
11296   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11297           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11298 }
11299 
11300 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11301                                              SourceLocation CC) {
11302   unsigned NumArgs = TheCall->getNumArgs();
11303   for (unsigned i = 0; i < NumArgs; ++i) {
11304     Expr *CurrA = TheCall->getArg(i);
11305     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11306       continue;
11307 
11308     bool IsSwapped = ((i > 0) &&
11309         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11310     IsSwapped |= ((i < (NumArgs - 1)) &&
11311         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11312     if (IsSwapped) {
11313       // Warn on this floating-point to bool conversion.
11314       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11315                       CurrA->getType(), CC,
11316                       diag::warn_impcast_floating_point_to_bool);
11317     }
11318   }
11319 }
11320 
11321 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11322                                    SourceLocation CC) {
11323   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11324                         E->getExprLoc()))
11325     return;
11326 
11327   // Don't warn on functions which have return type nullptr_t.
11328   if (isa<CallExpr>(E))
11329     return;
11330 
11331   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11332   const Expr::NullPointerConstantKind NullKind =
11333       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11334   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11335     return;
11336 
11337   // Return if target type is a safe conversion.
11338   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11339       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11340     return;
11341 
11342   SourceLocation Loc = E->getSourceRange().getBegin();
11343 
11344   // Venture through the macro stacks to get to the source of macro arguments.
11345   // The new location is a better location than the complete location that was
11346   // passed in.
11347   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11348   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11349 
11350   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11351   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11352     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11353         Loc, S.SourceMgr, S.getLangOpts());
11354     if (MacroName == "NULL")
11355       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11356   }
11357 
11358   // Only warn if the null and context location are in the same macro expansion.
11359   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11360     return;
11361 
11362   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11363       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11364       << FixItHint::CreateReplacement(Loc,
11365                                       S.getFixItZeroLiteralForType(T, Loc));
11366 }
11367 
11368 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11369                                   ObjCArrayLiteral *ArrayLiteral);
11370 
11371 static void
11372 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11373                            ObjCDictionaryLiteral *DictionaryLiteral);
11374 
11375 /// Check a single element within a collection literal against the
11376 /// target element type.
11377 static void checkObjCCollectionLiteralElement(Sema &S,
11378                                               QualType TargetElementType,
11379                                               Expr *Element,
11380                                               unsigned ElementKind) {
11381   // Skip a bitcast to 'id' or qualified 'id'.
11382   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11383     if (ICE->getCastKind() == CK_BitCast &&
11384         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11385       Element = ICE->getSubExpr();
11386   }
11387 
11388   QualType ElementType = Element->getType();
11389   ExprResult ElementResult(Element);
11390   if (ElementType->getAs<ObjCObjectPointerType>() &&
11391       S.CheckSingleAssignmentConstraints(TargetElementType,
11392                                          ElementResult,
11393                                          false, false)
11394         != Sema::Compatible) {
11395     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11396         << ElementType << ElementKind << TargetElementType
11397         << Element->getSourceRange();
11398   }
11399 
11400   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11401     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11402   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11403     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11404 }
11405 
11406 /// Check an Objective-C array literal being converted to the given
11407 /// target type.
11408 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11409                                   ObjCArrayLiteral *ArrayLiteral) {
11410   if (!S.NSArrayDecl)
11411     return;
11412 
11413   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11414   if (!TargetObjCPtr)
11415     return;
11416 
11417   if (TargetObjCPtr->isUnspecialized() ||
11418       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11419         != S.NSArrayDecl->getCanonicalDecl())
11420     return;
11421 
11422   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11423   if (TypeArgs.size() != 1)
11424     return;
11425 
11426   QualType TargetElementType = TypeArgs[0];
11427   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11428     checkObjCCollectionLiteralElement(S, TargetElementType,
11429                                       ArrayLiteral->getElement(I),
11430                                       0);
11431   }
11432 }
11433 
11434 /// Check an Objective-C dictionary literal being converted to the given
11435 /// target type.
11436 static void
11437 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11438                            ObjCDictionaryLiteral *DictionaryLiteral) {
11439   if (!S.NSDictionaryDecl)
11440     return;
11441 
11442   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11443   if (!TargetObjCPtr)
11444     return;
11445 
11446   if (TargetObjCPtr->isUnspecialized() ||
11447       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11448         != S.NSDictionaryDecl->getCanonicalDecl())
11449     return;
11450 
11451   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11452   if (TypeArgs.size() != 2)
11453     return;
11454 
11455   QualType TargetKeyType = TypeArgs[0];
11456   QualType TargetObjectType = TypeArgs[1];
11457   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11458     auto Element = DictionaryLiteral->getKeyValueElement(I);
11459     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11460     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11461   }
11462 }
11463 
11464 // Helper function to filter out cases for constant width constant conversion.
11465 // Don't warn on char array initialization or for non-decimal values.
11466 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11467                                           SourceLocation CC) {
11468   // If initializing from a constant, and the constant starts with '0',
11469   // then it is a binary, octal, or hexadecimal.  Allow these constants
11470   // to fill all the bits, even if there is a sign change.
11471   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11472     const char FirstLiteralCharacter =
11473         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11474     if (FirstLiteralCharacter == '0')
11475       return false;
11476   }
11477 
11478   // If the CC location points to a '{', and the type is char, then assume
11479   // assume it is an array initialization.
11480   if (CC.isValid() && T->isCharType()) {
11481     const char FirstContextCharacter =
11482         S.getSourceManager().getCharacterData(CC)[0];
11483     if (FirstContextCharacter == '{')
11484       return false;
11485   }
11486 
11487   return true;
11488 }
11489 
11490 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11491   const auto *IL = dyn_cast<IntegerLiteral>(E);
11492   if (!IL) {
11493     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11494       if (UO->getOpcode() == UO_Minus)
11495         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11496     }
11497   }
11498 
11499   return IL;
11500 }
11501 
11502 static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
11503                                           Expr *LHS, Expr *RHS) {
11504   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
11505   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
11506 
11507   const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
11508   if (!LHSEnumType)
11509     return;
11510   const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
11511   if (!RHSEnumType)
11512     return;
11513 
11514   // Ignore anonymous enums.
11515   if (!LHSEnumType->getDecl()->hasNameForLinkage())
11516     return;
11517   if (!RHSEnumType->getDecl()->hasNameForLinkage())
11518     return;
11519 
11520   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
11521     return;
11522 
11523   S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
11524       << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
11525       << RHS->getSourceRange();
11526 }
11527 
11528 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11529   E = E->IgnoreParenImpCasts();
11530   SourceLocation ExprLoc = E->getExprLoc();
11531 
11532   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11533     BinaryOperator::Opcode Opc = BO->getOpcode();
11534     Expr::EvalResult Result;
11535     // Do not diagnose unsigned shifts.
11536     if (Opc == BO_Shl) {
11537       const auto *LHS = getIntegerLiteral(BO->getLHS());
11538       const auto *RHS = getIntegerLiteral(BO->getRHS());
11539       if (LHS && LHS->getValue() == 0)
11540         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11541       else if (!E->isValueDependent() && LHS && RHS &&
11542                RHS->getValue().isNonNegative() &&
11543                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11544         S.Diag(ExprLoc, diag::warn_left_shift_always)
11545             << (Result.Val.getInt() != 0);
11546       else if (E->getType()->isSignedIntegerType())
11547         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11548     }
11549   }
11550 
11551   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11552     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11553     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11554     if (!LHS || !RHS)
11555       return;
11556     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11557         (RHS->getValue() == 0 || RHS->getValue() == 1))
11558       // Do not diagnose common idioms.
11559       return;
11560     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11561       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11562   }
11563 }
11564 
11565 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11566                                     SourceLocation CC,
11567                                     bool *ICContext = nullptr,
11568                                     bool IsListInit = false) {
11569   if (E->isTypeDependent() || E->isValueDependent()) return;
11570 
11571   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11572   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11573   if (Source == Target) return;
11574   if (Target->isDependentType()) return;
11575 
11576   // If the conversion context location is invalid don't complain. We also
11577   // don't want to emit a warning if the issue occurs from the expansion of
11578   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11579   // delay this check as long as possible. Once we detect we are in that
11580   // scenario, we just return.
11581   if (CC.isInvalid())
11582     return;
11583 
11584   if (Source->isAtomicType())
11585     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11586 
11587   // Diagnose implicit casts to bool.
11588   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11589     if (isa<StringLiteral>(E))
11590       // Warn on string literal to bool.  Checks for string literals in logical
11591       // and expressions, for instance, assert(0 && "error here"), are
11592       // prevented by a check in AnalyzeImplicitConversions().
11593       return DiagnoseImpCast(S, E, T, CC,
11594                              diag::warn_impcast_string_literal_to_bool);
11595     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11596         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11597       // This covers the literal expressions that evaluate to Objective-C
11598       // objects.
11599       return DiagnoseImpCast(S, E, T, CC,
11600                              diag::warn_impcast_objective_c_literal_to_bool);
11601     }
11602     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11603       // Warn on pointer to bool conversion that is always true.
11604       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11605                                      SourceRange(CC));
11606     }
11607   }
11608 
11609   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11610   // is a typedef for signed char (macOS), then that constant value has to be 1
11611   // or 0.
11612   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11613     Expr::EvalResult Result;
11614     if (E->EvaluateAsInt(Result, S.getASTContext(),
11615                          Expr::SE_AllowSideEffects)) {
11616       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11617         adornObjCBoolConversionDiagWithTernaryFixit(
11618             S, E,
11619             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11620                 << Result.Val.getInt().toString(10));
11621       }
11622       return;
11623     }
11624   }
11625 
11626   // Check implicit casts from Objective-C collection literals to specialized
11627   // collection types, e.g., NSArray<NSString *> *.
11628   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11629     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11630   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11631     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11632 
11633   // Strip vector types.
11634   if (isa<VectorType>(Source)) {
11635     if (!isa<VectorType>(Target)) {
11636       if (S.SourceMgr.isInSystemMacro(CC))
11637         return;
11638       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11639     }
11640 
11641     // If the vector cast is cast between two vectors of the same size, it is
11642     // a bitcast, not a conversion.
11643     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11644       return;
11645 
11646     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11647     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11648   }
11649   if (auto VecTy = dyn_cast<VectorType>(Target))
11650     Target = VecTy->getElementType().getTypePtr();
11651 
11652   // Strip complex types.
11653   if (isa<ComplexType>(Source)) {
11654     if (!isa<ComplexType>(Target)) {
11655       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11656         return;
11657 
11658       return DiagnoseImpCast(S, E, T, CC,
11659                              S.getLangOpts().CPlusPlus
11660                                  ? diag::err_impcast_complex_scalar
11661                                  : diag::warn_impcast_complex_scalar);
11662     }
11663 
11664     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11665     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11666   }
11667 
11668   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11669   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11670 
11671   // If the source is floating point...
11672   if (SourceBT && SourceBT->isFloatingPoint()) {
11673     // ...and the target is floating point...
11674     if (TargetBT && TargetBT->isFloatingPoint()) {
11675       // ...then warn if we're dropping FP rank.
11676 
11677       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11678           QualType(SourceBT, 0), QualType(TargetBT, 0));
11679       if (Order > 0) {
11680         // Don't warn about float constants that are precisely
11681         // representable in the target type.
11682         Expr::EvalResult result;
11683         if (E->EvaluateAsRValue(result, S.Context)) {
11684           // Value might be a float, a float vector, or a float complex.
11685           if (IsSameFloatAfterCast(result.Val,
11686                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11687                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11688             return;
11689         }
11690 
11691         if (S.SourceMgr.isInSystemMacro(CC))
11692           return;
11693 
11694         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11695       }
11696       // ... or possibly if we're increasing rank, too
11697       else if (Order < 0) {
11698         if (S.SourceMgr.isInSystemMacro(CC))
11699           return;
11700 
11701         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11702       }
11703       return;
11704     }
11705 
11706     // If the target is integral, always warn.
11707     if (TargetBT && TargetBT->isInteger()) {
11708       if (S.SourceMgr.isInSystemMacro(CC))
11709         return;
11710 
11711       DiagnoseFloatingImpCast(S, E, T, CC);
11712     }
11713 
11714     // Detect the case where a call result is converted from floating-point to
11715     // to bool, and the final argument to the call is converted from bool, to
11716     // discover this typo:
11717     //
11718     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11719     //
11720     // FIXME: This is an incredibly special case; is there some more general
11721     // way to detect this class of misplaced-parentheses bug?
11722     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11723       // Check last argument of function call to see if it is an
11724       // implicit cast from a type matching the type the result
11725       // is being cast to.
11726       CallExpr *CEx = cast<CallExpr>(E);
11727       if (unsigned NumArgs = CEx->getNumArgs()) {
11728         Expr *LastA = CEx->getArg(NumArgs - 1);
11729         Expr *InnerE = LastA->IgnoreParenImpCasts();
11730         if (isa<ImplicitCastExpr>(LastA) &&
11731             InnerE->getType()->isBooleanType()) {
11732           // Warn on this floating-point to bool conversion
11733           DiagnoseImpCast(S, E, T, CC,
11734                           diag::warn_impcast_floating_point_to_bool);
11735         }
11736       }
11737     }
11738     return;
11739   }
11740 
11741   // Valid casts involving fixed point types should be accounted for here.
11742   if (Source->isFixedPointType()) {
11743     if (Target->isUnsaturatedFixedPointType()) {
11744       Expr::EvalResult Result;
11745       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11746                                   S.isConstantEvaluated())) {
11747         APFixedPoint Value = Result.Val.getFixedPoint();
11748         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11749         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11750         if (Value > MaxVal || Value < MinVal) {
11751           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11752                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11753                                     << Value.toString() << T
11754                                     << E->getSourceRange()
11755                                     << clang::SourceRange(CC));
11756           return;
11757         }
11758       }
11759     } else if (Target->isIntegerType()) {
11760       Expr::EvalResult Result;
11761       if (!S.isConstantEvaluated() &&
11762           E->EvaluateAsFixedPoint(Result, S.Context,
11763                                   Expr::SE_AllowSideEffects)) {
11764         APFixedPoint FXResult = Result.Val.getFixedPoint();
11765 
11766         bool Overflowed;
11767         llvm::APSInt IntResult = FXResult.convertToInt(
11768             S.Context.getIntWidth(T),
11769             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11770 
11771         if (Overflowed) {
11772           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11773                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11774                                     << FXResult.toString() << T
11775                                     << E->getSourceRange()
11776                                     << clang::SourceRange(CC));
11777           return;
11778         }
11779       }
11780     }
11781   } else if (Target->isUnsaturatedFixedPointType()) {
11782     if (Source->isIntegerType()) {
11783       Expr::EvalResult Result;
11784       if (!S.isConstantEvaluated() &&
11785           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11786         llvm::APSInt Value = Result.Val.getInt();
11787 
11788         bool Overflowed;
11789         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11790             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11791 
11792         if (Overflowed) {
11793           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11794                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11795                                     << Value.toString(/*Radix=*/10) << T
11796                                     << E->getSourceRange()
11797                                     << clang::SourceRange(CC));
11798           return;
11799         }
11800       }
11801     }
11802   }
11803 
11804   // If we are casting an integer type to a floating point type without
11805   // initialization-list syntax, we might lose accuracy if the floating
11806   // point type has a narrower significand than the integer type.
11807   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11808       TargetBT->isFloatingType() && !IsListInit) {
11809     // Determine the number of precision bits in the source integer type.
11810     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11811     unsigned int SourcePrecision = SourceRange.Width;
11812 
11813     // Determine the number of precision bits in the
11814     // target floating point type.
11815     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11816         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11817 
11818     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11819         SourcePrecision > TargetPrecision) {
11820 
11821       llvm::APSInt SourceInt;
11822       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11823         // If the source integer is a constant, convert it to the target
11824         // floating point type. Issue a warning if the value changes
11825         // during the whole conversion.
11826         llvm::APFloat TargetFloatValue(
11827             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11828         llvm::APFloat::opStatus ConversionStatus =
11829             TargetFloatValue.convertFromAPInt(
11830                 SourceInt, SourceBT->isSignedInteger(),
11831                 llvm::APFloat::rmNearestTiesToEven);
11832 
11833         if (ConversionStatus != llvm::APFloat::opOK) {
11834           std::string PrettySourceValue = SourceInt.toString(10);
11835           SmallString<32> PrettyTargetValue;
11836           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11837 
11838           S.DiagRuntimeBehavior(
11839               E->getExprLoc(), E,
11840               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11841                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11842                   << E->getSourceRange() << clang::SourceRange(CC));
11843         }
11844       } else {
11845         // Otherwise, the implicit conversion may lose precision.
11846         DiagnoseImpCast(S, E, T, CC,
11847                         diag::warn_impcast_integer_float_precision);
11848       }
11849     }
11850   }
11851 
11852   DiagnoseNullConversion(S, E, T, CC);
11853 
11854   S.DiscardMisalignedMemberAddress(Target, E);
11855 
11856   if (Target->isBooleanType())
11857     DiagnoseIntInBoolContext(S, E);
11858 
11859   if (!Source->isIntegerType() || !Target->isIntegerType())
11860     return;
11861 
11862   // TODO: remove this early return once the false positives for constant->bool
11863   // in templates, macros, etc, are reduced or removed.
11864   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11865     return;
11866 
11867   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11868       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11869     return adornObjCBoolConversionDiagWithTernaryFixit(
11870         S, E,
11871         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11872             << E->getType());
11873   }
11874 
11875   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11876   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11877 
11878   if (SourceRange.Width > TargetRange.Width) {
11879     // If the source is a constant, use a default-on diagnostic.
11880     // TODO: this should happen for bitfield stores, too.
11881     Expr::EvalResult Result;
11882     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11883                          S.isConstantEvaluated())) {
11884       llvm::APSInt Value(32);
11885       Value = Result.Val.getInt();
11886 
11887       if (S.SourceMgr.isInSystemMacro(CC))
11888         return;
11889 
11890       std::string PrettySourceValue = Value.toString(10);
11891       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11892 
11893       S.DiagRuntimeBehavior(
11894           E->getExprLoc(), E,
11895           S.PDiag(diag::warn_impcast_integer_precision_constant)
11896               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11897               << E->getSourceRange() << clang::SourceRange(CC));
11898       return;
11899     }
11900 
11901     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11902     if (S.SourceMgr.isInSystemMacro(CC))
11903       return;
11904 
11905     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11906       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11907                              /* pruneControlFlow */ true);
11908     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11909   }
11910 
11911   if (TargetRange.Width > SourceRange.Width) {
11912     if (auto *UO = dyn_cast<UnaryOperator>(E))
11913       if (UO->getOpcode() == UO_Minus)
11914         if (Source->isUnsignedIntegerType()) {
11915           if (Target->isUnsignedIntegerType())
11916             return DiagnoseImpCast(S, E, T, CC,
11917                                    diag::warn_impcast_high_order_zero_bits);
11918           if (Target->isSignedIntegerType())
11919             return DiagnoseImpCast(S, E, T, CC,
11920                                    diag::warn_impcast_nonnegative_result);
11921         }
11922   }
11923 
11924   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11925       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11926     // Warn when doing a signed to signed conversion, warn if the positive
11927     // source value is exactly the width of the target type, which will
11928     // cause a negative value to be stored.
11929 
11930     Expr::EvalResult Result;
11931     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11932         !S.SourceMgr.isInSystemMacro(CC)) {
11933       llvm::APSInt Value = Result.Val.getInt();
11934       if (isSameWidthConstantConversion(S, E, T, CC)) {
11935         std::string PrettySourceValue = Value.toString(10);
11936         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11937 
11938         S.DiagRuntimeBehavior(
11939             E->getExprLoc(), E,
11940             S.PDiag(diag::warn_impcast_integer_precision_constant)
11941                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11942                 << E->getSourceRange() << clang::SourceRange(CC));
11943         return;
11944       }
11945     }
11946 
11947     // Fall through for non-constants to give a sign conversion warning.
11948   }
11949 
11950   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11951       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11952        SourceRange.Width == TargetRange.Width)) {
11953     if (S.SourceMgr.isInSystemMacro(CC))
11954       return;
11955 
11956     unsigned DiagID = diag::warn_impcast_integer_sign;
11957 
11958     // Traditionally, gcc has warned about this under -Wsign-compare.
11959     // We also want to warn about it in -Wconversion.
11960     // So if -Wconversion is off, use a completely identical diagnostic
11961     // in the sign-compare group.
11962     // The conditional-checking code will
11963     if (ICContext) {
11964       DiagID = diag::warn_impcast_integer_sign_conditional;
11965       *ICContext = true;
11966     }
11967 
11968     return DiagnoseImpCast(S, E, T, CC, DiagID);
11969   }
11970 
11971   // Diagnose conversions between different enumeration types.
11972   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11973   // type, to give us better diagnostics.
11974   QualType SourceType = E->getType();
11975   if (!S.getLangOpts().CPlusPlus) {
11976     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11977       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11978         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11979         SourceType = S.Context.getTypeDeclType(Enum);
11980         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11981       }
11982   }
11983 
11984   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11985     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11986       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11987           TargetEnum->getDecl()->hasNameForLinkage() &&
11988           SourceEnum != TargetEnum) {
11989         if (S.SourceMgr.isInSystemMacro(CC))
11990           return;
11991 
11992         return DiagnoseImpCast(S, E, SourceType, T, CC,
11993                                diag::warn_impcast_different_enum_types);
11994       }
11995 }
11996 
11997 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11998                                      SourceLocation CC, QualType T);
11999 
12000 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12001                                     SourceLocation CC, bool &ICContext) {
12002   E = E->IgnoreParenImpCasts();
12003 
12004   if (isa<ConditionalOperator>(E))
12005     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
12006 
12007   AnalyzeImplicitConversions(S, E, CC);
12008   if (E->getType() != T)
12009     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12010 }
12011 
12012 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
12013                                      SourceLocation CC, QualType T) {
12014   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12015 
12016   bool Suspicious = false;
12017   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
12018   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12019   CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
12020                                 E->getFalseExpr());
12021 
12022   if (T->isBooleanType())
12023     DiagnoseIntInBoolContext(S, E);
12024 
12025   // If -Wconversion would have warned about either of the candidates
12026   // for a signedness conversion to the context type...
12027   if (!Suspicious) return;
12028 
12029   // ...but it's currently ignored...
12030   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12031     return;
12032 
12033   // ...then check whether it would have warned about either of the
12034   // candidates for a signedness conversion to the condition type.
12035   if (E->getType() == T) return;
12036 
12037   Suspicious = false;
12038   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
12039                           E->getType(), CC, &Suspicious);
12040   if (!Suspicious)
12041     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12042                             E->getType(), CC, &Suspicious);
12043 }
12044 
12045 /// Check conversion of given expression to boolean.
12046 /// Input argument E is a logical expression.
12047 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12048   if (S.getLangOpts().Bool)
12049     return;
12050   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12051     return;
12052   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12053 }
12054 
12055 /// AnalyzeImplicitConversions - Find and report any interesting
12056 /// implicit conversions in the given expression.  There are a couple
12057 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12058 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12059                                        bool IsListInit/*= false*/) {
12060   QualType T = OrigE->getType();
12061   Expr *E = OrigE->IgnoreParenImpCasts();
12062 
12063   // Propagate whether we are in a C++ list initialization expression.
12064   // If so, we do not issue warnings for implicit int-float conversion
12065   // precision loss, because C++11 narrowing already handles it.
12066   IsListInit =
12067       IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12068 
12069   if (E->isTypeDependent() || E->isValueDependent())
12070     return;
12071 
12072   if (const auto *UO = dyn_cast<UnaryOperator>(E))
12073     if (UO->getOpcode() == UO_Not &&
12074         UO->getSubExpr()->isKnownToHaveBooleanValue())
12075       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12076           << OrigE->getSourceRange() << T->isBooleanType()
12077           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12078 
12079   // For conditional operators, we analyze the arguments as if they
12080   // were being fed directly into the output.
12081   if (isa<ConditionalOperator>(E)) {
12082     ConditionalOperator *CO = cast<ConditionalOperator>(E);
12083     CheckConditionalOperator(S, CO, CC, T);
12084     return;
12085   }
12086 
12087   // Check implicit argument conversions for function calls.
12088   if (CallExpr *Call = dyn_cast<CallExpr>(E))
12089     CheckImplicitArgumentConversions(S, Call, CC);
12090 
12091   // Go ahead and check any implicit conversions we might have skipped.
12092   // The non-canonical typecheck is just an optimization;
12093   // CheckImplicitConversion will filter out dead implicit conversions.
12094   if (E->getType() != T)
12095     CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
12096 
12097   // Now continue drilling into this expression.
12098 
12099   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12100     // The bound subexpressions in a PseudoObjectExpr are not reachable
12101     // as transitive children.
12102     // FIXME: Use a more uniform representation for this.
12103     for (auto *SE : POE->semantics())
12104       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12105         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
12106   }
12107 
12108   // Skip past explicit casts.
12109   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12110     E = CE->getSubExpr()->IgnoreParenImpCasts();
12111     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12112       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12113     return AnalyzeImplicitConversions(S, E, CC, IsListInit);
12114   }
12115 
12116   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12117     // Do a somewhat different check with comparison operators.
12118     if (BO->isComparisonOp())
12119       return AnalyzeComparison(S, BO);
12120 
12121     // And with simple assignments.
12122     if (BO->getOpcode() == BO_Assign)
12123       return AnalyzeAssignment(S, BO);
12124     // And with compound assignments.
12125     if (BO->isAssignmentOp())
12126       return AnalyzeCompoundAssignment(S, BO);
12127   }
12128 
12129   // These break the otherwise-useful invariant below.  Fortunately,
12130   // we don't really need to recurse into them, because any internal
12131   // expressions should have been analyzed already when they were
12132   // built into statements.
12133   if (isa<StmtExpr>(E)) return;
12134 
12135   // Don't descend into unevaluated contexts.
12136   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12137 
12138   // Now just recurse over the expression's children.
12139   CC = E->getExprLoc();
12140   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12141   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12142   for (Stmt *SubStmt : E->children()) {
12143     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12144     if (!ChildExpr)
12145       continue;
12146 
12147     if (IsLogicalAndOperator &&
12148         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12149       // Ignore checking string literals that are in logical and operators.
12150       // This is a common pattern for asserts.
12151       continue;
12152     AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
12153   }
12154 
12155   if (BO && BO->isLogicalOp()) {
12156     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12157     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12158       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12159 
12160     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12161     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12162       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12163   }
12164 
12165   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12166     if (U->getOpcode() == UO_LNot) {
12167       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12168     } else if (U->getOpcode() != UO_AddrOf) {
12169       if (U->getSubExpr()->getType()->isAtomicType())
12170         S.Diag(U->getSubExpr()->getBeginLoc(),
12171                diag::warn_atomic_implicit_seq_cst);
12172     }
12173   }
12174 }
12175 
12176 /// Diagnose integer type and any valid implicit conversion to it.
12177 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12178   // Taking into account implicit conversions,
12179   // allow any integer.
12180   if (!E->getType()->isIntegerType()) {
12181     S.Diag(E->getBeginLoc(),
12182            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12183     return true;
12184   }
12185   // Potentially emit standard warnings for implicit conversions if enabled
12186   // using -Wconversion.
12187   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12188   return false;
12189 }
12190 
12191 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12192 // Returns true when emitting a warning about taking the address of a reference.
12193 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12194                               const PartialDiagnostic &PD) {
12195   E = E->IgnoreParenImpCasts();
12196 
12197   const FunctionDecl *FD = nullptr;
12198 
12199   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12200     if (!DRE->getDecl()->getType()->isReferenceType())
12201       return false;
12202   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12203     if (!M->getMemberDecl()->getType()->isReferenceType())
12204       return false;
12205   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12206     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12207       return false;
12208     FD = Call->getDirectCallee();
12209   } else {
12210     return false;
12211   }
12212 
12213   SemaRef.Diag(E->getExprLoc(), PD);
12214 
12215   // If possible, point to location of function.
12216   if (FD) {
12217     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12218   }
12219 
12220   return true;
12221 }
12222 
12223 // Returns true if the SourceLocation is expanded from any macro body.
12224 // Returns false if the SourceLocation is invalid, is from not in a macro
12225 // expansion, or is from expanded from a top-level macro argument.
12226 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12227   if (Loc.isInvalid())
12228     return false;
12229 
12230   while (Loc.isMacroID()) {
12231     if (SM.isMacroBodyExpansion(Loc))
12232       return true;
12233     Loc = SM.getImmediateMacroCallerLoc(Loc);
12234   }
12235 
12236   return false;
12237 }
12238 
12239 /// Diagnose pointers that are always non-null.
12240 /// \param E the expression containing the pointer
12241 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12242 /// compared to a null pointer
12243 /// \param IsEqual True when the comparison is equal to a null pointer
12244 /// \param Range Extra SourceRange to highlight in the diagnostic
12245 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12246                                         Expr::NullPointerConstantKind NullKind,
12247                                         bool IsEqual, SourceRange Range) {
12248   if (!E)
12249     return;
12250 
12251   // Don't warn inside macros.
12252   if (E->getExprLoc().isMacroID()) {
12253     const SourceManager &SM = getSourceManager();
12254     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12255         IsInAnyMacroBody(SM, Range.getBegin()))
12256       return;
12257   }
12258   E = E->IgnoreImpCasts();
12259 
12260   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12261 
12262   if (isa<CXXThisExpr>(E)) {
12263     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12264                                 : diag::warn_this_bool_conversion;
12265     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12266     return;
12267   }
12268 
12269   bool IsAddressOf = false;
12270 
12271   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12272     if (UO->getOpcode() != UO_AddrOf)
12273       return;
12274     IsAddressOf = true;
12275     E = UO->getSubExpr();
12276   }
12277 
12278   if (IsAddressOf) {
12279     unsigned DiagID = IsCompare
12280                           ? diag::warn_address_of_reference_null_compare
12281                           : diag::warn_address_of_reference_bool_conversion;
12282     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12283                                          << IsEqual;
12284     if (CheckForReference(*this, E, PD)) {
12285       return;
12286     }
12287   }
12288 
12289   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12290     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12291     std::string Str;
12292     llvm::raw_string_ostream S(Str);
12293     E->printPretty(S, nullptr, getPrintingPolicy());
12294     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12295                                 : diag::warn_cast_nonnull_to_bool;
12296     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12297       << E->getSourceRange() << Range << IsEqual;
12298     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12299   };
12300 
12301   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12302   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12303     if (auto *Callee = Call->getDirectCallee()) {
12304       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12305         ComplainAboutNonnullParamOrCall(A);
12306         return;
12307       }
12308     }
12309   }
12310 
12311   // Expect to find a single Decl.  Skip anything more complicated.
12312   ValueDecl *D = nullptr;
12313   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12314     D = R->getDecl();
12315   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12316     D = M->getMemberDecl();
12317   }
12318 
12319   // Weak Decls can be null.
12320   if (!D || D->isWeak())
12321     return;
12322 
12323   // Check for parameter decl with nonnull attribute
12324   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12325     if (getCurFunction() &&
12326         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12327       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12328         ComplainAboutNonnullParamOrCall(A);
12329         return;
12330       }
12331 
12332       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12333         // Skip function template not specialized yet.
12334         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12335           return;
12336         auto ParamIter = llvm::find(FD->parameters(), PV);
12337         assert(ParamIter != FD->param_end());
12338         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12339 
12340         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12341           if (!NonNull->args_size()) {
12342               ComplainAboutNonnullParamOrCall(NonNull);
12343               return;
12344           }
12345 
12346           for (const ParamIdx &ArgNo : NonNull->args()) {
12347             if (ArgNo.getASTIndex() == ParamNo) {
12348               ComplainAboutNonnullParamOrCall(NonNull);
12349               return;
12350             }
12351           }
12352         }
12353       }
12354     }
12355   }
12356 
12357   QualType T = D->getType();
12358   const bool IsArray = T->isArrayType();
12359   const bool IsFunction = T->isFunctionType();
12360 
12361   // Address of function is used to silence the function warning.
12362   if (IsAddressOf && IsFunction) {
12363     return;
12364   }
12365 
12366   // Found nothing.
12367   if (!IsAddressOf && !IsFunction && !IsArray)
12368     return;
12369 
12370   // Pretty print the expression for the diagnostic.
12371   std::string Str;
12372   llvm::raw_string_ostream S(Str);
12373   E->printPretty(S, nullptr, getPrintingPolicy());
12374 
12375   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12376                               : diag::warn_impcast_pointer_to_bool;
12377   enum {
12378     AddressOf,
12379     FunctionPointer,
12380     ArrayPointer
12381   } DiagType;
12382   if (IsAddressOf)
12383     DiagType = AddressOf;
12384   else if (IsFunction)
12385     DiagType = FunctionPointer;
12386   else if (IsArray)
12387     DiagType = ArrayPointer;
12388   else
12389     llvm_unreachable("Could not determine diagnostic.");
12390   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12391                                 << Range << IsEqual;
12392 
12393   if (!IsFunction)
12394     return;
12395 
12396   // Suggest '&' to silence the function warning.
12397   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12398       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12399 
12400   // Check to see if '()' fixit should be emitted.
12401   QualType ReturnType;
12402   UnresolvedSet<4> NonTemplateOverloads;
12403   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12404   if (ReturnType.isNull())
12405     return;
12406 
12407   if (IsCompare) {
12408     // There are two cases here.  If there is null constant, the only suggest
12409     // for a pointer return type.  If the null is 0, then suggest if the return
12410     // type is a pointer or an integer type.
12411     if (!ReturnType->isPointerType()) {
12412       if (NullKind == Expr::NPCK_ZeroExpression ||
12413           NullKind == Expr::NPCK_ZeroLiteral) {
12414         if (!ReturnType->isIntegerType())
12415           return;
12416       } else {
12417         return;
12418       }
12419     }
12420   } else { // !IsCompare
12421     // For function to bool, only suggest if the function pointer has bool
12422     // return type.
12423     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12424       return;
12425   }
12426   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12427       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12428 }
12429 
12430 /// Diagnoses "dangerous" implicit conversions within the given
12431 /// expression (which is a full expression).  Implements -Wconversion
12432 /// and -Wsign-compare.
12433 ///
12434 /// \param CC the "context" location of the implicit conversion, i.e.
12435 ///   the most location of the syntactic entity requiring the implicit
12436 ///   conversion
12437 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12438   // Don't diagnose in unevaluated contexts.
12439   if (isUnevaluatedContext())
12440     return;
12441 
12442   // Don't diagnose for value- or type-dependent expressions.
12443   if (E->isTypeDependent() || E->isValueDependent())
12444     return;
12445 
12446   // Check for array bounds violations in cases where the check isn't triggered
12447   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12448   // ArraySubscriptExpr is on the RHS of a variable initialization.
12449   CheckArrayAccess(E);
12450 
12451   // This is not the right CC for (e.g.) a variable initialization.
12452   AnalyzeImplicitConversions(*this, E, CC);
12453 }
12454 
12455 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12456 /// Input argument E is a logical expression.
12457 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12458   ::CheckBoolLikeConversion(*this, E, CC);
12459 }
12460 
12461 /// Diagnose when expression is an integer constant expression and its evaluation
12462 /// results in integer overflow
12463 void Sema::CheckForIntOverflow (Expr *E) {
12464   // Use a work list to deal with nested struct initializers.
12465   SmallVector<Expr *, 2> Exprs(1, E);
12466 
12467   do {
12468     Expr *OriginalE = Exprs.pop_back_val();
12469     Expr *E = OriginalE->IgnoreParenCasts();
12470 
12471     if (isa<BinaryOperator>(E)) {
12472       E->EvaluateForOverflow(Context);
12473       continue;
12474     }
12475 
12476     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12477       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12478     else if (isa<ObjCBoxedExpr>(OriginalE))
12479       E->EvaluateForOverflow(Context);
12480     else if (auto Call = dyn_cast<CallExpr>(E))
12481       Exprs.append(Call->arg_begin(), Call->arg_end());
12482     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12483       Exprs.append(Message->arg_begin(), Message->arg_end());
12484   } while (!Exprs.empty());
12485 }
12486 
12487 namespace {
12488 
12489 /// Visitor for expressions which looks for unsequenced operations on the
12490 /// same object.
12491 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
12492   using Base = EvaluatedExprVisitor<SequenceChecker>;
12493 
12494   /// A tree of sequenced regions within an expression. Two regions are
12495   /// unsequenced if one is an ancestor or a descendent of the other. When we
12496   /// finish processing an expression with sequencing, such as a comma
12497   /// expression, we fold its tree nodes into its parent, since they are
12498   /// unsequenced with respect to nodes we will visit later.
12499   class SequenceTree {
12500     struct Value {
12501       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12502       unsigned Parent : 31;
12503       unsigned Merged : 1;
12504     };
12505     SmallVector<Value, 8> Values;
12506 
12507   public:
12508     /// A region within an expression which may be sequenced with respect
12509     /// to some other region.
12510     class Seq {
12511       friend class SequenceTree;
12512 
12513       unsigned Index;
12514 
12515       explicit Seq(unsigned N) : Index(N) {}
12516 
12517     public:
12518       Seq() : Index(0) {}
12519     };
12520 
12521     SequenceTree() { Values.push_back(Value(0)); }
12522     Seq root() const { return Seq(0); }
12523 
12524     /// Create a new sequence of operations, which is an unsequenced
12525     /// subset of \p Parent. This sequence of operations is sequenced with
12526     /// respect to other children of \p Parent.
12527     Seq allocate(Seq Parent) {
12528       Values.push_back(Value(Parent.Index));
12529       return Seq(Values.size() - 1);
12530     }
12531 
12532     /// Merge a sequence of operations into its parent.
12533     void merge(Seq S) {
12534       Values[S.Index].Merged = true;
12535     }
12536 
12537     /// Determine whether two operations are unsequenced. This operation
12538     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12539     /// should have been merged into its parent as appropriate.
12540     bool isUnsequenced(Seq Cur, Seq Old) {
12541       unsigned C = representative(Cur.Index);
12542       unsigned Target = representative(Old.Index);
12543       while (C >= Target) {
12544         if (C == Target)
12545           return true;
12546         C = Values[C].Parent;
12547       }
12548       return false;
12549     }
12550 
12551   private:
12552     /// Pick a representative for a sequence.
12553     unsigned representative(unsigned K) {
12554       if (Values[K].Merged)
12555         // Perform path compression as we go.
12556         return Values[K].Parent = representative(Values[K].Parent);
12557       return K;
12558     }
12559   };
12560 
12561   /// An object for which we can track unsequenced uses.
12562   using Object = NamedDecl *;
12563 
12564   /// Different flavors of object usage which we track. We only track the
12565   /// least-sequenced usage of each kind.
12566   enum UsageKind {
12567     /// A read of an object. Multiple unsequenced reads are OK.
12568     UK_Use,
12569 
12570     /// A modification of an object which is sequenced before the value
12571     /// computation of the expression, such as ++n in C++.
12572     UK_ModAsValue,
12573 
12574     /// A modification of an object which is not sequenced before the value
12575     /// computation of the expression, such as n++.
12576     UK_ModAsSideEffect,
12577 
12578     UK_Count = UK_ModAsSideEffect + 1
12579   };
12580 
12581   struct Usage {
12582     Expr *Use;
12583     SequenceTree::Seq Seq;
12584 
12585     Usage() : Use(nullptr), Seq() {}
12586   };
12587 
12588   struct UsageInfo {
12589     Usage Uses[UK_Count];
12590 
12591     /// Have we issued a diagnostic for this variable already?
12592     bool Diagnosed;
12593 
12594     UsageInfo() : Uses(), Diagnosed(false) {}
12595   };
12596   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12597 
12598   Sema &SemaRef;
12599 
12600   /// Sequenced regions within the expression.
12601   SequenceTree Tree;
12602 
12603   /// Declaration modifications and references which we have seen.
12604   UsageInfoMap UsageMap;
12605 
12606   /// The region we are currently within.
12607   SequenceTree::Seq Region;
12608 
12609   /// Filled in with declarations which were modified as a side-effect
12610   /// (that is, post-increment operations).
12611   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12612 
12613   /// Expressions to check later. We defer checking these to reduce
12614   /// stack usage.
12615   SmallVectorImpl<Expr *> &WorkList;
12616 
12617   /// RAII object wrapping the visitation of a sequenced subexpression of an
12618   /// expression. At the end of this process, the side-effects of the evaluation
12619   /// become sequenced with respect to the value computation of the result, so
12620   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12621   /// UK_ModAsValue.
12622   struct SequencedSubexpression {
12623     SequencedSubexpression(SequenceChecker &Self)
12624       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12625       Self.ModAsSideEffect = &ModAsSideEffect;
12626     }
12627 
12628     ~SequencedSubexpression() {
12629       for (auto &M : llvm::reverse(ModAsSideEffect)) {
12630         UsageInfo &U = Self.UsageMap[M.first];
12631         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
12632         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12633         SideEffectUsage = M.second;
12634       }
12635       Self.ModAsSideEffect = OldModAsSideEffect;
12636     }
12637 
12638     SequenceChecker &Self;
12639     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12640     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12641   };
12642 
12643   /// RAII object wrapping the visitation of a subexpression which we might
12644   /// choose to evaluate as a constant. If any subexpression is evaluated and
12645   /// found to be non-constant, this allows us to suppress the evaluation of
12646   /// the outer expression.
12647   class EvaluationTracker {
12648   public:
12649     EvaluationTracker(SequenceChecker &Self)
12650         : Self(Self), Prev(Self.EvalTracker) {
12651       Self.EvalTracker = this;
12652     }
12653 
12654     ~EvaluationTracker() {
12655       Self.EvalTracker = Prev;
12656       if (Prev)
12657         Prev->EvalOK &= EvalOK;
12658     }
12659 
12660     bool evaluate(const Expr *E, bool &Result) {
12661       if (!EvalOK || E->isValueDependent())
12662         return false;
12663       EvalOK = E->EvaluateAsBooleanCondition(
12664           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12665       return EvalOK;
12666     }
12667 
12668   private:
12669     SequenceChecker &Self;
12670     EvaluationTracker *Prev;
12671     bool EvalOK = true;
12672   } *EvalTracker = nullptr;
12673 
12674   /// Find the object which is produced by the specified expression,
12675   /// if any.
12676   Object getObject(Expr *E, bool Mod) const {
12677     E = E->IgnoreParenCasts();
12678     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12679       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12680         return getObject(UO->getSubExpr(), Mod);
12681     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12682       if (BO->getOpcode() == BO_Comma)
12683         return getObject(BO->getRHS(), Mod);
12684       if (Mod && BO->isAssignmentOp())
12685         return getObject(BO->getLHS(), Mod);
12686     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12687       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12688       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12689         return ME->getMemberDecl();
12690     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12691       // FIXME: If this is a reference, map through to its value.
12692       return DRE->getDecl();
12693     return nullptr;
12694   }
12695 
12696   /// Note that an object was modified or used by an expression.
12697   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12698     Usage &U = UI.Uses[UK];
12699     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12700       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12701         ModAsSideEffect->push_back(std::make_pair(O, U));
12702       U.Use = Ref;
12703       U.Seq = Region;
12704     }
12705   }
12706 
12707   /// Check whether a modification or use conflicts with a prior usage.
12708   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12709                   bool IsModMod) {
12710     if (UI.Diagnosed)
12711       return;
12712 
12713     const Usage &U = UI.Uses[OtherKind];
12714     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12715       return;
12716 
12717     Expr *Mod = U.Use;
12718     Expr *ModOrUse = Ref;
12719     if (OtherKind == UK_Use)
12720       std::swap(Mod, ModOrUse);
12721 
12722     SemaRef.DiagRuntimeBehavior(
12723         Mod->getExprLoc(), {Mod, ModOrUse},
12724         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12725                                : diag::warn_unsequenced_mod_use)
12726             << O << SourceRange(ModOrUse->getExprLoc()));
12727     UI.Diagnosed = true;
12728   }
12729 
12730   void notePreUse(Object O, Expr *Use) {
12731     UsageInfo &U = UsageMap[O];
12732     // Uses conflict with other modifications.
12733     checkUsage(O, U, Use, UK_ModAsValue, false);
12734   }
12735 
12736   void notePostUse(Object O, Expr *Use) {
12737     UsageInfo &U = UsageMap[O];
12738     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12739     addUsage(U, O, Use, UK_Use);
12740   }
12741 
12742   void notePreMod(Object O, Expr *Mod) {
12743     UsageInfo &U = UsageMap[O];
12744     // Modifications conflict with other modifications and with uses.
12745     checkUsage(O, U, Mod, UK_ModAsValue, true);
12746     checkUsage(O, U, Mod, UK_Use, false);
12747   }
12748 
12749   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12750     UsageInfo &U = UsageMap[O];
12751     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12752     addUsage(U, O, Use, UK);
12753   }
12754 
12755 public:
12756   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12757       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12758     Visit(E);
12759   }
12760 
12761   void VisitStmt(Stmt *S) {
12762     // Skip all statements which aren't expressions for now.
12763   }
12764 
12765   void VisitExpr(Expr *E) {
12766     // By default, just recurse to evaluated subexpressions.
12767     Base::VisitStmt(E);
12768   }
12769 
12770   void VisitCastExpr(CastExpr *E) {
12771     Object O = Object();
12772     if (E->getCastKind() == CK_LValueToRValue)
12773       O = getObject(E->getSubExpr(), false);
12774 
12775     if (O)
12776       notePreUse(O, E);
12777     VisitExpr(E);
12778     if (O)
12779       notePostUse(O, E);
12780   }
12781 
12782   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12783     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12784     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12785     SequenceTree::Seq OldRegion = Region;
12786 
12787     {
12788       SequencedSubexpression SeqBefore(*this);
12789       Region = BeforeRegion;
12790       Visit(SequencedBefore);
12791     }
12792 
12793     Region = AfterRegion;
12794     Visit(SequencedAfter);
12795 
12796     Region = OldRegion;
12797 
12798     Tree.merge(BeforeRegion);
12799     Tree.merge(AfterRegion);
12800   }
12801 
12802   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12803     // C++17 [expr.sub]p1:
12804     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12805     //   expression E1 is sequenced before the expression E2.
12806     if (SemaRef.getLangOpts().CPlusPlus17)
12807       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12808     else
12809       Base::VisitStmt(ASE);
12810   }
12811 
12812   void VisitBinComma(BinaryOperator *BO) {
12813     // C++11 [expr.comma]p1:
12814     //   Every value computation and side effect associated with the left
12815     //   expression is sequenced before every value computation and side
12816     //   effect associated with the right expression.
12817     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12818   }
12819 
12820   void VisitBinAssign(BinaryOperator *BO) {
12821     // The modification is sequenced after the value computation of the LHS
12822     // and RHS, so check it before inspecting the operands and update the
12823     // map afterwards.
12824     Object O = getObject(BO->getLHS(), true);
12825     if (!O)
12826       return VisitExpr(BO);
12827 
12828     notePreMod(O, BO);
12829 
12830     // C++11 [expr.ass]p7:
12831     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12832     //   only once.
12833     //
12834     // Therefore, for a compound assignment operator, O is considered used
12835     // everywhere except within the evaluation of E1 itself.
12836     if (isa<CompoundAssignOperator>(BO))
12837       notePreUse(O, BO);
12838 
12839     Visit(BO->getLHS());
12840 
12841     if (isa<CompoundAssignOperator>(BO))
12842       notePostUse(O, BO);
12843 
12844     Visit(BO->getRHS());
12845 
12846     // C++11 [expr.ass]p1:
12847     //   the assignment is sequenced [...] before the value computation of the
12848     //   assignment expression.
12849     // C11 6.5.16/3 has no such rule.
12850     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12851                                                        : UK_ModAsSideEffect);
12852   }
12853 
12854   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12855     VisitBinAssign(CAO);
12856   }
12857 
12858   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12859   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12860   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12861     Object O = getObject(UO->getSubExpr(), true);
12862     if (!O)
12863       return VisitExpr(UO);
12864 
12865     notePreMod(O, UO);
12866     Visit(UO->getSubExpr());
12867     // C++11 [expr.pre.incr]p1:
12868     //   the expression ++x is equivalent to x+=1
12869     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12870                                                        : UK_ModAsSideEffect);
12871   }
12872 
12873   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12874   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12875   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12876     Object O = getObject(UO->getSubExpr(), true);
12877     if (!O)
12878       return VisitExpr(UO);
12879 
12880     notePreMod(O, UO);
12881     Visit(UO->getSubExpr());
12882     notePostMod(O, UO, UK_ModAsSideEffect);
12883   }
12884 
12885   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12886   void VisitBinLOr(BinaryOperator *BO) {
12887     // The side-effects of the LHS of an '&&' are sequenced before the
12888     // value computation of the RHS, and hence before the value computation
12889     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12890     // as if they were unconditionally sequenced.
12891     EvaluationTracker Eval(*this);
12892     {
12893       SequencedSubexpression Sequenced(*this);
12894       Visit(BO->getLHS());
12895     }
12896 
12897     bool Result;
12898     if (Eval.evaluate(BO->getLHS(), Result)) {
12899       if (!Result)
12900         Visit(BO->getRHS());
12901     } else {
12902       // Check for unsequenced operations in the RHS, treating it as an
12903       // entirely separate evaluation.
12904       //
12905       // FIXME: If there are operations in the RHS which are unsequenced
12906       // with respect to operations outside the RHS, and those operations
12907       // are unconditionally evaluated, diagnose them.
12908       WorkList.push_back(BO->getRHS());
12909     }
12910   }
12911   void VisitBinLAnd(BinaryOperator *BO) {
12912     EvaluationTracker Eval(*this);
12913     {
12914       SequencedSubexpression Sequenced(*this);
12915       Visit(BO->getLHS());
12916     }
12917 
12918     bool Result;
12919     if (Eval.evaluate(BO->getLHS(), Result)) {
12920       if (Result)
12921         Visit(BO->getRHS());
12922     } else {
12923       WorkList.push_back(BO->getRHS());
12924     }
12925   }
12926 
12927   // Only visit the condition, unless we can be sure which subexpression will
12928   // be chosen.
12929   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12930     EvaluationTracker Eval(*this);
12931     {
12932       SequencedSubexpression Sequenced(*this);
12933       Visit(CO->getCond());
12934     }
12935 
12936     bool Result;
12937     if (Eval.evaluate(CO->getCond(), Result))
12938       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12939     else {
12940       WorkList.push_back(CO->getTrueExpr());
12941       WorkList.push_back(CO->getFalseExpr());
12942     }
12943   }
12944 
12945   void VisitCallExpr(CallExpr *CE) {
12946     // C++11 [intro.execution]p15:
12947     //   When calling a function [...], every value computation and side effect
12948     //   associated with any argument expression, or with the postfix expression
12949     //   designating the called function, is sequenced before execution of every
12950     //   expression or statement in the body of the function [and thus before
12951     //   the value computation of its result].
12952     SequencedSubexpression Sequenced(*this);
12953     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(),
12954                                         [&] { Base::VisitCallExpr(CE); });
12955 
12956     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12957   }
12958 
12959   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12960     // This is a call, so all subexpressions are sequenced before the result.
12961     SequencedSubexpression Sequenced(*this);
12962 
12963     if (!CCE->isListInitialization())
12964       return VisitExpr(CCE);
12965 
12966     // In C++11, list initializations are sequenced.
12967     SmallVector<SequenceTree::Seq, 32> Elts;
12968     SequenceTree::Seq Parent = Region;
12969     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12970                                         E = CCE->arg_end();
12971          I != E; ++I) {
12972       Region = Tree.allocate(Parent);
12973       Elts.push_back(Region);
12974       Visit(*I);
12975     }
12976 
12977     // Forget that the initializers are sequenced.
12978     Region = Parent;
12979     for (unsigned I = 0; I < Elts.size(); ++I)
12980       Tree.merge(Elts[I]);
12981   }
12982 
12983   void VisitInitListExpr(InitListExpr *ILE) {
12984     if (!SemaRef.getLangOpts().CPlusPlus11)
12985       return VisitExpr(ILE);
12986 
12987     // In C++11, list initializations are sequenced.
12988     SmallVector<SequenceTree::Seq, 32> Elts;
12989     SequenceTree::Seq Parent = Region;
12990     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12991       Expr *E = ILE->getInit(I);
12992       if (!E) continue;
12993       Region = Tree.allocate(Parent);
12994       Elts.push_back(Region);
12995       Visit(E);
12996     }
12997 
12998     // Forget that the initializers are sequenced.
12999     Region = Parent;
13000     for (unsigned I = 0; I < Elts.size(); ++I)
13001       Tree.merge(Elts[I]);
13002   }
13003 };
13004 
13005 } // namespace
13006 
13007 void Sema::CheckUnsequencedOperations(Expr *E) {
13008   SmallVector<Expr *, 8> WorkList;
13009   WorkList.push_back(E);
13010   while (!WorkList.empty()) {
13011     Expr *Item = WorkList.pop_back_val();
13012     SequenceChecker(*this, Item, WorkList);
13013   }
13014 }
13015 
13016 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13017                               bool IsConstexpr) {
13018   llvm::SaveAndRestore<bool> ConstantContext(
13019       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13020   CheckImplicitConversions(E, CheckLoc);
13021   if (!E->isInstantiationDependent())
13022     CheckUnsequencedOperations(E);
13023   if (!IsConstexpr && !E->isValueDependent())
13024     CheckForIntOverflow(E);
13025   DiagnoseMisalignedMembers();
13026 }
13027 
13028 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13029                                        FieldDecl *BitField,
13030                                        Expr *Init) {
13031   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13032 }
13033 
13034 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13035                                          SourceLocation Loc) {
13036   if (!PType->isVariablyModifiedType())
13037     return;
13038   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13039     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13040     return;
13041   }
13042   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13043     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13044     return;
13045   }
13046   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13047     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13048     return;
13049   }
13050 
13051   const ArrayType *AT = S.Context.getAsArrayType(PType);
13052   if (!AT)
13053     return;
13054 
13055   if (AT->getSizeModifier() != ArrayType::Star) {
13056     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13057     return;
13058   }
13059 
13060   S.Diag(Loc, diag::err_array_star_in_function_definition);
13061 }
13062 
13063 /// CheckParmsForFunctionDef - Check that the parameters of the given
13064 /// function are appropriate for the definition of a function. This
13065 /// takes care of any checks that cannot be performed on the
13066 /// declaration itself, e.g., that the types of each of the function
13067 /// parameters are complete.
13068 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13069                                     bool CheckParameterNames) {
13070   bool HasInvalidParm = false;
13071   for (ParmVarDecl *Param : Parameters) {
13072     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13073     // function declarator that is part of a function definition of
13074     // that function shall not have incomplete type.
13075     //
13076     // This is also C++ [dcl.fct]p6.
13077     if (!Param->isInvalidDecl() &&
13078         RequireCompleteType(Param->getLocation(), Param->getType(),
13079                             diag::err_typecheck_decl_incomplete_type)) {
13080       Param->setInvalidDecl();
13081       HasInvalidParm = true;
13082     }
13083 
13084     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13085     // declaration of each parameter shall include an identifier.
13086     if (CheckParameterNames &&
13087         Param->getIdentifier() == nullptr &&
13088         !Param->isImplicit() &&
13089         !getLangOpts().CPlusPlus)
13090       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13091 
13092     // C99 6.7.5.3p12:
13093     //   If the function declarator is not part of a definition of that
13094     //   function, parameters may have incomplete type and may use the [*]
13095     //   notation in their sequences of declarator specifiers to specify
13096     //   variable length array types.
13097     QualType PType = Param->getOriginalType();
13098     // FIXME: This diagnostic should point the '[*]' if source-location
13099     // information is added for it.
13100     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13101 
13102     // If the parameter is a c++ class type and it has to be destructed in the
13103     // callee function, declare the destructor so that it can be called by the
13104     // callee function. Do not perform any direct access check on the dtor here.
13105     if (!Param->isInvalidDecl()) {
13106       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13107         if (!ClassDecl->isInvalidDecl() &&
13108             !ClassDecl->hasIrrelevantDestructor() &&
13109             !ClassDecl->isDependentContext() &&
13110             ClassDecl->isParamDestroyedInCallee()) {
13111           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13112           MarkFunctionReferenced(Param->getLocation(), Destructor);
13113           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13114         }
13115       }
13116     }
13117 
13118     // Parameters with the pass_object_size attribute only need to be marked
13119     // constant at function definitions. Because we lack information about
13120     // whether we're on a declaration or definition when we're instantiating the
13121     // attribute, we need to check for constness here.
13122     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13123       if (!Param->getType().isConstQualified())
13124         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13125             << Attr->getSpelling() << 1;
13126 
13127     // Check for parameter names shadowing fields from the class.
13128     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13129       // The owning context for the parameter should be the function, but we
13130       // want to see if this function's declaration context is a record.
13131       DeclContext *DC = Param->getDeclContext();
13132       if (DC && DC->isFunctionOrMethod()) {
13133         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13134           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13135                                      RD, /*DeclIsField*/ false);
13136       }
13137     }
13138   }
13139 
13140   return HasInvalidParm;
13141 }
13142 
13143 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
13144 /// or MemberExpr.
13145 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
13146                               ASTContext &Context) {
13147   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
13148     return Context.getDeclAlign(DRE->getDecl());
13149 
13150   if (const auto *ME = dyn_cast<MemberExpr>(E))
13151     return Context.getDeclAlign(ME->getMemberDecl());
13152 
13153   return TypeAlign;
13154 }
13155 
13156 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13157 /// pointer cast increases the alignment requirements.
13158 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13159   // This is actually a lot of work to potentially be doing on every
13160   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13161   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13162     return;
13163 
13164   // Ignore dependent types.
13165   if (T->isDependentType() || Op->getType()->isDependentType())
13166     return;
13167 
13168   // Require that the destination be a pointer type.
13169   const PointerType *DestPtr = T->getAs<PointerType>();
13170   if (!DestPtr) return;
13171 
13172   // If the destination has alignment 1, we're done.
13173   QualType DestPointee = DestPtr->getPointeeType();
13174   if (DestPointee->isIncompleteType()) return;
13175   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13176   if (DestAlign.isOne()) return;
13177 
13178   // Require that the source be a pointer type.
13179   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13180   if (!SrcPtr) return;
13181   QualType SrcPointee = SrcPtr->getPointeeType();
13182 
13183   // Whitelist casts from cv void*.  We already implicitly
13184   // whitelisted casts to cv void*, since they have alignment 1.
13185   // Also whitelist casts involving incomplete types, which implicitly
13186   // includes 'void'.
13187   if (SrcPointee->isIncompleteType()) return;
13188 
13189   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13190 
13191   if (auto *CE = dyn_cast<CastExpr>(Op)) {
13192     if (CE->getCastKind() == CK_ArrayToPointerDecay)
13193       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13194   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13195     if (UO->getOpcode() == UO_AddrOf)
13196       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13197   }
13198 
13199   if (SrcAlign >= DestAlign) return;
13200 
13201   Diag(TRange.getBegin(), diag::warn_cast_align)
13202     << Op->getType() << T
13203     << static_cast<unsigned>(SrcAlign.getQuantity())
13204     << static_cast<unsigned>(DestAlign.getQuantity())
13205     << TRange << Op->getSourceRange();
13206 }
13207 
13208 /// Check whether this array fits the idiom of a size-one tail padded
13209 /// array member of a struct.
13210 ///
13211 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13212 /// commonly used to emulate flexible arrays in C89 code.
13213 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13214                                     const NamedDecl *ND) {
13215   if (Size != 1 || !ND) return false;
13216 
13217   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13218   if (!FD) return false;
13219 
13220   // Don't consider sizes resulting from macro expansions or template argument
13221   // substitution to form C89 tail-padded arrays.
13222 
13223   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13224   while (TInfo) {
13225     TypeLoc TL = TInfo->getTypeLoc();
13226     // Look through typedefs.
13227     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13228       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13229       TInfo = TDL->getTypeSourceInfo();
13230       continue;
13231     }
13232     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13233       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13234       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13235         return false;
13236     }
13237     break;
13238   }
13239 
13240   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13241   if (!RD) return false;
13242   if (RD->isUnion()) return false;
13243   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13244     if (!CRD->isStandardLayout()) return false;
13245   }
13246 
13247   // See if this is the last field decl in the record.
13248   const Decl *D = FD;
13249   while ((D = D->getNextDeclInContext()))
13250     if (isa<FieldDecl>(D))
13251       return false;
13252   return true;
13253 }
13254 
13255 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13256                             const ArraySubscriptExpr *ASE,
13257                             bool AllowOnePastEnd, bool IndexNegated) {
13258   // Already diagnosed by the constant evaluator.
13259   if (isConstantEvaluated())
13260     return;
13261 
13262   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13263   if (IndexExpr->isValueDependent())
13264     return;
13265 
13266   const Type *EffectiveType =
13267       BaseExpr->getType()->getPointeeOrArrayElementType();
13268   BaseExpr = BaseExpr->IgnoreParenCasts();
13269   const ConstantArrayType *ArrayTy =
13270       Context.getAsConstantArrayType(BaseExpr->getType());
13271 
13272   if (!ArrayTy)
13273     return;
13274 
13275   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13276   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13277     return;
13278 
13279   Expr::EvalResult Result;
13280   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13281     return;
13282 
13283   llvm::APSInt index = Result.Val.getInt();
13284   if (IndexNegated)
13285     index = -index;
13286 
13287   const NamedDecl *ND = nullptr;
13288   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13289     ND = DRE->getDecl();
13290   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13291     ND = ME->getMemberDecl();
13292 
13293   if (index.isUnsigned() || !index.isNegative()) {
13294     // It is possible that the type of the base expression after
13295     // IgnoreParenCasts is incomplete, even though the type of the base
13296     // expression before IgnoreParenCasts is complete (see PR39746 for an
13297     // example). In this case we have no information about whether the array
13298     // access exceeds the array bounds. However we can still diagnose an array
13299     // access which precedes the array bounds.
13300     if (BaseType->isIncompleteType())
13301       return;
13302 
13303     llvm::APInt size = ArrayTy->getSize();
13304     if (!size.isStrictlyPositive())
13305       return;
13306 
13307     if (BaseType != EffectiveType) {
13308       // Make sure we're comparing apples to apples when comparing index to size
13309       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13310       uint64_t array_typesize = Context.getTypeSize(BaseType);
13311       // Handle ptrarith_typesize being zero, such as when casting to void*
13312       if (!ptrarith_typesize) ptrarith_typesize = 1;
13313       if (ptrarith_typesize != array_typesize) {
13314         // There's a cast to a different size type involved
13315         uint64_t ratio = array_typesize / ptrarith_typesize;
13316         // TODO: Be smarter about handling cases where array_typesize is not a
13317         // multiple of ptrarith_typesize
13318         if (ptrarith_typesize * ratio == array_typesize)
13319           size *= llvm::APInt(size.getBitWidth(), ratio);
13320       }
13321     }
13322 
13323     if (size.getBitWidth() > index.getBitWidth())
13324       index = index.zext(size.getBitWidth());
13325     else if (size.getBitWidth() < index.getBitWidth())
13326       size = size.zext(index.getBitWidth());
13327 
13328     // For array subscripting the index must be less than size, but for pointer
13329     // arithmetic also allow the index (offset) to be equal to size since
13330     // computing the next address after the end of the array is legal and
13331     // commonly done e.g. in C++ iterators and range-based for loops.
13332     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13333       return;
13334 
13335     // Also don't warn for arrays of size 1 which are members of some
13336     // structure. These are often used to approximate flexible arrays in C89
13337     // code.
13338     if (IsTailPaddedMemberArray(*this, size, ND))
13339       return;
13340 
13341     // Suppress the warning if the subscript expression (as identified by the
13342     // ']' location) and the index expression are both from macro expansions
13343     // within a system header.
13344     if (ASE) {
13345       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13346           ASE->getRBracketLoc());
13347       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13348         SourceLocation IndexLoc =
13349             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13350         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13351           return;
13352       }
13353     }
13354 
13355     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13356     if (ASE)
13357       DiagID = diag::warn_array_index_exceeds_bounds;
13358 
13359     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13360                         PDiag(DiagID) << index.toString(10, true)
13361                                       << size.toString(10, true)
13362                                       << (unsigned)size.getLimitedValue(~0U)
13363                                       << IndexExpr->getSourceRange());
13364   } else {
13365     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13366     if (!ASE) {
13367       DiagID = diag::warn_ptr_arith_precedes_bounds;
13368       if (index.isNegative()) index = -index;
13369     }
13370 
13371     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13372                         PDiag(DiagID) << index.toString(10, true)
13373                                       << IndexExpr->getSourceRange());
13374   }
13375 
13376   if (!ND) {
13377     // Try harder to find a NamedDecl to point at in the note.
13378     while (const ArraySubscriptExpr *ASE =
13379            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13380       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13381     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13382       ND = DRE->getDecl();
13383     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13384       ND = ME->getMemberDecl();
13385   }
13386 
13387   if (ND)
13388     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13389                         PDiag(diag::note_array_declared_here)
13390                             << ND->getDeclName());
13391 }
13392 
13393 void Sema::CheckArrayAccess(const Expr *expr) {
13394   int AllowOnePastEnd = 0;
13395   while (expr) {
13396     expr = expr->IgnoreParenImpCasts();
13397     switch (expr->getStmtClass()) {
13398       case Stmt::ArraySubscriptExprClass: {
13399         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13400         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13401                          AllowOnePastEnd > 0);
13402         expr = ASE->getBase();
13403         break;
13404       }
13405       case Stmt::MemberExprClass: {
13406         expr = cast<MemberExpr>(expr)->getBase();
13407         break;
13408       }
13409       case Stmt::OMPArraySectionExprClass: {
13410         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13411         if (ASE->getLowerBound())
13412           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13413                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13414         return;
13415       }
13416       case Stmt::UnaryOperatorClass: {
13417         // Only unwrap the * and & unary operators
13418         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13419         expr = UO->getSubExpr();
13420         switch (UO->getOpcode()) {
13421           case UO_AddrOf:
13422             AllowOnePastEnd++;
13423             break;
13424           case UO_Deref:
13425             AllowOnePastEnd--;
13426             break;
13427           default:
13428             return;
13429         }
13430         break;
13431       }
13432       case Stmt::ConditionalOperatorClass: {
13433         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13434         if (const Expr *lhs = cond->getLHS())
13435           CheckArrayAccess(lhs);
13436         if (const Expr *rhs = cond->getRHS())
13437           CheckArrayAccess(rhs);
13438         return;
13439       }
13440       case Stmt::CXXOperatorCallExprClass: {
13441         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13442         for (const auto *Arg : OCE->arguments())
13443           CheckArrayAccess(Arg);
13444         return;
13445       }
13446       default:
13447         return;
13448     }
13449   }
13450 }
13451 
13452 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13453 
13454 namespace {
13455 
13456 struct RetainCycleOwner {
13457   VarDecl *Variable = nullptr;
13458   SourceRange Range;
13459   SourceLocation Loc;
13460   bool Indirect = false;
13461 
13462   RetainCycleOwner() = default;
13463 
13464   void setLocsFrom(Expr *e) {
13465     Loc = e->getExprLoc();
13466     Range = e->getSourceRange();
13467   }
13468 };
13469 
13470 } // namespace
13471 
13472 /// Consider whether capturing the given variable can possibly lead to
13473 /// a retain cycle.
13474 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13475   // In ARC, it's captured strongly iff the variable has __strong
13476   // lifetime.  In MRR, it's captured strongly if the variable is
13477   // __block and has an appropriate type.
13478   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13479     return false;
13480 
13481   owner.Variable = var;
13482   if (ref)
13483     owner.setLocsFrom(ref);
13484   return true;
13485 }
13486 
13487 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13488   while (true) {
13489     e = e->IgnoreParens();
13490     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13491       switch (cast->getCastKind()) {
13492       case CK_BitCast:
13493       case CK_LValueBitCast:
13494       case CK_LValueToRValue:
13495       case CK_ARCReclaimReturnedObject:
13496         e = cast->getSubExpr();
13497         continue;
13498 
13499       default:
13500         return false;
13501       }
13502     }
13503 
13504     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13505       ObjCIvarDecl *ivar = ref->getDecl();
13506       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13507         return false;
13508 
13509       // Try to find a retain cycle in the base.
13510       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13511         return false;
13512 
13513       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13514       owner.Indirect = true;
13515       return true;
13516     }
13517 
13518     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13519       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13520       if (!var) return false;
13521       return considerVariable(var, ref, owner);
13522     }
13523 
13524     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13525       if (member->isArrow()) return false;
13526 
13527       // Don't count this as an indirect ownership.
13528       e = member->getBase();
13529       continue;
13530     }
13531 
13532     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13533       // Only pay attention to pseudo-objects on property references.
13534       ObjCPropertyRefExpr *pre
13535         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13536                                               ->IgnoreParens());
13537       if (!pre) return false;
13538       if (pre->isImplicitProperty()) return false;
13539       ObjCPropertyDecl *property = pre->getExplicitProperty();
13540       if (!property->isRetaining() &&
13541           !(property->getPropertyIvarDecl() &&
13542             property->getPropertyIvarDecl()->getType()
13543               .getObjCLifetime() == Qualifiers::OCL_Strong))
13544           return false;
13545 
13546       owner.Indirect = true;
13547       if (pre->isSuperReceiver()) {
13548         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13549         if (!owner.Variable)
13550           return false;
13551         owner.Loc = pre->getLocation();
13552         owner.Range = pre->getSourceRange();
13553         return true;
13554       }
13555       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13556                               ->getSourceExpr());
13557       continue;
13558     }
13559 
13560     // Array ivars?
13561 
13562     return false;
13563   }
13564 }
13565 
13566 namespace {
13567 
13568   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13569     ASTContext &Context;
13570     VarDecl *Variable;
13571     Expr *Capturer = nullptr;
13572     bool VarWillBeReased = false;
13573 
13574     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13575         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13576           Context(Context), Variable(variable) {}
13577 
13578     void VisitDeclRefExpr(DeclRefExpr *ref) {
13579       if (ref->getDecl() == Variable && !Capturer)
13580         Capturer = ref;
13581     }
13582 
13583     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13584       if (Capturer) return;
13585       Visit(ref->getBase());
13586       if (Capturer && ref->isFreeIvar())
13587         Capturer = ref;
13588     }
13589 
13590     void VisitBlockExpr(BlockExpr *block) {
13591       // Look inside nested blocks
13592       if (block->getBlockDecl()->capturesVariable(Variable))
13593         Visit(block->getBlockDecl()->getBody());
13594     }
13595 
13596     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13597       if (Capturer) return;
13598       if (OVE->getSourceExpr())
13599         Visit(OVE->getSourceExpr());
13600     }
13601 
13602     void VisitBinaryOperator(BinaryOperator *BinOp) {
13603       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13604         return;
13605       Expr *LHS = BinOp->getLHS();
13606       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13607         if (DRE->getDecl() != Variable)
13608           return;
13609         if (Expr *RHS = BinOp->getRHS()) {
13610           RHS = RHS->IgnoreParenCasts();
13611           llvm::APSInt Value;
13612           VarWillBeReased =
13613             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13614         }
13615       }
13616     }
13617   };
13618 
13619 } // namespace
13620 
13621 /// Check whether the given argument is a block which captures a
13622 /// variable.
13623 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13624   assert(owner.Variable && owner.Loc.isValid());
13625 
13626   e = e->IgnoreParenCasts();
13627 
13628   // Look through [^{...} copy] and Block_copy(^{...}).
13629   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13630     Selector Cmd = ME->getSelector();
13631     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13632       e = ME->getInstanceReceiver();
13633       if (!e)
13634         return nullptr;
13635       e = e->IgnoreParenCasts();
13636     }
13637   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13638     if (CE->getNumArgs() == 1) {
13639       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13640       if (Fn) {
13641         const IdentifierInfo *FnI = Fn->getIdentifier();
13642         if (FnI && FnI->isStr("_Block_copy")) {
13643           e = CE->getArg(0)->IgnoreParenCasts();
13644         }
13645       }
13646     }
13647   }
13648 
13649   BlockExpr *block = dyn_cast<BlockExpr>(e);
13650   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13651     return nullptr;
13652 
13653   FindCaptureVisitor visitor(S.Context, owner.Variable);
13654   visitor.Visit(block->getBlockDecl()->getBody());
13655   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13656 }
13657 
13658 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13659                                 RetainCycleOwner &owner) {
13660   assert(capturer);
13661   assert(owner.Variable && owner.Loc.isValid());
13662 
13663   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13664     << owner.Variable << capturer->getSourceRange();
13665   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13666     << owner.Indirect << owner.Range;
13667 }
13668 
13669 /// Check for a keyword selector that starts with the word 'add' or
13670 /// 'set'.
13671 static bool isSetterLikeSelector(Selector sel) {
13672   if (sel.isUnarySelector()) return false;
13673 
13674   StringRef str = sel.getNameForSlot(0);
13675   while (!str.empty() && str.front() == '_') str = str.substr(1);
13676   if (str.startswith("set"))
13677     str = str.substr(3);
13678   else if (str.startswith("add")) {
13679     // Specially whitelist 'addOperationWithBlock:'.
13680     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13681       return false;
13682     str = str.substr(3);
13683   }
13684   else
13685     return false;
13686 
13687   if (str.empty()) return true;
13688   return !isLowercase(str.front());
13689 }
13690 
13691 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13692                                                     ObjCMessageExpr *Message) {
13693   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13694                                                 Message->getReceiverInterface(),
13695                                                 NSAPI::ClassId_NSMutableArray);
13696   if (!IsMutableArray) {
13697     return None;
13698   }
13699 
13700   Selector Sel = Message->getSelector();
13701 
13702   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13703     S.NSAPIObj->getNSArrayMethodKind(Sel);
13704   if (!MKOpt) {
13705     return None;
13706   }
13707 
13708   NSAPI::NSArrayMethodKind MK = *MKOpt;
13709 
13710   switch (MK) {
13711     case NSAPI::NSMutableArr_addObject:
13712     case NSAPI::NSMutableArr_insertObjectAtIndex:
13713     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13714       return 0;
13715     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13716       return 1;
13717 
13718     default:
13719       return None;
13720   }
13721 
13722   return None;
13723 }
13724 
13725 static
13726 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13727                                                   ObjCMessageExpr *Message) {
13728   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13729                                             Message->getReceiverInterface(),
13730                                             NSAPI::ClassId_NSMutableDictionary);
13731   if (!IsMutableDictionary) {
13732     return None;
13733   }
13734 
13735   Selector Sel = Message->getSelector();
13736 
13737   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13738     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13739   if (!MKOpt) {
13740     return None;
13741   }
13742 
13743   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13744 
13745   switch (MK) {
13746     case NSAPI::NSMutableDict_setObjectForKey:
13747     case NSAPI::NSMutableDict_setValueForKey:
13748     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13749       return 0;
13750 
13751     default:
13752       return None;
13753   }
13754 
13755   return None;
13756 }
13757 
13758 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13759   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13760                                                 Message->getReceiverInterface(),
13761                                                 NSAPI::ClassId_NSMutableSet);
13762 
13763   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13764                                             Message->getReceiverInterface(),
13765                                             NSAPI::ClassId_NSMutableOrderedSet);
13766   if (!IsMutableSet && !IsMutableOrderedSet) {
13767     return None;
13768   }
13769 
13770   Selector Sel = Message->getSelector();
13771 
13772   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13773   if (!MKOpt) {
13774     return None;
13775   }
13776 
13777   NSAPI::NSSetMethodKind MK = *MKOpt;
13778 
13779   switch (MK) {
13780     case NSAPI::NSMutableSet_addObject:
13781     case NSAPI::NSOrderedSet_setObjectAtIndex:
13782     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13783     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13784       return 0;
13785     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13786       return 1;
13787   }
13788 
13789   return None;
13790 }
13791 
13792 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13793   if (!Message->isInstanceMessage()) {
13794     return;
13795   }
13796 
13797   Optional<int> ArgOpt;
13798 
13799   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13800       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13801       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13802     return;
13803   }
13804 
13805   int ArgIndex = *ArgOpt;
13806 
13807   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13808   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13809     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13810   }
13811 
13812   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13813     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13814       if (ArgRE->isObjCSelfExpr()) {
13815         Diag(Message->getSourceRange().getBegin(),
13816              diag::warn_objc_circular_container)
13817           << ArgRE->getDecl() << StringRef("'super'");
13818       }
13819     }
13820   } else {
13821     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13822 
13823     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13824       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13825     }
13826 
13827     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13828       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13829         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13830           ValueDecl *Decl = ReceiverRE->getDecl();
13831           Diag(Message->getSourceRange().getBegin(),
13832                diag::warn_objc_circular_container)
13833             << Decl << Decl;
13834           if (!ArgRE->isObjCSelfExpr()) {
13835             Diag(Decl->getLocation(),
13836                  diag::note_objc_circular_container_declared_here)
13837               << Decl;
13838           }
13839         }
13840       }
13841     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13842       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13843         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13844           ObjCIvarDecl *Decl = IvarRE->getDecl();
13845           Diag(Message->getSourceRange().getBegin(),
13846                diag::warn_objc_circular_container)
13847             << Decl << Decl;
13848           Diag(Decl->getLocation(),
13849                diag::note_objc_circular_container_declared_here)
13850             << Decl;
13851         }
13852       }
13853     }
13854   }
13855 }
13856 
13857 /// Check a message send to see if it's likely to cause a retain cycle.
13858 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13859   // Only check instance methods whose selector looks like a setter.
13860   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13861     return;
13862 
13863   // Try to find a variable that the receiver is strongly owned by.
13864   RetainCycleOwner owner;
13865   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13866     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13867       return;
13868   } else {
13869     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13870     owner.Variable = getCurMethodDecl()->getSelfDecl();
13871     owner.Loc = msg->getSuperLoc();
13872     owner.Range = msg->getSuperLoc();
13873   }
13874 
13875   // Check whether the receiver is captured by any of the arguments.
13876   const ObjCMethodDecl *MD = msg->getMethodDecl();
13877   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13878     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13879       // noescape blocks should not be retained by the method.
13880       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13881         continue;
13882       return diagnoseRetainCycle(*this, capturer, owner);
13883     }
13884   }
13885 }
13886 
13887 /// Check a property assign to see if it's likely to cause a retain cycle.
13888 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13889   RetainCycleOwner owner;
13890   if (!findRetainCycleOwner(*this, receiver, owner))
13891     return;
13892 
13893   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13894     diagnoseRetainCycle(*this, capturer, owner);
13895 }
13896 
13897 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13898   RetainCycleOwner Owner;
13899   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13900     return;
13901 
13902   // Because we don't have an expression for the variable, we have to set the
13903   // location explicitly here.
13904   Owner.Loc = Var->getLocation();
13905   Owner.Range = Var->getSourceRange();
13906 
13907   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13908     diagnoseRetainCycle(*this, Capturer, Owner);
13909 }
13910 
13911 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13912                                      Expr *RHS, bool isProperty) {
13913   // Check if RHS is an Objective-C object literal, which also can get
13914   // immediately zapped in a weak reference.  Note that we explicitly
13915   // allow ObjCStringLiterals, since those are designed to never really die.
13916   RHS = RHS->IgnoreParenImpCasts();
13917 
13918   // This enum needs to match with the 'select' in
13919   // warn_objc_arc_literal_assign (off-by-1).
13920   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13921   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13922     return false;
13923 
13924   S.Diag(Loc, diag::warn_arc_literal_assign)
13925     << (unsigned) Kind
13926     << (isProperty ? 0 : 1)
13927     << RHS->getSourceRange();
13928 
13929   return true;
13930 }
13931 
13932 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13933                                     Qualifiers::ObjCLifetime LT,
13934                                     Expr *RHS, bool isProperty) {
13935   // Strip off any implicit cast added to get to the one ARC-specific.
13936   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13937     if (cast->getCastKind() == CK_ARCConsumeObject) {
13938       S.Diag(Loc, diag::warn_arc_retained_assign)
13939         << (LT == Qualifiers::OCL_ExplicitNone)
13940         << (isProperty ? 0 : 1)
13941         << RHS->getSourceRange();
13942       return true;
13943     }
13944     RHS = cast->getSubExpr();
13945   }
13946 
13947   if (LT == Qualifiers::OCL_Weak &&
13948       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13949     return true;
13950 
13951   return false;
13952 }
13953 
13954 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13955                               QualType LHS, Expr *RHS) {
13956   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13957 
13958   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13959     return false;
13960 
13961   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13962     return true;
13963 
13964   return false;
13965 }
13966 
13967 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13968                               Expr *LHS, Expr *RHS) {
13969   QualType LHSType;
13970   // PropertyRef on LHS type need be directly obtained from
13971   // its declaration as it has a PseudoType.
13972   ObjCPropertyRefExpr *PRE
13973     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13974   if (PRE && !PRE->isImplicitProperty()) {
13975     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13976     if (PD)
13977       LHSType = PD->getType();
13978   }
13979 
13980   if (LHSType.isNull())
13981     LHSType = LHS->getType();
13982 
13983   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13984 
13985   if (LT == Qualifiers::OCL_Weak) {
13986     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13987       getCurFunction()->markSafeWeakUse(LHS);
13988   }
13989 
13990   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13991     return;
13992 
13993   // FIXME. Check for other life times.
13994   if (LT != Qualifiers::OCL_None)
13995     return;
13996 
13997   if (PRE) {
13998     if (PRE->isImplicitProperty())
13999       return;
14000     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14001     if (!PD)
14002       return;
14003 
14004     unsigned Attributes = PD->getPropertyAttributes();
14005     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
14006       // when 'assign' attribute was not explicitly specified
14007       // by user, ignore it and rely on property type itself
14008       // for lifetime info.
14009       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14010       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
14011           LHSType->isObjCRetainableType())
14012         return;
14013 
14014       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14015         if (cast->getCastKind() == CK_ARCConsumeObject) {
14016           Diag(Loc, diag::warn_arc_retained_property_assign)
14017           << RHS->getSourceRange();
14018           return;
14019         }
14020         RHS = cast->getSubExpr();
14021       }
14022     }
14023     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
14024       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14025         return;
14026     }
14027   }
14028 }
14029 
14030 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14031 
14032 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14033                                         SourceLocation StmtLoc,
14034                                         const NullStmt *Body) {
14035   // Do not warn if the body is a macro that expands to nothing, e.g:
14036   //
14037   // #define CALL(x)
14038   // if (condition)
14039   //   CALL(0);
14040   if (Body->hasLeadingEmptyMacro())
14041     return false;
14042 
14043   // Get line numbers of statement and body.
14044   bool StmtLineInvalid;
14045   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14046                                                       &StmtLineInvalid);
14047   if (StmtLineInvalid)
14048     return false;
14049 
14050   bool BodyLineInvalid;
14051   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14052                                                       &BodyLineInvalid);
14053   if (BodyLineInvalid)
14054     return false;
14055 
14056   // Warn if null statement and body are on the same line.
14057   if (StmtLine != BodyLine)
14058     return false;
14059 
14060   return true;
14061 }
14062 
14063 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14064                                  const Stmt *Body,
14065                                  unsigned DiagID) {
14066   // Since this is a syntactic check, don't emit diagnostic for template
14067   // instantiations, this just adds noise.
14068   if (CurrentInstantiationScope)
14069     return;
14070 
14071   // The body should be a null statement.
14072   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14073   if (!NBody)
14074     return;
14075 
14076   // Do the usual checks.
14077   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14078     return;
14079 
14080   Diag(NBody->getSemiLoc(), DiagID);
14081   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14082 }
14083 
14084 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14085                                  const Stmt *PossibleBody) {
14086   assert(!CurrentInstantiationScope); // Ensured by caller
14087 
14088   SourceLocation StmtLoc;
14089   const Stmt *Body;
14090   unsigned DiagID;
14091   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14092     StmtLoc = FS->getRParenLoc();
14093     Body = FS->getBody();
14094     DiagID = diag::warn_empty_for_body;
14095   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14096     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14097     Body = WS->getBody();
14098     DiagID = diag::warn_empty_while_body;
14099   } else
14100     return; // Neither `for' nor `while'.
14101 
14102   // The body should be a null statement.
14103   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14104   if (!NBody)
14105     return;
14106 
14107   // Skip expensive checks if diagnostic is disabled.
14108   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14109     return;
14110 
14111   // Do the usual checks.
14112   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14113     return;
14114 
14115   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14116   // noise level low, emit diagnostics only if for/while is followed by a
14117   // CompoundStmt, e.g.:
14118   //    for (int i = 0; i < n; i++);
14119   //    {
14120   //      a(i);
14121   //    }
14122   // or if for/while is followed by a statement with more indentation
14123   // than for/while itself:
14124   //    for (int i = 0; i < n; i++);
14125   //      a(i);
14126   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14127   if (!ProbableTypo) {
14128     bool BodyColInvalid;
14129     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14130         PossibleBody->getBeginLoc(), &BodyColInvalid);
14131     if (BodyColInvalid)
14132       return;
14133 
14134     bool StmtColInvalid;
14135     unsigned StmtCol =
14136         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14137     if (StmtColInvalid)
14138       return;
14139 
14140     if (BodyCol > StmtCol)
14141       ProbableTypo = true;
14142   }
14143 
14144   if (ProbableTypo) {
14145     Diag(NBody->getSemiLoc(), DiagID);
14146     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14147   }
14148 }
14149 
14150 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14151 
14152 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14153 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14154                              SourceLocation OpLoc) {
14155   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14156     return;
14157 
14158   if (inTemplateInstantiation())
14159     return;
14160 
14161   // Strip parens and casts away.
14162   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14163   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14164 
14165   // Check for a call expression
14166   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14167   if (!CE || CE->getNumArgs() != 1)
14168     return;
14169 
14170   // Check for a call to std::move
14171   if (!CE->isCallToStdMove())
14172     return;
14173 
14174   // Get argument from std::move
14175   RHSExpr = CE->getArg(0);
14176 
14177   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14178   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14179 
14180   // Two DeclRefExpr's, check that the decls are the same.
14181   if (LHSDeclRef && RHSDeclRef) {
14182     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14183       return;
14184     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14185         RHSDeclRef->getDecl()->getCanonicalDecl())
14186       return;
14187 
14188     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14189                                         << LHSExpr->getSourceRange()
14190                                         << RHSExpr->getSourceRange();
14191     return;
14192   }
14193 
14194   // Member variables require a different approach to check for self moves.
14195   // MemberExpr's are the same if every nested MemberExpr refers to the same
14196   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14197   // the base Expr's are CXXThisExpr's.
14198   const Expr *LHSBase = LHSExpr;
14199   const Expr *RHSBase = RHSExpr;
14200   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14201   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14202   if (!LHSME || !RHSME)
14203     return;
14204 
14205   while (LHSME && RHSME) {
14206     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14207         RHSME->getMemberDecl()->getCanonicalDecl())
14208       return;
14209 
14210     LHSBase = LHSME->getBase();
14211     RHSBase = RHSME->getBase();
14212     LHSME = dyn_cast<MemberExpr>(LHSBase);
14213     RHSME = dyn_cast<MemberExpr>(RHSBase);
14214   }
14215 
14216   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14217   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14218   if (LHSDeclRef && RHSDeclRef) {
14219     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14220       return;
14221     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14222         RHSDeclRef->getDecl()->getCanonicalDecl())
14223       return;
14224 
14225     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14226                                         << LHSExpr->getSourceRange()
14227                                         << RHSExpr->getSourceRange();
14228     return;
14229   }
14230 
14231   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14232     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14233                                         << LHSExpr->getSourceRange()
14234                                         << RHSExpr->getSourceRange();
14235 }
14236 
14237 //===--- Layout compatibility ----------------------------------------------//
14238 
14239 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14240 
14241 /// Check if two enumeration types are layout-compatible.
14242 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14243   // C++11 [dcl.enum] p8:
14244   // Two enumeration types are layout-compatible if they have the same
14245   // underlying type.
14246   return ED1->isComplete() && ED2->isComplete() &&
14247          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14248 }
14249 
14250 /// Check if two fields are layout-compatible.
14251 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14252                                FieldDecl *Field2) {
14253   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14254     return false;
14255 
14256   if (Field1->isBitField() != Field2->isBitField())
14257     return false;
14258 
14259   if (Field1->isBitField()) {
14260     // Make sure that the bit-fields are the same length.
14261     unsigned Bits1 = Field1->getBitWidthValue(C);
14262     unsigned Bits2 = Field2->getBitWidthValue(C);
14263 
14264     if (Bits1 != Bits2)
14265       return false;
14266   }
14267 
14268   return true;
14269 }
14270 
14271 /// Check if two standard-layout structs are layout-compatible.
14272 /// (C++11 [class.mem] p17)
14273 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14274                                      RecordDecl *RD2) {
14275   // If both records are C++ classes, check that base classes match.
14276   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14277     // If one of records is a CXXRecordDecl we are in C++ mode,
14278     // thus the other one is a CXXRecordDecl, too.
14279     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14280     // Check number of base classes.
14281     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14282       return false;
14283 
14284     // Check the base classes.
14285     for (CXXRecordDecl::base_class_const_iterator
14286                Base1 = D1CXX->bases_begin(),
14287            BaseEnd1 = D1CXX->bases_end(),
14288               Base2 = D2CXX->bases_begin();
14289          Base1 != BaseEnd1;
14290          ++Base1, ++Base2) {
14291       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14292         return false;
14293     }
14294   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14295     // If only RD2 is a C++ class, it should have zero base classes.
14296     if (D2CXX->getNumBases() > 0)
14297       return false;
14298   }
14299 
14300   // Check the fields.
14301   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14302                              Field2End = RD2->field_end(),
14303                              Field1 = RD1->field_begin(),
14304                              Field1End = RD1->field_end();
14305   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14306     if (!isLayoutCompatible(C, *Field1, *Field2))
14307       return false;
14308   }
14309   if (Field1 != Field1End || Field2 != Field2End)
14310     return false;
14311 
14312   return true;
14313 }
14314 
14315 /// Check if two standard-layout unions are layout-compatible.
14316 /// (C++11 [class.mem] p18)
14317 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14318                                     RecordDecl *RD2) {
14319   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14320   for (auto *Field2 : RD2->fields())
14321     UnmatchedFields.insert(Field2);
14322 
14323   for (auto *Field1 : RD1->fields()) {
14324     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14325         I = UnmatchedFields.begin(),
14326         E = UnmatchedFields.end();
14327 
14328     for ( ; I != E; ++I) {
14329       if (isLayoutCompatible(C, Field1, *I)) {
14330         bool Result = UnmatchedFields.erase(*I);
14331         (void) Result;
14332         assert(Result);
14333         break;
14334       }
14335     }
14336     if (I == E)
14337       return false;
14338   }
14339 
14340   return UnmatchedFields.empty();
14341 }
14342 
14343 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14344                                RecordDecl *RD2) {
14345   if (RD1->isUnion() != RD2->isUnion())
14346     return false;
14347 
14348   if (RD1->isUnion())
14349     return isLayoutCompatibleUnion(C, RD1, RD2);
14350   else
14351     return isLayoutCompatibleStruct(C, RD1, RD2);
14352 }
14353 
14354 /// Check if two types are layout-compatible in C++11 sense.
14355 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14356   if (T1.isNull() || T2.isNull())
14357     return false;
14358 
14359   // C++11 [basic.types] p11:
14360   // If two types T1 and T2 are the same type, then T1 and T2 are
14361   // layout-compatible types.
14362   if (C.hasSameType(T1, T2))
14363     return true;
14364 
14365   T1 = T1.getCanonicalType().getUnqualifiedType();
14366   T2 = T2.getCanonicalType().getUnqualifiedType();
14367 
14368   const Type::TypeClass TC1 = T1->getTypeClass();
14369   const Type::TypeClass TC2 = T2->getTypeClass();
14370 
14371   if (TC1 != TC2)
14372     return false;
14373 
14374   if (TC1 == Type::Enum) {
14375     return isLayoutCompatible(C,
14376                               cast<EnumType>(T1)->getDecl(),
14377                               cast<EnumType>(T2)->getDecl());
14378   } else if (TC1 == Type::Record) {
14379     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14380       return false;
14381 
14382     return isLayoutCompatible(C,
14383                               cast<RecordType>(T1)->getDecl(),
14384                               cast<RecordType>(T2)->getDecl());
14385   }
14386 
14387   return false;
14388 }
14389 
14390 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14391 
14392 /// Given a type tag expression find the type tag itself.
14393 ///
14394 /// \param TypeExpr Type tag expression, as it appears in user's code.
14395 ///
14396 /// \param VD Declaration of an identifier that appears in a type tag.
14397 ///
14398 /// \param MagicValue Type tag magic value.
14399 ///
14400 /// \param isConstantEvaluated wether the evalaution should be performed in
14401 
14402 /// constant context.
14403 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14404                             const ValueDecl **VD, uint64_t *MagicValue,
14405                             bool isConstantEvaluated) {
14406   while(true) {
14407     if (!TypeExpr)
14408       return false;
14409 
14410     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14411 
14412     switch (TypeExpr->getStmtClass()) {
14413     case Stmt::UnaryOperatorClass: {
14414       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14415       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14416         TypeExpr = UO->getSubExpr();
14417         continue;
14418       }
14419       return false;
14420     }
14421 
14422     case Stmt::DeclRefExprClass: {
14423       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14424       *VD = DRE->getDecl();
14425       return true;
14426     }
14427 
14428     case Stmt::IntegerLiteralClass: {
14429       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14430       llvm::APInt MagicValueAPInt = IL->getValue();
14431       if (MagicValueAPInt.getActiveBits() <= 64) {
14432         *MagicValue = MagicValueAPInt.getZExtValue();
14433         return true;
14434       } else
14435         return false;
14436     }
14437 
14438     case Stmt::BinaryConditionalOperatorClass:
14439     case Stmt::ConditionalOperatorClass: {
14440       const AbstractConditionalOperator *ACO =
14441           cast<AbstractConditionalOperator>(TypeExpr);
14442       bool Result;
14443       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14444                                                      isConstantEvaluated)) {
14445         if (Result)
14446           TypeExpr = ACO->getTrueExpr();
14447         else
14448           TypeExpr = ACO->getFalseExpr();
14449         continue;
14450       }
14451       return false;
14452     }
14453 
14454     case Stmt::BinaryOperatorClass: {
14455       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14456       if (BO->getOpcode() == BO_Comma) {
14457         TypeExpr = BO->getRHS();
14458         continue;
14459       }
14460       return false;
14461     }
14462 
14463     default:
14464       return false;
14465     }
14466   }
14467 }
14468 
14469 /// Retrieve the C type corresponding to type tag TypeExpr.
14470 ///
14471 /// \param TypeExpr Expression that specifies a type tag.
14472 ///
14473 /// \param MagicValues Registered magic values.
14474 ///
14475 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14476 ///        kind.
14477 ///
14478 /// \param TypeInfo Information about the corresponding C type.
14479 ///
14480 /// \param isConstantEvaluated wether the evalaution should be performed in
14481 /// constant context.
14482 ///
14483 /// \returns true if the corresponding C type was found.
14484 static bool GetMatchingCType(
14485     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14486     const ASTContext &Ctx,
14487     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14488         *MagicValues,
14489     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14490     bool isConstantEvaluated) {
14491   FoundWrongKind = false;
14492 
14493   // Variable declaration that has type_tag_for_datatype attribute.
14494   const ValueDecl *VD = nullptr;
14495 
14496   uint64_t MagicValue;
14497 
14498   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14499     return false;
14500 
14501   if (VD) {
14502     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14503       if (I->getArgumentKind() != ArgumentKind) {
14504         FoundWrongKind = true;
14505         return false;
14506       }
14507       TypeInfo.Type = I->getMatchingCType();
14508       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14509       TypeInfo.MustBeNull = I->getMustBeNull();
14510       return true;
14511     }
14512     return false;
14513   }
14514 
14515   if (!MagicValues)
14516     return false;
14517 
14518   llvm::DenseMap<Sema::TypeTagMagicValue,
14519                  Sema::TypeTagData>::const_iterator I =
14520       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14521   if (I == MagicValues->end())
14522     return false;
14523 
14524   TypeInfo = I->second;
14525   return true;
14526 }
14527 
14528 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14529                                       uint64_t MagicValue, QualType Type,
14530                                       bool LayoutCompatible,
14531                                       bool MustBeNull) {
14532   if (!TypeTagForDatatypeMagicValues)
14533     TypeTagForDatatypeMagicValues.reset(
14534         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14535 
14536   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14537   (*TypeTagForDatatypeMagicValues)[Magic] =
14538       TypeTagData(Type, LayoutCompatible, MustBeNull);
14539 }
14540 
14541 static bool IsSameCharType(QualType T1, QualType T2) {
14542   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14543   if (!BT1)
14544     return false;
14545 
14546   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14547   if (!BT2)
14548     return false;
14549 
14550   BuiltinType::Kind T1Kind = BT1->getKind();
14551   BuiltinType::Kind T2Kind = BT2->getKind();
14552 
14553   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14554          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14555          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14556          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14557 }
14558 
14559 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14560                                     const ArrayRef<const Expr *> ExprArgs,
14561                                     SourceLocation CallSiteLoc) {
14562   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14563   bool IsPointerAttr = Attr->getIsPointer();
14564 
14565   // Retrieve the argument representing the 'type_tag'.
14566   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14567   if (TypeTagIdxAST >= ExprArgs.size()) {
14568     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14569         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14570     return;
14571   }
14572   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14573   bool FoundWrongKind;
14574   TypeTagData TypeInfo;
14575   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14576                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14577                         TypeInfo, isConstantEvaluated())) {
14578     if (FoundWrongKind)
14579       Diag(TypeTagExpr->getExprLoc(),
14580            diag::warn_type_tag_for_datatype_wrong_kind)
14581         << TypeTagExpr->getSourceRange();
14582     return;
14583   }
14584 
14585   // Retrieve the argument representing the 'arg_idx'.
14586   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14587   if (ArgumentIdxAST >= ExprArgs.size()) {
14588     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14589         << 1 << Attr->getArgumentIdx().getSourceIndex();
14590     return;
14591   }
14592   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14593   if (IsPointerAttr) {
14594     // Skip implicit cast of pointer to `void *' (as a function argument).
14595     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14596       if (ICE->getType()->isVoidPointerType() &&
14597           ICE->getCastKind() == CK_BitCast)
14598         ArgumentExpr = ICE->getSubExpr();
14599   }
14600   QualType ArgumentType = ArgumentExpr->getType();
14601 
14602   // Passing a `void*' pointer shouldn't trigger a warning.
14603   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14604     return;
14605 
14606   if (TypeInfo.MustBeNull) {
14607     // Type tag with matching void type requires a null pointer.
14608     if (!ArgumentExpr->isNullPointerConstant(Context,
14609                                              Expr::NPC_ValueDependentIsNotNull)) {
14610       Diag(ArgumentExpr->getExprLoc(),
14611            diag::warn_type_safety_null_pointer_required)
14612           << ArgumentKind->getName()
14613           << ArgumentExpr->getSourceRange()
14614           << TypeTagExpr->getSourceRange();
14615     }
14616     return;
14617   }
14618 
14619   QualType RequiredType = TypeInfo.Type;
14620   if (IsPointerAttr)
14621     RequiredType = Context.getPointerType(RequiredType);
14622 
14623   bool mismatch = false;
14624   if (!TypeInfo.LayoutCompatible) {
14625     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14626 
14627     // C++11 [basic.fundamental] p1:
14628     // Plain char, signed char, and unsigned char are three distinct types.
14629     //
14630     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14631     // char' depending on the current char signedness mode.
14632     if (mismatch)
14633       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14634                                            RequiredType->getPointeeType())) ||
14635           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14636         mismatch = false;
14637   } else
14638     if (IsPointerAttr)
14639       mismatch = !isLayoutCompatible(Context,
14640                                      ArgumentType->getPointeeType(),
14641                                      RequiredType->getPointeeType());
14642     else
14643       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14644 
14645   if (mismatch)
14646     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14647         << ArgumentType << ArgumentKind
14648         << TypeInfo.LayoutCompatible << RequiredType
14649         << ArgumentExpr->getSourceRange()
14650         << TypeTagExpr->getSourceRange();
14651 }
14652 
14653 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14654                                          CharUnits Alignment) {
14655   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14656 }
14657 
14658 void Sema::DiagnoseMisalignedMembers() {
14659   for (MisalignedMember &m : MisalignedMembers) {
14660     const NamedDecl *ND = m.RD;
14661     if (ND->getName().empty()) {
14662       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14663         ND = TD;
14664     }
14665     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14666         << m.MD << ND << m.E->getSourceRange();
14667   }
14668   MisalignedMembers.clear();
14669 }
14670 
14671 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14672   E = E->IgnoreParens();
14673   if (!T->isPointerType() && !T->isIntegerType())
14674     return;
14675   if (isa<UnaryOperator>(E) &&
14676       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14677     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14678     if (isa<MemberExpr>(Op)) {
14679       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14680       if (MA != MisalignedMembers.end() &&
14681           (T->isIntegerType() ||
14682            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14683                                    Context.getTypeAlignInChars(
14684                                        T->getPointeeType()) <= MA->Alignment))))
14685         MisalignedMembers.erase(MA);
14686     }
14687   }
14688 }
14689 
14690 void Sema::RefersToMemberWithReducedAlignment(
14691     Expr *E,
14692     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14693         Action) {
14694   const auto *ME = dyn_cast<MemberExpr>(E);
14695   if (!ME)
14696     return;
14697 
14698   // No need to check expressions with an __unaligned-qualified type.
14699   if (E->getType().getQualifiers().hasUnaligned())
14700     return;
14701 
14702   // For a chain of MemberExpr like "a.b.c.d" this list
14703   // will keep FieldDecl's like [d, c, b].
14704   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14705   const MemberExpr *TopME = nullptr;
14706   bool AnyIsPacked = false;
14707   do {
14708     QualType BaseType = ME->getBase()->getType();
14709     if (BaseType->isDependentType())
14710       return;
14711     if (ME->isArrow())
14712       BaseType = BaseType->getPointeeType();
14713     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14714     if (RD->isInvalidDecl())
14715       return;
14716 
14717     ValueDecl *MD = ME->getMemberDecl();
14718     auto *FD = dyn_cast<FieldDecl>(MD);
14719     // We do not care about non-data members.
14720     if (!FD || FD->isInvalidDecl())
14721       return;
14722 
14723     AnyIsPacked =
14724         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14725     ReverseMemberChain.push_back(FD);
14726 
14727     TopME = ME;
14728     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14729   } while (ME);
14730   assert(TopME && "We did not compute a topmost MemberExpr!");
14731 
14732   // Not the scope of this diagnostic.
14733   if (!AnyIsPacked)
14734     return;
14735 
14736   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14737   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14738   // TODO: The innermost base of the member expression may be too complicated.
14739   // For now, just disregard these cases. This is left for future
14740   // improvement.
14741   if (!DRE && !isa<CXXThisExpr>(TopBase))
14742       return;
14743 
14744   // Alignment expected by the whole expression.
14745   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14746 
14747   // No need to do anything else with this case.
14748   if (ExpectedAlignment.isOne())
14749     return;
14750 
14751   // Synthesize offset of the whole access.
14752   CharUnits Offset;
14753   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14754        I++) {
14755     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14756   }
14757 
14758   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14759   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14760       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14761 
14762   // The base expression of the innermost MemberExpr may give
14763   // stronger guarantees than the class containing the member.
14764   if (DRE && !TopME->isArrow()) {
14765     const ValueDecl *VD = DRE->getDecl();
14766     if (!VD->getType()->isReferenceType())
14767       CompleteObjectAlignment =
14768           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14769   }
14770 
14771   // Check if the synthesized offset fulfills the alignment.
14772   if (Offset % ExpectedAlignment != 0 ||
14773       // It may fulfill the offset it but the effective alignment may still be
14774       // lower than the expected expression alignment.
14775       CompleteObjectAlignment < ExpectedAlignment) {
14776     // If this happens, we want to determine a sensible culprit of this.
14777     // Intuitively, watching the chain of member expressions from right to
14778     // left, we start with the required alignment (as required by the field
14779     // type) but some packed attribute in that chain has reduced the alignment.
14780     // It may happen that another packed structure increases it again. But if
14781     // we are here such increase has not been enough. So pointing the first
14782     // FieldDecl that either is packed or else its RecordDecl is,
14783     // seems reasonable.
14784     FieldDecl *FD = nullptr;
14785     CharUnits Alignment;
14786     for (FieldDecl *FDI : ReverseMemberChain) {
14787       if (FDI->hasAttr<PackedAttr>() ||
14788           FDI->getParent()->hasAttr<PackedAttr>()) {
14789         FD = FDI;
14790         Alignment = std::min(
14791             Context.getTypeAlignInChars(FD->getType()),
14792             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14793         break;
14794       }
14795     }
14796     assert(FD && "We did not find a packed FieldDecl!");
14797     Action(E, FD->getParent(), FD, Alignment);
14798   }
14799 }
14800 
14801 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14802   using namespace std::placeholders;
14803 
14804   RefersToMemberWithReducedAlignment(
14805       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14806                      _2, _3, _4));
14807 }
14808