1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.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/Analysis/Analyses/FormatString.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/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->getLocEnd(), 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)->getLocStart(),
121                     call->getArg(argCount - 1)->getLocEnd());
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->getLocStart(), 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->getLocStart(), 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->getLocEnd(), 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->getLocStart(), 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->getLocStart());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195   if (checkArgCount(S, TheCall, 3))
196     return true;
197 
198   // First two arguments should be integers.
199   for (unsigned I = 0; I < 2; ++I) {
200     ExprResult Arg = TheCall->getArg(I);
201     QualType Ty = Arg.get()->getType();
202     if (!Ty->isIntegerType()) {
203       S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
204           << Ty << Arg.get()->getSourceRange();
205       return true;
206     }
207     InitializedEntity Entity = InitializedEntity::InitializeParameter(
208         S.getASTContext(), Ty, /*consume*/ false);
209     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210     if (Arg.isInvalid())
211       return true;
212     TheCall->setArg(I, Arg.get());
213   }
214 
215   // Third argument should be a pointer to a non-const integer.
216   // IRGen correctly handles volatile, restrict, and address spaces, and
217   // the other qualifiers aren't possible.
218   {
219     ExprResult Arg = TheCall->getArg(2);
220     QualType Ty = Arg.get()->getType();
221     const auto *PtrTy = Ty->getAs<PointerType>();
222     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223           !PtrTy->getPointeeType().isConstQualified())) {
224       S.Diag(Arg.get()->getLocStart(),
225              diag::err_overflow_builtin_must_be_ptr_int)
226           << Ty << Arg.get()->getSourceRange();
227       return true;
228     }
229     InitializedEntity Entity = InitializedEntity::InitializeParameter(
230         S.getASTContext(), Ty, /*consume*/ false);
231     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232     if (Arg.isInvalid())
233       return true;
234     TheCall->setArg(2, Arg.get());
235   }
236   return false;
237 }
238 
239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
240 		                  CallExpr *TheCall, unsigned SizeIdx,
241                                   unsigned DstSizeIdx) {
242   if (TheCall->getNumArgs() <= SizeIdx ||
243       TheCall->getNumArgs() <= DstSizeIdx)
244     return;
245 
246   const Expr *SizeArg = TheCall->getArg(SizeIdx);
247   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
248 
249   llvm::APSInt Size, DstSize;
250 
251   // find out if both sizes are known at compile time
252   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
253       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
254     return;
255 
256   if (Size.ule(DstSize))
257     return;
258 
259   // confirmed overflow so generate the diagnostic.
260   IdentifierInfo *FnName = FDecl->getIdentifier();
261   SourceLocation SL = TheCall->getLocStart();
262   SourceRange SR = TheCall->getSourceRange();
263 
264   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
265 }
266 
267 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
268   if (checkArgCount(S, BuiltinCall, 2))
269     return true;
270 
271   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
272   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
273   Expr *Call = BuiltinCall->getArg(0);
274   Expr *Chain = BuiltinCall->getArg(1);
275 
276   if (Call->getStmtClass() != Stmt::CallExprClass) {
277     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
278         << Call->getSourceRange();
279     return true;
280   }
281 
282   auto CE = cast<CallExpr>(Call);
283   if (CE->getCallee()->getType()->isBlockPointerType()) {
284     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
285         << Call->getSourceRange();
286     return true;
287   }
288 
289   const Decl *TargetDecl = CE->getCalleeDecl();
290   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
291     if (FD->getBuiltinID()) {
292       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
293           << Call->getSourceRange();
294       return true;
295     }
296 
297   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
298     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
299         << Call->getSourceRange();
300     return true;
301   }
302 
303   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
304   if (ChainResult.isInvalid())
305     return true;
306   if (!ChainResult.get()->getType()->isPointerType()) {
307     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
308         << Chain->getSourceRange();
309     return true;
310   }
311 
312   QualType ReturnTy = CE->getCallReturnType(S.Context);
313   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
314   QualType BuiltinTy = S.Context.getFunctionType(
315       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
316   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
317 
318   Builtin =
319       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
320 
321   BuiltinCall->setType(CE->getType());
322   BuiltinCall->setValueKind(CE->getValueKind());
323   BuiltinCall->setObjectKind(CE->getObjectKind());
324   BuiltinCall->setCallee(Builtin);
325   BuiltinCall->setArg(1, ChainResult.get());
326 
327   return false;
328 }
329 
330 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
331                                      Scope::ScopeFlags NeededScopeFlags,
332                                      unsigned DiagID) {
333   // Scopes aren't available during instantiation. Fortunately, builtin
334   // functions cannot be template args so they cannot be formed through template
335   // instantiation. Therefore checking once during the parse is sufficient.
336   if (SemaRef.inTemplateInstantiation())
337     return false;
338 
339   Scope *S = SemaRef.getCurScope();
340   while (S && !S->isSEHExceptScope())
341     S = S->getParent();
342   if (!S || !(S->getFlags() & NeededScopeFlags)) {
343     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
344     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
345         << DRE->getDecl()->getIdentifier();
346     return true;
347   }
348 
349   return false;
350 }
351 
352 static inline bool isBlockPointer(Expr *Arg) {
353   return Arg->getType()->isBlockPointerType();
354 }
355 
356 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
357 /// void*, which is a requirement of device side enqueue.
358 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
359   const BlockPointerType *BPT =
360       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
361   ArrayRef<QualType> Params =
362       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
363   unsigned ArgCounter = 0;
364   bool IllegalParams = false;
365   // Iterate through the block parameters until either one is found that is not
366   // a local void*, or the block is valid.
367   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
368        I != E; ++I, ++ArgCounter) {
369     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
370         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
371             LangAS::opencl_local) {
372       // Get the location of the error. If a block literal has been passed
373       // (BlockExpr) then we can point straight to the offending argument,
374       // else we just point to the variable reference.
375       SourceLocation ErrorLoc;
376       if (isa<BlockExpr>(BlockArg)) {
377         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
378         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
379       } else if (isa<DeclRefExpr>(BlockArg)) {
380         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
381       }
382       S.Diag(ErrorLoc,
383              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
384       IllegalParams = true;
385     }
386   }
387 
388   return IllegalParams;
389 }
390 
391 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
392   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
393     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
394           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
395     return true;
396   }
397   return false;
398 }
399 
400 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
401   if (checkArgCount(S, TheCall, 2))
402     return true;
403 
404   if (checkOpenCLSubgroupExt(S, TheCall))
405     return true;
406 
407   // First argument is an ndrange_t type.
408   Expr *NDRangeArg = TheCall->getArg(0);
409   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
410     S.Diag(NDRangeArg->getLocStart(),
411            diag::err_opencl_builtin_expected_type)
412         << TheCall->getDirectCallee() << "'ndrange_t'";
413     return true;
414   }
415 
416   Expr *BlockArg = TheCall->getArg(1);
417   if (!isBlockPointer(BlockArg)) {
418     S.Diag(BlockArg->getLocStart(),
419            diag::err_opencl_builtin_expected_type)
420         << TheCall->getDirectCallee() << "block";
421     return true;
422   }
423   return checkOpenCLBlockArgs(S, BlockArg);
424 }
425 
426 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
427 /// get_kernel_work_group_size
428 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
429 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
430   if (checkArgCount(S, TheCall, 1))
431     return true;
432 
433   Expr *BlockArg = TheCall->getArg(0);
434   if (!isBlockPointer(BlockArg)) {
435     S.Diag(BlockArg->getLocStart(),
436            diag::err_opencl_builtin_expected_type)
437         << TheCall->getDirectCallee() << "block";
438     return true;
439   }
440   return checkOpenCLBlockArgs(S, BlockArg);
441 }
442 
443 /// Diagnose integer type and any valid implicit conversion to it.
444 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
445                                       const QualType &IntType);
446 
447 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
448                                             unsigned Start, unsigned End) {
449   bool IllegalParams = false;
450   for (unsigned I = Start; I <= End; ++I)
451     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
452                                               S.Context.getSizeType());
453   return IllegalParams;
454 }
455 
456 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
457 /// 'local void*' parameter of passed block.
458 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
459                                            Expr *BlockArg,
460                                            unsigned NumNonVarArgs) {
461   const BlockPointerType *BPT =
462       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
463   unsigned NumBlockParams =
464       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
465   unsigned TotalNumArgs = TheCall->getNumArgs();
466 
467   // For each argument passed to the block, a corresponding uint needs to
468   // be passed to describe the size of the local memory.
469   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
470     S.Diag(TheCall->getLocStart(),
471            diag::err_opencl_enqueue_kernel_local_size_args);
472     return true;
473   }
474 
475   // Check that the sizes of the local memory are specified by integers.
476   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
477                                          TotalNumArgs - 1);
478 }
479 
480 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
481 /// overload formats specified in Table 6.13.17.1.
482 /// int enqueue_kernel(queue_t queue,
483 ///                    kernel_enqueue_flags_t flags,
484 ///                    const ndrange_t ndrange,
485 ///                    void (^block)(void))
486 /// int enqueue_kernel(queue_t queue,
487 ///                    kernel_enqueue_flags_t flags,
488 ///                    const ndrange_t ndrange,
489 ///                    uint num_events_in_wait_list,
490 ///                    clk_event_t *event_wait_list,
491 ///                    clk_event_t *event_ret,
492 ///                    void (^block)(void))
493 /// int enqueue_kernel(queue_t queue,
494 ///                    kernel_enqueue_flags_t flags,
495 ///                    const ndrange_t ndrange,
496 ///                    void (^block)(local void*, ...),
497 ///                    uint size0, ...)
498 /// int enqueue_kernel(queue_t queue,
499 ///                    kernel_enqueue_flags_t flags,
500 ///                    const ndrange_t ndrange,
501 ///                    uint num_events_in_wait_list,
502 ///                    clk_event_t *event_wait_list,
503 ///                    clk_event_t *event_ret,
504 ///                    void (^block)(local void*, ...),
505 ///                    uint size0, ...)
506 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
507   unsigned NumArgs = TheCall->getNumArgs();
508 
509   if (NumArgs < 4) {
510     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
511     return true;
512   }
513 
514   Expr *Arg0 = TheCall->getArg(0);
515   Expr *Arg1 = TheCall->getArg(1);
516   Expr *Arg2 = TheCall->getArg(2);
517   Expr *Arg3 = TheCall->getArg(3);
518 
519   // First argument always needs to be a queue_t type.
520   if (!Arg0->getType()->isQueueT()) {
521     S.Diag(TheCall->getArg(0)->getLocStart(),
522            diag::err_opencl_builtin_expected_type)
523         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
524     return true;
525   }
526 
527   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
528   if (!Arg1->getType()->isIntegerType()) {
529     S.Diag(TheCall->getArg(1)->getLocStart(),
530            diag::err_opencl_builtin_expected_type)
531         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
532     return true;
533   }
534 
535   // Third argument is always an ndrange_t type.
536   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
537     S.Diag(TheCall->getArg(2)->getLocStart(),
538            diag::err_opencl_builtin_expected_type)
539         << TheCall->getDirectCallee() << "'ndrange_t'";
540     return true;
541   }
542 
543   // With four arguments, there is only one form that the function could be
544   // called in: no events and no variable arguments.
545   if (NumArgs == 4) {
546     // check that the last argument is the right block type.
547     if (!isBlockPointer(Arg3)) {
548       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
549           << TheCall->getDirectCallee() << "block";
550       return true;
551     }
552     // we have a block type, check the prototype
553     const BlockPointerType *BPT =
554         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
555     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
556       S.Diag(Arg3->getLocStart(),
557              diag::err_opencl_enqueue_kernel_blocks_no_args);
558       return true;
559     }
560     return false;
561   }
562   // we can have block + varargs.
563   if (isBlockPointer(Arg3))
564     return (checkOpenCLBlockArgs(S, Arg3) ||
565             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
566   // last two cases with either exactly 7 args or 7 args and varargs.
567   if (NumArgs >= 7) {
568     // check common block argument.
569     Expr *Arg6 = TheCall->getArg(6);
570     if (!isBlockPointer(Arg6)) {
571       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
572           << TheCall->getDirectCallee() << "block";
573       return true;
574     }
575     if (checkOpenCLBlockArgs(S, Arg6))
576       return true;
577 
578     // Forth argument has to be any integer type.
579     if (!Arg3->getType()->isIntegerType()) {
580       S.Diag(TheCall->getArg(3)->getLocStart(),
581              diag::err_opencl_builtin_expected_type)
582           << TheCall->getDirectCallee() << "integer";
583       return true;
584     }
585     // check remaining common arguments.
586     Expr *Arg4 = TheCall->getArg(4);
587     Expr *Arg5 = TheCall->getArg(5);
588 
589     // Fifth argument is always passed as a pointer to clk_event_t.
590     if (!Arg4->isNullPointerConstant(S.Context,
591                                      Expr::NPC_ValueDependentIsNotNull) &&
592         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
593       S.Diag(TheCall->getArg(4)->getLocStart(),
594              diag::err_opencl_builtin_expected_type)
595           << TheCall->getDirectCallee()
596           << S.Context.getPointerType(S.Context.OCLClkEventTy);
597       return true;
598     }
599 
600     // Sixth argument is always passed as a pointer to clk_event_t.
601     if (!Arg5->isNullPointerConstant(S.Context,
602                                      Expr::NPC_ValueDependentIsNotNull) &&
603         !(Arg5->getType()->isPointerType() &&
604           Arg5->getType()->getPointeeType()->isClkEventT())) {
605       S.Diag(TheCall->getArg(5)->getLocStart(),
606              diag::err_opencl_builtin_expected_type)
607           << TheCall->getDirectCallee()
608           << S.Context.getPointerType(S.Context.OCLClkEventTy);
609       return true;
610     }
611 
612     if (NumArgs == 7)
613       return false;
614 
615     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
616   }
617 
618   // None of the specific case has been detected, give generic error
619   S.Diag(TheCall->getLocStart(),
620          diag::err_opencl_enqueue_kernel_incorrect_args);
621   return true;
622 }
623 
624 /// Returns OpenCL access qual.
625 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
626     return D->getAttr<OpenCLAccessAttr>();
627 }
628 
629 /// Returns true if pipe element type is different from the pointer.
630 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
631   const Expr *Arg0 = Call->getArg(0);
632   // First argument type should always be pipe.
633   if (!Arg0->getType()->isPipeType()) {
634     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
635         << Call->getDirectCallee() << Arg0->getSourceRange();
636     return true;
637   }
638   OpenCLAccessAttr *AccessQual =
639       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
640   // Validates the access qualifier is compatible with the call.
641   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
642   // read_only and write_only, and assumed to be read_only if no qualifier is
643   // specified.
644   switch (Call->getDirectCallee()->getBuiltinID()) {
645   case Builtin::BIread_pipe:
646   case Builtin::BIreserve_read_pipe:
647   case Builtin::BIcommit_read_pipe:
648   case Builtin::BIwork_group_reserve_read_pipe:
649   case Builtin::BIsub_group_reserve_read_pipe:
650   case Builtin::BIwork_group_commit_read_pipe:
651   case Builtin::BIsub_group_commit_read_pipe:
652     if (!(!AccessQual || AccessQual->isReadOnly())) {
653       S.Diag(Arg0->getLocStart(),
654              diag::err_opencl_builtin_pipe_invalid_access_modifier)
655           << "read_only" << Arg0->getSourceRange();
656       return true;
657     }
658     break;
659   case Builtin::BIwrite_pipe:
660   case Builtin::BIreserve_write_pipe:
661   case Builtin::BIcommit_write_pipe:
662   case Builtin::BIwork_group_reserve_write_pipe:
663   case Builtin::BIsub_group_reserve_write_pipe:
664   case Builtin::BIwork_group_commit_write_pipe:
665   case Builtin::BIsub_group_commit_write_pipe:
666     if (!(AccessQual && AccessQual->isWriteOnly())) {
667       S.Diag(Arg0->getLocStart(),
668              diag::err_opencl_builtin_pipe_invalid_access_modifier)
669           << "write_only" << Arg0->getSourceRange();
670       return true;
671     }
672     break;
673   default:
674     break;
675   }
676   return false;
677 }
678 
679 /// Returns true if pipe element type is different from the pointer.
680 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
681   const Expr *Arg0 = Call->getArg(0);
682   const Expr *ArgIdx = Call->getArg(Idx);
683   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
684   const QualType EltTy = PipeTy->getElementType();
685   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
686   // The Idx argument should be a pointer and the type of the pointer and
687   // the type of pipe element should also be the same.
688   if (!ArgTy ||
689       !S.Context.hasSameType(
690           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
691     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
692         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
693         << ArgIdx->getType() << ArgIdx->getSourceRange();
694     return true;
695   }
696   return false;
697 }
698 
699 // Performs semantic analysis for the read/write_pipe call.
700 // \param S Reference to the semantic analyzer.
701 // \param Call A pointer to the builtin call.
702 // \return True if a semantic error has been found, false otherwise.
703 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
704   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
705   // functions have two forms.
706   switch (Call->getNumArgs()) {
707   case 2:
708     if (checkOpenCLPipeArg(S, Call))
709       return true;
710     // The call with 2 arguments should be
711     // read/write_pipe(pipe T, T*).
712     // Check packet type T.
713     if (checkOpenCLPipePacketType(S, Call, 1))
714       return true;
715     break;
716 
717   case 4: {
718     if (checkOpenCLPipeArg(S, Call))
719       return true;
720     // The call with 4 arguments should be
721     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
722     // Check reserve_id_t.
723     if (!Call->getArg(1)->getType()->isReserveIDT()) {
724       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
725           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
726           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
727       return true;
728     }
729 
730     // Check the index.
731     const Expr *Arg2 = Call->getArg(2);
732     if (!Arg2->getType()->isIntegerType() &&
733         !Arg2->getType()->isUnsignedIntegerType()) {
734       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
735           << Call->getDirectCallee() << S.Context.UnsignedIntTy
736           << Arg2->getType() << Arg2->getSourceRange();
737       return true;
738     }
739 
740     // Check packet type T.
741     if (checkOpenCLPipePacketType(S, Call, 3))
742       return true;
743   } break;
744   default:
745     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
746         << Call->getDirectCallee() << Call->getSourceRange();
747     return true;
748   }
749 
750   return false;
751 }
752 
753 // Performs a semantic analysis on the {work_group_/sub_group_
754 //        /_}reserve_{read/write}_pipe
755 // \param S Reference to the semantic analyzer.
756 // \param Call The call to the builtin function to be analyzed.
757 // \return True if a semantic error was found, false otherwise.
758 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
759   if (checkArgCount(S, Call, 2))
760     return true;
761 
762   if (checkOpenCLPipeArg(S, Call))
763     return true;
764 
765   // Check the reserve size.
766   if (!Call->getArg(1)->getType()->isIntegerType() &&
767       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
768     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
769         << Call->getDirectCallee() << S.Context.UnsignedIntTy
770         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
771     return true;
772   }
773 
774   // Since return type of reserve_read/write_pipe built-in function is
775   // reserve_id_t, which is not defined in the builtin def file , we used int
776   // as return type and need to override the return type of these functions.
777   Call->setType(S.Context.OCLReserveIDTy);
778 
779   return false;
780 }
781 
782 // Performs a semantic analysis on {work_group_/sub_group_
783 //        /_}commit_{read/write}_pipe
784 // \param S Reference to the semantic analyzer.
785 // \param Call The call to the builtin function to be analyzed.
786 // \return True if a semantic error was found, false otherwise.
787 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
788   if (checkArgCount(S, Call, 2))
789     return true;
790 
791   if (checkOpenCLPipeArg(S, Call))
792     return true;
793 
794   // Check reserve_id_t.
795   if (!Call->getArg(1)->getType()->isReserveIDT()) {
796     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
797         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
798         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
799     return true;
800   }
801 
802   return false;
803 }
804 
805 // Performs a semantic analysis on the call to built-in Pipe
806 //        Query Functions.
807 // \param S Reference to the semantic analyzer.
808 // \param Call The call to the builtin function to be analyzed.
809 // \return True if a semantic error was found, false otherwise.
810 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
811   if (checkArgCount(S, Call, 1))
812     return true;
813 
814   if (!Call->getArg(0)->getType()->isPipeType()) {
815     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
816         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
817     return true;
818   }
819 
820   return false;
821 }
822 
823 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
824 // Performs semantic analysis for the to_global/local/private call.
825 // \param S Reference to the semantic analyzer.
826 // \param BuiltinID ID of the builtin function.
827 // \param Call A pointer to the builtin call.
828 // \return True if a semantic error has been found, false otherwise.
829 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
830                                     CallExpr *Call) {
831   if (Call->getNumArgs() != 1) {
832     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
833         << Call->getDirectCallee() << Call->getSourceRange();
834     return true;
835   }
836 
837   auto RT = Call->getArg(0)->getType();
838   if (!RT->isPointerType() || RT->getPointeeType()
839       .getAddressSpace() == LangAS::opencl_constant) {
840     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
841         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
842     return true;
843   }
844 
845   RT = RT->getPointeeType();
846   auto Qual = RT.getQualifiers();
847   switch (BuiltinID) {
848   case Builtin::BIto_global:
849     Qual.setAddressSpace(LangAS::opencl_global);
850     break;
851   case Builtin::BIto_local:
852     Qual.setAddressSpace(LangAS::opencl_local);
853     break;
854   case Builtin::BIto_private:
855     Qual.setAddressSpace(LangAS::opencl_private);
856     break;
857   default:
858     llvm_unreachable("Invalid builtin function");
859   }
860   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
861       RT.getUnqualifiedType(), Qual)));
862 
863   return false;
864 }
865 
866 // Emit an error and return true if the current architecture is not in the list
867 // of supported architectures.
868 static bool
869 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
870                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
871   llvm::Triple::ArchType CurArch =
872       S.getASTContext().getTargetInfo().getTriple().getArch();
873   if (llvm::is_contained(SupportedArchs, CurArch))
874     return false;
875   S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
876       << TheCall->getSourceRange();
877   return true;
878 }
879 
880 ExprResult
881 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
882                                CallExpr *TheCall) {
883   ExprResult TheCallResult(TheCall);
884 
885   // Find out if any arguments are required to be integer constant expressions.
886   unsigned ICEArguments = 0;
887   ASTContext::GetBuiltinTypeError Error;
888   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
889   if (Error != ASTContext::GE_None)
890     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
891 
892   // If any arguments are required to be ICE's, check and diagnose.
893   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
894     // Skip arguments not required to be ICE's.
895     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
896 
897     llvm::APSInt Result;
898     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
899       return true;
900     ICEArguments &= ~(1 << ArgNo);
901   }
902 
903   switch (BuiltinID) {
904   case Builtin::BI__builtin___CFStringMakeConstantString:
905     assert(TheCall->getNumArgs() == 1 &&
906            "Wrong # arguments to builtin CFStringMakeConstantString");
907     if (CheckObjCString(TheCall->getArg(0)))
908       return ExprError();
909     break;
910   case Builtin::BI__builtin_ms_va_start:
911   case Builtin::BI__builtin_stdarg_start:
912   case Builtin::BI__builtin_va_start:
913     if (SemaBuiltinVAStart(BuiltinID, TheCall))
914       return ExprError();
915     break;
916   case Builtin::BI__va_start: {
917     switch (Context.getTargetInfo().getTriple().getArch()) {
918     case llvm::Triple::arm:
919     case llvm::Triple::thumb:
920       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
921         return ExprError();
922       break;
923     default:
924       if (SemaBuiltinVAStart(BuiltinID, TheCall))
925         return ExprError();
926       break;
927     }
928     break;
929   }
930 
931   // The acquire, release, and no fence variants are ARM and AArch64 only.
932   case Builtin::BI_interlockedbittestandset_acq:
933   case Builtin::BI_interlockedbittestandset_rel:
934   case Builtin::BI_interlockedbittestandset_nf:
935   case Builtin::BI_interlockedbittestandreset_acq:
936   case Builtin::BI_interlockedbittestandreset_rel:
937   case Builtin::BI_interlockedbittestandreset_nf:
938     if (CheckBuiltinTargetSupport(
939             *this, BuiltinID, TheCall,
940             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
941       return ExprError();
942     break;
943 
944   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
945   case Builtin::BI_bittest64:
946   case Builtin::BI_bittestandcomplement64:
947   case Builtin::BI_bittestandreset64:
948   case Builtin::BI_bittestandset64:
949   case Builtin::BI_interlockedbittestandreset64:
950   case Builtin::BI_interlockedbittestandset64:
951     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
952                                   {llvm::Triple::x86_64, llvm::Triple::arm,
953                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
954       return ExprError();
955     break;
956 
957   case Builtin::BI__builtin_isgreater:
958   case Builtin::BI__builtin_isgreaterequal:
959   case Builtin::BI__builtin_isless:
960   case Builtin::BI__builtin_islessequal:
961   case Builtin::BI__builtin_islessgreater:
962   case Builtin::BI__builtin_isunordered:
963     if (SemaBuiltinUnorderedCompare(TheCall))
964       return ExprError();
965     break;
966   case Builtin::BI__builtin_fpclassify:
967     if (SemaBuiltinFPClassification(TheCall, 6))
968       return ExprError();
969     break;
970   case Builtin::BI__builtin_isfinite:
971   case Builtin::BI__builtin_isinf:
972   case Builtin::BI__builtin_isinf_sign:
973   case Builtin::BI__builtin_isnan:
974   case Builtin::BI__builtin_isnormal:
975   case Builtin::BI__builtin_signbit:
976   case Builtin::BI__builtin_signbitf:
977   case Builtin::BI__builtin_signbitl:
978     if (SemaBuiltinFPClassification(TheCall, 1))
979       return ExprError();
980     break;
981   case Builtin::BI__builtin_shufflevector:
982     return SemaBuiltinShuffleVector(TheCall);
983     // TheCall will be freed by the smart pointer here, but that's fine, since
984     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
985   case Builtin::BI__builtin_prefetch:
986     if (SemaBuiltinPrefetch(TheCall))
987       return ExprError();
988     break;
989   case Builtin::BI__builtin_alloca_with_align:
990     if (SemaBuiltinAllocaWithAlign(TheCall))
991       return ExprError();
992     break;
993   case Builtin::BI__assume:
994   case Builtin::BI__builtin_assume:
995     if (SemaBuiltinAssume(TheCall))
996       return ExprError();
997     break;
998   case Builtin::BI__builtin_assume_aligned:
999     if (SemaBuiltinAssumeAligned(TheCall))
1000       return ExprError();
1001     break;
1002   case Builtin::BI__builtin_object_size:
1003     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1004       return ExprError();
1005     break;
1006   case Builtin::BI__builtin_longjmp:
1007     if (SemaBuiltinLongjmp(TheCall))
1008       return ExprError();
1009     break;
1010   case Builtin::BI__builtin_setjmp:
1011     if (SemaBuiltinSetjmp(TheCall))
1012       return ExprError();
1013     break;
1014   case Builtin::BI_setjmp:
1015   case Builtin::BI_setjmpex:
1016     if (checkArgCount(*this, TheCall, 1))
1017       return true;
1018     break;
1019   case Builtin::BI__builtin_classify_type:
1020     if (checkArgCount(*this, TheCall, 1)) return true;
1021     TheCall->setType(Context.IntTy);
1022     break;
1023   case Builtin::BI__builtin_constant_p:
1024     if (checkArgCount(*this, TheCall, 1)) return true;
1025     TheCall->setType(Context.IntTy);
1026     break;
1027   case Builtin::BI__sync_fetch_and_add:
1028   case Builtin::BI__sync_fetch_and_add_1:
1029   case Builtin::BI__sync_fetch_and_add_2:
1030   case Builtin::BI__sync_fetch_and_add_4:
1031   case Builtin::BI__sync_fetch_and_add_8:
1032   case Builtin::BI__sync_fetch_and_add_16:
1033   case Builtin::BI__sync_fetch_and_sub:
1034   case Builtin::BI__sync_fetch_and_sub_1:
1035   case Builtin::BI__sync_fetch_and_sub_2:
1036   case Builtin::BI__sync_fetch_and_sub_4:
1037   case Builtin::BI__sync_fetch_and_sub_8:
1038   case Builtin::BI__sync_fetch_and_sub_16:
1039   case Builtin::BI__sync_fetch_and_or:
1040   case Builtin::BI__sync_fetch_and_or_1:
1041   case Builtin::BI__sync_fetch_and_or_2:
1042   case Builtin::BI__sync_fetch_and_or_4:
1043   case Builtin::BI__sync_fetch_and_or_8:
1044   case Builtin::BI__sync_fetch_and_or_16:
1045   case Builtin::BI__sync_fetch_and_and:
1046   case Builtin::BI__sync_fetch_and_and_1:
1047   case Builtin::BI__sync_fetch_and_and_2:
1048   case Builtin::BI__sync_fetch_and_and_4:
1049   case Builtin::BI__sync_fetch_and_and_8:
1050   case Builtin::BI__sync_fetch_and_and_16:
1051   case Builtin::BI__sync_fetch_and_xor:
1052   case Builtin::BI__sync_fetch_and_xor_1:
1053   case Builtin::BI__sync_fetch_and_xor_2:
1054   case Builtin::BI__sync_fetch_and_xor_4:
1055   case Builtin::BI__sync_fetch_and_xor_8:
1056   case Builtin::BI__sync_fetch_and_xor_16:
1057   case Builtin::BI__sync_fetch_and_nand:
1058   case Builtin::BI__sync_fetch_and_nand_1:
1059   case Builtin::BI__sync_fetch_and_nand_2:
1060   case Builtin::BI__sync_fetch_and_nand_4:
1061   case Builtin::BI__sync_fetch_and_nand_8:
1062   case Builtin::BI__sync_fetch_and_nand_16:
1063   case Builtin::BI__sync_add_and_fetch:
1064   case Builtin::BI__sync_add_and_fetch_1:
1065   case Builtin::BI__sync_add_and_fetch_2:
1066   case Builtin::BI__sync_add_and_fetch_4:
1067   case Builtin::BI__sync_add_and_fetch_8:
1068   case Builtin::BI__sync_add_and_fetch_16:
1069   case Builtin::BI__sync_sub_and_fetch:
1070   case Builtin::BI__sync_sub_and_fetch_1:
1071   case Builtin::BI__sync_sub_and_fetch_2:
1072   case Builtin::BI__sync_sub_and_fetch_4:
1073   case Builtin::BI__sync_sub_and_fetch_8:
1074   case Builtin::BI__sync_sub_and_fetch_16:
1075   case Builtin::BI__sync_and_and_fetch:
1076   case Builtin::BI__sync_and_and_fetch_1:
1077   case Builtin::BI__sync_and_and_fetch_2:
1078   case Builtin::BI__sync_and_and_fetch_4:
1079   case Builtin::BI__sync_and_and_fetch_8:
1080   case Builtin::BI__sync_and_and_fetch_16:
1081   case Builtin::BI__sync_or_and_fetch:
1082   case Builtin::BI__sync_or_and_fetch_1:
1083   case Builtin::BI__sync_or_and_fetch_2:
1084   case Builtin::BI__sync_or_and_fetch_4:
1085   case Builtin::BI__sync_or_and_fetch_8:
1086   case Builtin::BI__sync_or_and_fetch_16:
1087   case Builtin::BI__sync_xor_and_fetch:
1088   case Builtin::BI__sync_xor_and_fetch_1:
1089   case Builtin::BI__sync_xor_and_fetch_2:
1090   case Builtin::BI__sync_xor_and_fetch_4:
1091   case Builtin::BI__sync_xor_and_fetch_8:
1092   case Builtin::BI__sync_xor_and_fetch_16:
1093   case Builtin::BI__sync_nand_and_fetch:
1094   case Builtin::BI__sync_nand_and_fetch_1:
1095   case Builtin::BI__sync_nand_and_fetch_2:
1096   case Builtin::BI__sync_nand_and_fetch_4:
1097   case Builtin::BI__sync_nand_and_fetch_8:
1098   case Builtin::BI__sync_nand_and_fetch_16:
1099   case Builtin::BI__sync_val_compare_and_swap:
1100   case Builtin::BI__sync_val_compare_and_swap_1:
1101   case Builtin::BI__sync_val_compare_and_swap_2:
1102   case Builtin::BI__sync_val_compare_and_swap_4:
1103   case Builtin::BI__sync_val_compare_and_swap_8:
1104   case Builtin::BI__sync_val_compare_and_swap_16:
1105   case Builtin::BI__sync_bool_compare_and_swap:
1106   case Builtin::BI__sync_bool_compare_and_swap_1:
1107   case Builtin::BI__sync_bool_compare_and_swap_2:
1108   case Builtin::BI__sync_bool_compare_and_swap_4:
1109   case Builtin::BI__sync_bool_compare_and_swap_8:
1110   case Builtin::BI__sync_bool_compare_and_swap_16:
1111   case Builtin::BI__sync_lock_test_and_set:
1112   case Builtin::BI__sync_lock_test_and_set_1:
1113   case Builtin::BI__sync_lock_test_and_set_2:
1114   case Builtin::BI__sync_lock_test_and_set_4:
1115   case Builtin::BI__sync_lock_test_and_set_8:
1116   case Builtin::BI__sync_lock_test_and_set_16:
1117   case Builtin::BI__sync_lock_release:
1118   case Builtin::BI__sync_lock_release_1:
1119   case Builtin::BI__sync_lock_release_2:
1120   case Builtin::BI__sync_lock_release_4:
1121   case Builtin::BI__sync_lock_release_8:
1122   case Builtin::BI__sync_lock_release_16:
1123   case Builtin::BI__sync_swap:
1124   case Builtin::BI__sync_swap_1:
1125   case Builtin::BI__sync_swap_2:
1126   case Builtin::BI__sync_swap_4:
1127   case Builtin::BI__sync_swap_8:
1128   case Builtin::BI__sync_swap_16:
1129     return SemaBuiltinAtomicOverloaded(TheCallResult);
1130   case Builtin::BI__builtin_nontemporal_load:
1131   case Builtin::BI__builtin_nontemporal_store:
1132     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1133 #define BUILTIN(ID, TYPE, ATTRS)
1134 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1135   case Builtin::BI##ID: \
1136     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1137 #include "clang/Basic/Builtins.def"
1138   case Builtin::BI__annotation:
1139     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1140       return ExprError();
1141     break;
1142   case Builtin::BI__builtin_annotation:
1143     if (SemaBuiltinAnnotation(*this, TheCall))
1144       return ExprError();
1145     break;
1146   case Builtin::BI__builtin_addressof:
1147     if (SemaBuiltinAddressof(*this, TheCall))
1148       return ExprError();
1149     break;
1150   case Builtin::BI__builtin_add_overflow:
1151   case Builtin::BI__builtin_sub_overflow:
1152   case Builtin::BI__builtin_mul_overflow:
1153     if (SemaBuiltinOverflow(*this, TheCall))
1154       return ExprError();
1155     break;
1156   case Builtin::BI__builtin_operator_new:
1157   case Builtin::BI__builtin_operator_delete: {
1158     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1159     ExprResult Res =
1160         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1161     if (Res.isInvalid())
1162       CorrectDelayedTyposInExpr(TheCallResult.get());
1163     return Res;
1164   }
1165   case Builtin::BI__builtin_dump_struct: {
1166     // We first want to ensure we are called with 2 arguments
1167     if (checkArgCount(*this, TheCall, 2))
1168       return ExprError();
1169     // Ensure that the first argument is of type 'struct XX *'
1170     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1171     const QualType PtrArgType = PtrArg->getType();
1172     if (!PtrArgType->isPointerType() ||
1173         !PtrArgType->getPointeeType()->isRecordType()) {
1174       Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1175           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1176           << "structure pointer";
1177       return ExprError();
1178     }
1179 
1180     // Ensure that the second argument is of type 'FunctionType'
1181     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1182     const QualType FnPtrArgType = FnPtrArg->getType();
1183     if (!FnPtrArgType->isPointerType()) {
1184       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1185           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1186           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1187       return ExprError();
1188     }
1189 
1190     const auto *FuncType =
1191         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1192 
1193     if (!FuncType) {
1194       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1195           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1196           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1197       return ExprError();
1198     }
1199 
1200     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1201       if (!FT->getNumParams()) {
1202         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1203             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1204             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1205         return ExprError();
1206       }
1207       QualType PT = FT->getParamType(0);
1208       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1209           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1210           !PT->getPointeeType().isConstQualified()) {
1211         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1212             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1213             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1214         return ExprError();
1215       }
1216     }
1217 
1218     TheCall->setType(Context.IntTy);
1219     break;
1220   }
1221 
1222   // check secure string manipulation functions where overflows
1223   // are detectable at compile time
1224   case Builtin::BI__builtin___memcpy_chk:
1225   case Builtin::BI__builtin___memmove_chk:
1226   case Builtin::BI__builtin___memset_chk:
1227   case Builtin::BI__builtin___strlcat_chk:
1228   case Builtin::BI__builtin___strlcpy_chk:
1229   case Builtin::BI__builtin___strncat_chk:
1230   case Builtin::BI__builtin___strncpy_chk:
1231   case Builtin::BI__builtin___stpncpy_chk:
1232     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1233     break;
1234   case Builtin::BI__builtin___memccpy_chk:
1235     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1236     break;
1237   case Builtin::BI__builtin___snprintf_chk:
1238   case Builtin::BI__builtin___vsnprintf_chk:
1239     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1240     break;
1241   case Builtin::BI__builtin_call_with_static_chain:
1242     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1243       return ExprError();
1244     break;
1245   case Builtin::BI__exception_code:
1246   case Builtin::BI_exception_code:
1247     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1248                                  diag::err_seh___except_block))
1249       return ExprError();
1250     break;
1251   case Builtin::BI__exception_info:
1252   case Builtin::BI_exception_info:
1253     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1254                                  diag::err_seh___except_filter))
1255       return ExprError();
1256     break;
1257   case Builtin::BI__GetExceptionInfo:
1258     if (checkArgCount(*this, TheCall, 1))
1259       return ExprError();
1260 
1261     if (CheckCXXThrowOperand(
1262             TheCall->getLocStart(),
1263             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1264             TheCall))
1265       return ExprError();
1266 
1267     TheCall->setType(Context.VoidPtrTy);
1268     break;
1269   // OpenCL v2.0, s6.13.16 - Pipe functions
1270   case Builtin::BIread_pipe:
1271   case Builtin::BIwrite_pipe:
1272     // Since those two functions are declared with var args, we need a semantic
1273     // check for the argument.
1274     if (SemaBuiltinRWPipe(*this, TheCall))
1275       return ExprError();
1276     TheCall->setType(Context.IntTy);
1277     break;
1278   case Builtin::BIreserve_read_pipe:
1279   case Builtin::BIreserve_write_pipe:
1280   case Builtin::BIwork_group_reserve_read_pipe:
1281   case Builtin::BIwork_group_reserve_write_pipe:
1282     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1283       return ExprError();
1284     break;
1285   case Builtin::BIsub_group_reserve_read_pipe:
1286   case Builtin::BIsub_group_reserve_write_pipe:
1287     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1288         SemaBuiltinReserveRWPipe(*this, TheCall))
1289       return ExprError();
1290     break;
1291   case Builtin::BIcommit_read_pipe:
1292   case Builtin::BIcommit_write_pipe:
1293   case Builtin::BIwork_group_commit_read_pipe:
1294   case Builtin::BIwork_group_commit_write_pipe:
1295     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1296       return ExprError();
1297     break;
1298   case Builtin::BIsub_group_commit_read_pipe:
1299   case Builtin::BIsub_group_commit_write_pipe:
1300     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1301         SemaBuiltinCommitRWPipe(*this, TheCall))
1302       return ExprError();
1303     break;
1304   case Builtin::BIget_pipe_num_packets:
1305   case Builtin::BIget_pipe_max_packets:
1306     if (SemaBuiltinPipePackets(*this, TheCall))
1307       return ExprError();
1308     TheCall->setType(Context.UnsignedIntTy);
1309     break;
1310   case Builtin::BIto_global:
1311   case Builtin::BIto_local:
1312   case Builtin::BIto_private:
1313     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1314       return ExprError();
1315     break;
1316   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1317   case Builtin::BIenqueue_kernel:
1318     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1319       return ExprError();
1320     break;
1321   case Builtin::BIget_kernel_work_group_size:
1322   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1323     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1324       return ExprError();
1325     break;
1326   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1327   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1328     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1329       return ExprError();
1330     break;
1331   case Builtin::BI__builtin_os_log_format:
1332   case Builtin::BI__builtin_os_log_format_buffer_size:
1333     if (SemaBuiltinOSLogFormat(TheCall))
1334       return ExprError();
1335     break;
1336   }
1337 
1338   // Since the target specific builtins for each arch overlap, only check those
1339   // of the arch we are compiling for.
1340   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1341     switch (Context.getTargetInfo().getTriple().getArch()) {
1342       case llvm::Triple::arm:
1343       case llvm::Triple::armeb:
1344       case llvm::Triple::thumb:
1345       case llvm::Triple::thumbeb:
1346         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1347           return ExprError();
1348         break;
1349       case llvm::Triple::aarch64:
1350       case llvm::Triple::aarch64_be:
1351         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1352           return ExprError();
1353         break;
1354       case llvm::Triple::hexagon:
1355         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1356           return ExprError();
1357         break;
1358       case llvm::Triple::mips:
1359       case llvm::Triple::mipsel:
1360       case llvm::Triple::mips64:
1361       case llvm::Triple::mips64el:
1362         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1363           return ExprError();
1364         break;
1365       case llvm::Triple::systemz:
1366         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1367           return ExprError();
1368         break;
1369       case llvm::Triple::x86:
1370       case llvm::Triple::x86_64:
1371         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1372           return ExprError();
1373         break;
1374       case llvm::Triple::ppc:
1375       case llvm::Triple::ppc64:
1376       case llvm::Triple::ppc64le:
1377         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1378           return ExprError();
1379         break;
1380       default:
1381         break;
1382     }
1383   }
1384 
1385   return TheCallResult;
1386 }
1387 
1388 // Get the valid immediate range for the specified NEON type code.
1389 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1390   NeonTypeFlags Type(t);
1391   int IsQuad = ForceQuad ? true : Type.isQuad();
1392   switch (Type.getEltType()) {
1393   case NeonTypeFlags::Int8:
1394   case NeonTypeFlags::Poly8:
1395     return shift ? 7 : (8 << IsQuad) - 1;
1396   case NeonTypeFlags::Int16:
1397   case NeonTypeFlags::Poly16:
1398     return shift ? 15 : (4 << IsQuad) - 1;
1399   case NeonTypeFlags::Int32:
1400     return shift ? 31 : (2 << IsQuad) - 1;
1401   case NeonTypeFlags::Int64:
1402   case NeonTypeFlags::Poly64:
1403     return shift ? 63 : (1 << IsQuad) - 1;
1404   case NeonTypeFlags::Poly128:
1405     return shift ? 127 : (1 << IsQuad) - 1;
1406   case NeonTypeFlags::Float16:
1407     assert(!shift && "cannot shift float types!");
1408     return (4 << IsQuad) - 1;
1409   case NeonTypeFlags::Float32:
1410     assert(!shift && "cannot shift float types!");
1411     return (2 << IsQuad) - 1;
1412   case NeonTypeFlags::Float64:
1413     assert(!shift && "cannot shift float types!");
1414     return (1 << IsQuad) - 1;
1415   }
1416   llvm_unreachable("Invalid NeonTypeFlag!");
1417 }
1418 
1419 /// getNeonEltType - Return the QualType corresponding to the elements of
1420 /// the vector type specified by the NeonTypeFlags.  This is used to check
1421 /// the pointer arguments for Neon load/store intrinsics.
1422 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1423                                bool IsPolyUnsigned, bool IsInt64Long) {
1424   switch (Flags.getEltType()) {
1425   case NeonTypeFlags::Int8:
1426     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1427   case NeonTypeFlags::Int16:
1428     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1429   case NeonTypeFlags::Int32:
1430     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1431   case NeonTypeFlags::Int64:
1432     if (IsInt64Long)
1433       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1434     else
1435       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1436                                 : Context.LongLongTy;
1437   case NeonTypeFlags::Poly8:
1438     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1439   case NeonTypeFlags::Poly16:
1440     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1441   case NeonTypeFlags::Poly64:
1442     if (IsInt64Long)
1443       return Context.UnsignedLongTy;
1444     else
1445       return Context.UnsignedLongLongTy;
1446   case NeonTypeFlags::Poly128:
1447     break;
1448   case NeonTypeFlags::Float16:
1449     return Context.HalfTy;
1450   case NeonTypeFlags::Float32:
1451     return Context.FloatTy;
1452   case NeonTypeFlags::Float64:
1453     return Context.DoubleTy;
1454   }
1455   llvm_unreachable("Invalid NeonTypeFlag!");
1456 }
1457 
1458 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1459   llvm::APSInt Result;
1460   uint64_t mask = 0;
1461   unsigned TV = 0;
1462   int PtrArgNum = -1;
1463   bool HasConstPtr = false;
1464   switch (BuiltinID) {
1465 #define GET_NEON_OVERLOAD_CHECK
1466 #include "clang/Basic/arm_neon.inc"
1467 #include "clang/Basic/arm_fp16.inc"
1468 #undef GET_NEON_OVERLOAD_CHECK
1469   }
1470 
1471   // For NEON intrinsics which are overloaded on vector element type, validate
1472   // the immediate which specifies which variant to emit.
1473   unsigned ImmArg = TheCall->getNumArgs()-1;
1474   if (mask) {
1475     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1476       return true;
1477 
1478     TV = Result.getLimitedValue(64);
1479     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1480       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1481         << TheCall->getArg(ImmArg)->getSourceRange();
1482   }
1483 
1484   if (PtrArgNum >= 0) {
1485     // Check that pointer arguments have the specified type.
1486     Expr *Arg = TheCall->getArg(PtrArgNum);
1487     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1488       Arg = ICE->getSubExpr();
1489     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1490     QualType RHSTy = RHS.get()->getType();
1491 
1492     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1493     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1494                           Arch == llvm::Triple::aarch64_be;
1495     bool IsInt64Long =
1496         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1497     QualType EltTy =
1498         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1499     if (HasConstPtr)
1500       EltTy = EltTy.withConst();
1501     QualType LHSTy = Context.getPointerType(EltTy);
1502     AssignConvertType ConvTy;
1503     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1504     if (RHS.isInvalid())
1505       return true;
1506     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1507                                  RHS.get(), AA_Assigning))
1508       return true;
1509   }
1510 
1511   // For NEON intrinsics which take an immediate value as part of the
1512   // instruction, range check them here.
1513   unsigned i = 0, l = 0, u = 0;
1514   switch (BuiltinID) {
1515   default:
1516     return false;
1517   #define GET_NEON_IMMEDIATE_CHECK
1518   #include "clang/Basic/arm_neon.inc"
1519   #include "clang/Basic/arm_fp16.inc"
1520   #undef GET_NEON_IMMEDIATE_CHECK
1521   }
1522 
1523   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1524 }
1525 
1526 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1527                                         unsigned MaxWidth) {
1528   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1529           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1530           BuiltinID == ARM::BI__builtin_arm_strex ||
1531           BuiltinID == ARM::BI__builtin_arm_stlex ||
1532           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1533           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1534           BuiltinID == AArch64::BI__builtin_arm_strex ||
1535           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1536          "unexpected ARM builtin");
1537   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1538                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1539                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1540                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1541 
1542   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1543 
1544   // Ensure that we have the proper number of arguments.
1545   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1546     return true;
1547 
1548   // Inspect the pointer argument of the atomic builtin.  This should always be
1549   // a pointer type, whose element is an integral scalar or pointer type.
1550   // Because it is a pointer type, we don't have to worry about any implicit
1551   // casts here.
1552   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1553   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1554   if (PointerArgRes.isInvalid())
1555     return true;
1556   PointerArg = PointerArgRes.get();
1557 
1558   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1559   if (!pointerType) {
1560     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1561       << PointerArg->getType() << PointerArg->getSourceRange();
1562     return true;
1563   }
1564 
1565   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1566   // task is to insert the appropriate casts into the AST. First work out just
1567   // what the appropriate type is.
1568   QualType ValType = pointerType->getPointeeType();
1569   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1570   if (IsLdrex)
1571     AddrType.addConst();
1572 
1573   // Issue a warning if the cast is dodgy.
1574   CastKind CastNeeded = CK_NoOp;
1575   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1576     CastNeeded = CK_BitCast;
1577     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1578       << PointerArg->getType()
1579       << Context.getPointerType(AddrType)
1580       << AA_Passing << PointerArg->getSourceRange();
1581   }
1582 
1583   // Finally, do the cast and replace the argument with the corrected version.
1584   AddrType = Context.getPointerType(AddrType);
1585   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1586   if (PointerArgRes.isInvalid())
1587     return true;
1588   PointerArg = PointerArgRes.get();
1589 
1590   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1591 
1592   // In general, we allow ints, floats and pointers to be loaded and stored.
1593   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1594       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1595     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1596       << PointerArg->getType() << PointerArg->getSourceRange();
1597     return true;
1598   }
1599 
1600   // But ARM doesn't have instructions to deal with 128-bit versions.
1601   if (Context.getTypeSize(ValType) > MaxWidth) {
1602     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1603     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1604       << PointerArg->getType() << PointerArg->getSourceRange();
1605     return true;
1606   }
1607 
1608   switch (ValType.getObjCLifetime()) {
1609   case Qualifiers::OCL_None:
1610   case Qualifiers::OCL_ExplicitNone:
1611     // okay
1612     break;
1613 
1614   case Qualifiers::OCL_Weak:
1615   case Qualifiers::OCL_Strong:
1616   case Qualifiers::OCL_Autoreleasing:
1617     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1618       << ValType << PointerArg->getSourceRange();
1619     return true;
1620   }
1621 
1622   if (IsLdrex) {
1623     TheCall->setType(ValType);
1624     return false;
1625   }
1626 
1627   // Initialize the argument to be stored.
1628   ExprResult ValArg = TheCall->getArg(0);
1629   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1630       Context, ValType, /*consume*/ false);
1631   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1632   if (ValArg.isInvalid())
1633     return true;
1634   TheCall->setArg(0, ValArg.get());
1635 
1636   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1637   // but the custom checker bypasses all default analysis.
1638   TheCall->setType(Context.IntTy);
1639   return false;
1640 }
1641 
1642 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1643   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1644       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1645       BuiltinID == ARM::BI__builtin_arm_strex ||
1646       BuiltinID == ARM::BI__builtin_arm_stlex) {
1647     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1648   }
1649 
1650   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1651     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1652       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1653   }
1654 
1655   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1656       BuiltinID == ARM::BI__builtin_arm_wsr64)
1657     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1658 
1659   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1660       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1661       BuiltinID == ARM::BI__builtin_arm_wsr ||
1662       BuiltinID == ARM::BI__builtin_arm_wsrp)
1663     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1664 
1665   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1666     return true;
1667 
1668   // For intrinsics which take an immediate value as part of the instruction,
1669   // range check them here.
1670   // FIXME: VFP Intrinsics should error if VFP not present.
1671   switch (BuiltinID) {
1672   default: return false;
1673   case ARM::BI__builtin_arm_ssat:
1674     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1675   case ARM::BI__builtin_arm_usat:
1676     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1677   case ARM::BI__builtin_arm_ssat16:
1678     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1679   case ARM::BI__builtin_arm_usat16:
1680     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1681   case ARM::BI__builtin_arm_vcvtr_f:
1682   case ARM::BI__builtin_arm_vcvtr_d:
1683     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1684   case ARM::BI__builtin_arm_dmb:
1685   case ARM::BI__builtin_arm_dsb:
1686   case ARM::BI__builtin_arm_isb:
1687   case ARM::BI__builtin_arm_dbg:
1688     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1689   }
1690 }
1691 
1692 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1693                                          CallExpr *TheCall) {
1694   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1695       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1696       BuiltinID == AArch64::BI__builtin_arm_strex ||
1697       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1698     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1699   }
1700 
1701   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1702     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1703       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1704       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1705       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1706   }
1707 
1708   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1709       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1710     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1711 
1712   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1713       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1714       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1715       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1716     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1717 
1718   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1719     return true;
1720 
1721   // For intrinsics which take an immediate value as part of the instruction,
1722   // range check them here.
1723   unsigned i = 0, l = 0, u = 0;
1724   switch (BuiltinID) {
1725   default: return false;
1726   case AArch64::BI__builtin_arm_dmb:
1727   case AArch64::BI__builtin_arm_dsb:
1728   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1729   }
1730 
1731   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1732 }
1733 
1734 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1735   static const std::map<unsigned, std::vector<StringRef>> ValidCPU = {
1736     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, {"v65"} },
1737     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, {"v62", "v65"} },
1738     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, {"v62", "v65"} },
1739     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, {"v62", "v65"} },
1740     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {"v60", "v62", "v65"} },
1741     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {"v60", "v62", "v65"} },
1742     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {"v60", "v62", "v65"} },
1743     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {"v60", "v62", "v65"} },
1744     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {"v60", "v62", "v65"} },
1745     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {"v60", "v62", "v65"} },
1746     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {"v60", "v62", "v65"} },
1747     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {"v60", "v62", "v65"} },
1748     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {"v60", "v62", "v65"} },
1749     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {"v60", "v62", "v65"} },
1750     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {"v60", "v62", "v65"} },
1751     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {"v60", "v62", "v65"} },
1752     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, {"v62", "v65"} },
1753     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, {"v62", "v65"} },
1754     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, {"v62", "v65"} },
1755   };
1756 
1757   static const std::map<unsigned, std::vector<StringRef>> ValidHVX = {
1758     { Hexagon::BI__builtin_HEXAGON_V6_extractw, {"v60", "v62", "v65"} },
1759     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, {"v60", "v62", "v65"} },
1760     { Hexagon::BI__builtin_HEXAGON_V6_hi, {"v60", "v62", "v65"} },
1761     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, {"v60", "v62", "v65"} },
1762     { Hexagon::BI__builtin_HEXAGON_V6_lo, {"v60", "v62", "v65"} },
1763     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, {"v60", "v62", "v65"} },
1764     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, {"v62", "v65"} },
1765     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, {"v62", "v65"} },
1766     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, {"v62", "v65"} },
1767     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, {"v62", "v65"} },
1768     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, {"v60", "v62", "v65"} },
1769     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, {"v60", "v62", "v65"} },
1770     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, {"v60", "v62", "v65"} },
1771     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, {"v60", "v62", "v65"} },
1772     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, {"v60", "v62", "v65"} },
1773     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, {"v60", "v62", "v65"} },
1774     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, {"v60", "v62", "v65"} },
1775     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, {"v60", "v62", "v65"} },
1776     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, {"v60", "v62", "v65"} },
1777     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, {"v60", "v62", "v65"} },
1778     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, {"v60", "v62", "v65"} },
1779     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, {"v60", "v62", "v65"} },
1780     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, {"v60", "v62", "v65"} },
1781     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, {"v60", "v62", "v65"} },
1782     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, {"v62", "v65"} },
1783     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, {"v62", "v65"} },
1784     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, {"v60", "v62", "v65"} },
1785     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, {"v60", "v62", "v65"} },
1786     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, {"v62", "v65"} },
1787     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, {"v62", "v65"} },
1788     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, {"v62", "v65"} },
1789     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, {"v62", "v65"} },
1790     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, {"v65"} },
1791     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, {"v65"} },
1792     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, {"v65"} },
1793     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, {"v65"} },
1794     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, {"v60", "v62", "v65"} },
1795     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, {"v60", "v62", "v65"} },
1796     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, {"v60", "v62", "v65"} },
1797     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, {"v60", "v62", "v65"} },
1798     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, {"v60", "v62", "v65"} },
1799     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, {"v60", "v62", "v65"} },
1800     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, {"v60", "v62", "v65"} },
1801     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, {"v60", "v62", "v65"} },
1802     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, {"v60", "v62", "v65"} },
1803     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, {"v60", "v62", "v65"} },
1804     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, {"v60", "v62", "v65"} },
1805     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, {"v60", "v62", "v65"} },
1806     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, {"v60", "v62", "v65"} },
1807     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, {"v60", "v62", "v65"} },
1808     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, {"v60", "v62", "v65"} },
1809     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, {"v60", "v62", "v65"} },
1810     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, {"v60", "v62", "v65"} },
1811     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, {"v60", "v62", "v65"} },
1812     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, {"v60", "v62", "v65"} },
1813     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, {"v60", "v62", "v65"} },
1814     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, {"v62", "v65"} },
1815     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, {"v62", "v65"} },
1816     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, {"v62", "v65"} },
1817     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, {"v62", "v65"} },
1818     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, {"v62", "v65"} },
1819     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, {"v62", "v65"} },
1820     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, {"v62", "v65"} },
1821     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, {"v62", "v65"} },
1822     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, {"v62", "v65"} },
1823     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, {"v62", "v65"} },
1824     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, {"v60", "v62", "v65"} },
1825     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, {"v60", "v62", "v65"} },
1826     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, {"v60", "v62", "v65"} },
1827     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, {"v60", "v62", "v65"} },
1828     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, {"v60", "v62", "v65"} },
1829     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, {"v60", "v62", "v65"} },
1830     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, {"v60", "v62", "v65"} },
1831     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, {"v60", "v62", "v65"} },
1832     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, {"v60", "v62", "v65"} },
1833     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, {"v60", "v62", "v65"} },
1834     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, {"v62", "v65"} },
1835     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, {"v62", "v65"} },
1836     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, {"v60", "v62", "v65"} },
1837     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, {"v60", "v62", "v65"} },
1838     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, {"v62", "v65"} },
1839     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, {"v62", "v65"} },
1840     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, {"v60", "v62", "v65"} },
1841     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, {"v60", "v62", "v65"} },
1842     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, {"v60", "v62", "v65"} },
1843     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, {"v60", "v62", "v65"} },
1844     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, {"v62", "v65"} },
1845     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, {"v62", "v65"} },
1846     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, {"v60", "v62", "v65"} },
1847     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, {"v60", "v62", "v65"} },
1848     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, {"v60", "v62", "v65"} },
1849     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, {"v60", "v62", "v65"} },
1850     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, {"v60", "v62", "v65"} },
1851     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, {"v60", "v62", "v65"} },
1852     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, {"v62", "v65"} },
1853     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, {"v62", "v65"} },
1854     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, {"v62", "v65"} },
1855     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, {"v62", "v65"} },
1856     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, {"v62", "v65"} },
1857     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, {"v62", "v65"} },
1858     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, {"v60", "v62", "v65"} },
1859     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, {"v60", "v62", "v65"} },
1860     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, {"v60", "v62", "v65"} },
1861     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, {"v60", "v62", "v65"} },
1862     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, {"v60", "v62", "v65"} },
1863     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, {"v60", "v62", "v65"} },
1864     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, {"v60", "v62", "v65"} },
1865     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, {"v60", "v62", "v65"} },
1866     { Hexagon::BI__builtin_HEXAGON_V6_valignb, {"v60", "v62", "v65"} },
1867     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, {"v60", "v62", "v65"} },
1868     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {"v60", "v62", "v65"} },
1869     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {"v60", "v62", "v65"} },
1870     { Hexagon::BI__builtin_HEXAGON_V6_vand, {"v60", "v62", "v65"} },
1871     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, {"v60", "v62", "v65"} },
1872     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, {"v62", "v65"} },
1873     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, {"v62", "v65"} },
1874     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, {"v62", "v65"} },
1875     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, {"v62", "v65"} },
1876     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, {"v60", "v62", "v65"} },
1877     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, {"v60", "v62", "v65"} },
1878     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, {"v60", "v62", "v65"} },
1879     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, {"v60", "v62", "v65"} },
1880     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, {"v62", "v65"} },
1881     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, {"v62", "v65"} },
1882     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, {"v62", "v65"} },
1883     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, {"v62", "v65"} },
1884     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, {"v60", "v62", "v65"} },
1885     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, {"v60", "v62", "v65"} },
1886     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, {"v60", "v62", "v65"} },
1887     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, {"v60", "v62", "v65"} },
1888     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, {"v60", "v62", "v65"} },
1889     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, {"v60", "v62", "v65"} },
1890     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, {"v65"} },
1891     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, {"v65"} },
1892     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, {"v60", "v62", "v65"} },
1893     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, {"v60", "v62", "v65"} },
1894     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, {"v60", "v62", "v65"} },
1895     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, {"v60", "v62", "v65"} },
1896     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, {"v60", "v62", "v65"} },
1897     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, {"v60", "v62", "v65"} },
1898     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, {"v60", "v62", "v65"} },
1899     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, {"v60", "v62", "v65"} },
1900     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, {"v60", "v62", "v65"} },
1901     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, {"v60", "v62", "v65"} },
1902     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, {"v65"} },
1903     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, {"v65"} },
1904     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, {"v60", "v62", "v65"} },
1905     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, {"v60", "v62", "v65"} },
1906     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, {"v62", "v65"} },
1907     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, {"v62", "v65"} },
1908     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, {"v60", "v62", "v65"} },
1909     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, {"v60", "v62", "v65"} },
1910     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, {"v60", "v62", "v65"} },
1911     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, {"v60", "v62", "v65"} },
1912     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, {"v60", "v62", "v65"} },
1913     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, {"v60", "v62", "v65"} },
1914     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, {"v65"} },
1915     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, {"v65"} },
1916     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, {"v65"} },
1917     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, {"v65"} },
1918     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, {"v62", "v65"} },
1919     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, {"v62", "v65"} },
1920     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, {"v65"} },
1921     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, {"v65"} },
1922     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, {"v60", "v62", "v65"} },
1923     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, {"v60", "v62", "v65"} },
1924     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, {"v60", "v62", "v65"} },
1925     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, {"v60", "v62", "v65"} },
1926     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, {"v60", "v62", "v65"} },
1927     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, {"v60", "v62", "v65"} },
1928     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, {"v60", "v62", "v65"} },
1929     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, {"v60", "v62", "v65"} },
1930     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, {"v60", "v62", "v65"} },
1931     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, {"v60", "v62", "v65"} },
1932     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, {"v62", "v65"} },
1933     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, {"v62", "v65"} },
1934     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, {"v60", "v62", "v65"} },
1935     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, {"v60", "v62", "v65"} },
1936     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, {"v60", "v62", "v65"} },
1937     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, {"v60", "v62", "v65"} },
1938     { Hexagon::BI__builtin_HEXAGON_V6_vassign, {"v60", "v62", "v65"} },
1939     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, {"v60", "v62", "v65"} },
1940     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, {"v60", "v62", "v65"} },
1941     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, {"v60", "v62", "v65"} },
1942     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, {"v65"} },
1943     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, {"v65"} },
1944     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, {"v65"} },
1945     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, {"v65"} },
1946     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, {"v60", "v62", "v65"} },
1947     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, {"v60", "v62", "v65"} },
1948     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, {"v60", "v62", "v65"} },
1949     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, {"v60", "v62", "v65"} },
1950     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, {"v60", "v62", "v65"} },
1951     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, {"v60", "v62", "v65"} },
1952     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, {"v60", "v62", "v65"} },
1953     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, {"v60", "v62", "v65"} },
1954     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, {"v60", "v62", "v65"} },
1955     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, {"v60", "v62", "v65"} },
1956     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, {"v60", "v62", "v65"} },
1957     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, {"v60", "v62", "v65"} },
1958     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, {"v65"} },
1959     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, {"v65"} },
1960     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, {"v65"} },
1961     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, {"v65"} },
1962     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, {"v60", "v62", "v65"} },
1963     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, {"v60", "v62", "v65"} },
1964     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, {"v60", "v62", "v65"} },
1965     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, {"v60", "v62", "v65"} },
1966     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, {"v60", "v62", "v65"} },
1967     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, {"v60", "v62", "v65"} },
1968     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, {"v60", "v62", "v65"} },
1969     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, {"v60", "v62", "v65"} },
1970     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, {"v60", "v62", "v65"} },
1971     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, {"v60", "v62", "v65"} },
1972     { Hexagon::BI__builtin_HEXAGON_V6_vd0, {"v60", "v62", "v65"} },
1973     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, {"v60", "v62", "v65"} },
1974     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, {"v65"} },
1975     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, {"v65"} },
1976     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, {"v60", "v62", "v65"} },
1977     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, {"v60", "v62", "v65"} },
1978     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, {"v60", "v62", "v65"} },
1979     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, {"v60", "v62", "v65"} },
1980     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, {"v60", "v62", "v65"} },
1981     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, {"v60", "v62", "v65"} },
1982     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, {"v60", "v62", "v65"} },
1983     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, {"v60", "v62", "v65"} },
1984     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, {"v60", "v62", "v65"} },
1985     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, {"v60", "v62", "v65"} },
1986     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, {"v60", "v62", "v65"} },
1987     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, {"v60", "v62", "v65"} },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, {"v60", "v62", "v65"} },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, {"v60", "v62", "v65"} },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, {"v60", "v62", "v65"} },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, {"v60", "v62", "v65"} },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, {"v60", "v62", "v65"} },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, {"v60", "v62", "v65"} },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, {"v60", "v62", "v65"} },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, {"v60", "v62", "v65"} },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, {"v60", "v62", "v65"} },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, {"v60", "v62", "v65"} },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, {"v60", "v62", "v65"} },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, {"v60", "v62", "v65"} },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, {"v60", "v62", "v65"} },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, {"v60", "v62", "v65"} },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, {"v60", "v62", "v65"} },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, {"v60", "v62", "v65"} },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, {"v60", "v62", "v65"} },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, {"v60", "v62", "v65"} },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, {"v60", "v62", "v65"} },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, {"v60", "v62", "v65"} },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, {"v60", "v62", "v65"} },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, {"v60", "v62", "v65"} },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, {"v60", "v62", "v65"} },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, {"v60", "v62", "v65"} },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, {"v60", "v62", "v65"} },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, {"v60", "v62", "v65"} },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, {"v60", "v62", "v65"} },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, {"v60", "v62", "v65"} },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, {"v60", "v62", "v65"} },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, {"v60", "v62", "v65"} },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, {"v60", "v62", "v65"} },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, {"v60", "v62", "v65"} },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, {"v60", "v62", "v65"} },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, {"v60", "v62", "v65"} },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, {"v60", "v62", "v65"} },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, {"v60", "v62", "v65"} },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, {"v60", "v62", "v65"} },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, {"v60", "v62", "v65"} },
2026     { Hexagon::BI__builtin_HEXAGON_V6_veqb, {"v60", "v62", "v65"} },
2027     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, {"v60", "v62", "v65"} },
2028     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, {"v60", "v62", "v65"} },
2029     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, {"v60", "v62", "v65"} },
2030     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, {"v60", "v62", "v65"} },
2031     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, {"v60", "v62", "v65"} },
2032     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, {"v60", "v62", "v65"} },
2033     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, {"v60", "v62", "v65"} },
2034     { Hexagon::BI__builtin_HEXAGON_V6_veqh, {"v60", "v62", "v65"} },
2035     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, {"v60", "v62", "v65"} },
2036     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, {"v60", "v62", "v65"} },
2037     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, {"v60", "v62", "v65"} },
2038     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, {"v60", "v62", "v65"} },
2039     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, {"v60", "v62", "v65"} },
2040     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, {"v60", "v62", "v65"} },
2041     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, {"v60", "v62", "v65"} },
2042     { Hexagon::BI__builtin_HEXAGON_V6_veqw, {"v60", "v62", "v65"} },
2043     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, {"v60", "v62", "v65"} },
2044     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, {"v60", "v62", "v65"} },
2045     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, {"v60", "v62", "v65"} },
2046     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, {"v60", "v62", "v65"} },
2047     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, {"v60", "v62", "v65"} },
2048     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, {"v60", "v62", "v65"} },
2049     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, {"v60", "v62", "v65"} },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, {"v60", "v62", "v65"} },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, {"v60", "v62", "v65"} },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, {"v60", "v62", "v65"} },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, {"v60", "v62", "v65"} },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, {"v60", "v62", "v65"} },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, {"v60", "v62", "v65"} },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, {"v60", "v62", "v65"} },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, {"v60", "v62", "v65"} },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vgth, {"v60", "v62", "v65"} },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, {"v60", "v62", "v65"} },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, {"v60", "v62", "v65"} },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, {"v60", "v62", "v65"} },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, {"v60", "v62", "v65"} },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, {"v60", "v62", "v65"} },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, {"v60", "v62", "v65"} },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, {"v60", "v62", "v65"} },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, {"v60", "v62", "v65"} },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, {"v60", "v62", "v65"} },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, {"v60", "v62", "v65"} },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, {"v60", "v62", "v65"} },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, {"v60", "v62", "v65"} },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, {"v60", "v62", "v65"} },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, {"v60", "v62", "v65"} },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, {"v60", "v62", "v65"} },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, {"v60", "v62", "v65"} },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, {"v60", "v62", "v65"} },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, {"v60", "v62", "v65"} },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, {"v60", "v62", "v65"} },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, {"v60", "v62", "v65"} },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, {"v60", "v62", "v65"} },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, {"v60", "v62", "v65"} },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, {"v60", "v62", "v65"} },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, {"v60", "v62", "v65"} },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, {"v60", "v62", "v65"} },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, {"v60", "v62", "v65"} },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, {"v60", "v62", "v65"} },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, {"v60", "v62", "v65"} },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, {"v60", "v62", "v65"} },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, {"v60", "v62", "v65"} },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, {"v60", "v62", "v65"} },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, {"v60", "v62", "v65"} },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, {"v60", "v62", "v65"} },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, {"v60", "v62", "v65"} },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, {"v60", "v62", "v65"} },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, {"v60", "v62", "v65"} },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, {"v60", "v62", "v65"} },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, {"v60", "v62", "v65"} },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, {"v60", "v62", "v65"} },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, {"v60", "v62", "v65"} },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, {"v60", "v62", "v65"} },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, {"v60", "v62", "v65"} },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, {"v60", "v62", "v65"} },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {"v60", "v62", "v65"} },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {"v60", "v62", "v65"} },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, {"v62", "v65"} },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, {"v62", "v65"} },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, {"v60", "v62", "v65"} },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, {"v60", "v62", "v65"} },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, {"v60", "v62", "v65"} },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, {"v60", "v62", "v65"} },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, {"v60", "v62", "v65"} },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, {"v60", "v62", "v65"} },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, {"v60", "v62", "v65"} },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, {"v60", "v62", "v65"} },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, {"v65"} },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, {"v65"} },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, {"v60", "v62", "v65"} },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, {"v60", "v62", "v65"} },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {"v62", "v65"} },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {"v62", "v65"} },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, {"v62", "v65"} },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, {"v62", "v65"} },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, {"v60", "v62", "v65"} },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, {"v60", "v62", "v65"} },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {"v62", "v65"} },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, {"v62", "v65"} },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, {"v60", "v62", "v65"} },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, {"v60", "v62", "v65"} },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {"v62", "v65"} },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {"v62", "v65"} },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, {"v62", "v65"} },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, {"v62", "v65"} },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, {"v60", "v62", "v65"} },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, {"v60", "v62", "v65"} },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {"v62", "v65"} },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, {"v62", "v65"} },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, {"v62", "v65"} },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, {"v62", "v65"} },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, {"v60", "v62", "v65"} },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, {"v60", "v62", "v65"} },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, {"v60", "v62", "v65"} },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, {"v60", "v62", "v65"} },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, {"v60", "v62", "v65"} },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, {"v60", "v62", "v65"} },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, {"v60", "v62", "v65"} },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, {"v60", "v62", "v65"} },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vminb, {"v62", "v65"} },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, {"v62", "v65"} },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vminh, {"v60", "v62", "v65"} },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, {"v60", "v62", "v65"} },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vminub, {"v60", "v62", "v65"} },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, {"v60", "v62", "v65"} },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, {"v60", "v62", "v65"} },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, {"v60", "v62", "v65"} },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vminw, {"v60", "v62", "v65"} },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, {"v60", "v62", "v65"} },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, {"v60", "v62", "v65"} },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, {"v60", "v62", "v65"} },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, {"v60", "v62", "v65"} },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, {"v60", "v62", "v65"} },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, {"v60", "v62", "v65"} },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, {"v60", "v62", "v65"} },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, {"v65"} },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, {"v65"} },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, {"v65"} },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, {"v65"} },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, {"v60", "v62", "v65"} },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, {"v60", "v62", "v65"} },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, {"v60", "v62", "v65"} },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, {"v60", "v62", "v65"} },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, {"v60", "v62", "v65"} },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, {"v60", "v62", "v65"} },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, {"v65"} },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, {"v65"} },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, {"v62", "v65"} },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, {"v62", "v65"} },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, {"v62", "v65"} },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, {"v62", "v65"} },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, {"v65"} },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, {"v65"} },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, {"v65"} },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, {"v65"} },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, {"v60", "v62", "v65"} },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, {"v60", "v62", "v65"} },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, {"v60", "v62", "v65"} },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, {"v60", "v62", "v65"} },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, {"v60", "v62", "v65"} },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, {"v60", "v62", "v65"} },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, {"v60", "v62", "v65"} },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, {"v60", "v62", "v65"} },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, {"v60", "v62", "v65"} },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, {"v60", "v62", "v65"} },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, {"v60", "v62", "v65"} },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, {"v60", "v62", "v65"} },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, {"v60", "v62", "v65"} },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, {"v60", "v62", "v65"} },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, {"v62", "v65"} },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, {"v62", "v65"} },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, {"v60", "v62", "v65"} },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, {"v60", "v62", "v65"} },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, {"v65"} },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, {"v65"} },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, {"v60", "v62", "v65"} },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, {"v60", "v62", "v65"} },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, {"v60", "v62", "v65"} },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, {"v60", "v62", "v65"} },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, {"v60", "v62", "v65"} },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, {"v60", "v62", "v65"} },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, {"v60", "v62", "v65"} },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, {"v60", "v62", "v65"} },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, {"v60", "v62", "v65"} },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, {"v60", "v62", "v65"} },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, {"v60", "v62", "v65"} },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, {"v60", "v62", "v65"} },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, {"v60", "v62", "v65"} },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, {"v60", "v62", "v65"} },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, {"v60", "v62", "v65"} },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, {"v60", "v62", "v65"} },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, {"v60", "v62", "v65"} },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, {"v60", "v62", "v65"} },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, {"v60", "v62", "v65"} },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, {"v60", "v62", "v65"} },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, {"v60", "v62", "v65"} },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, {"v60", "v62", "v65"} },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, {"v60", "v62", "v65"} },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, {"v60", "v62", "v65"} },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, {"v60", "v62", "v65"} },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, {"v60", "v62", "v65"} },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, {"v60", "v62", "v65"} },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, {"v60", "v62", "v65"} },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, {"v60", "v62", "v65"} },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, {"v60", "v62", "v65"} },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, {"v60", "v62", "v65"} },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, {"v60", "v62", "v65"} },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, {"v60", "v62", "v65"} },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, {"v60", "v62", "v65"} },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, {"v60", "v62", "v65"} },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, {"v60", "v62", "v65"} },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, {"v60", "v62", "v65"} },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, {"v60", "v62", "v65"} },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, {"v60", "v62", "v65"} },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, {"v60", "v62", "v65"} },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, {"v60", "v62", "v65"} },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, {"v60", "v62", "v65"} },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, {"v62", "v65"} },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, {"v62", "v65"} },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, {"v62", "v65"} },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, {"v62", "v65"} },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, {"v60", "v62", "v65"} },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, {"v60", "v62", "v65"} },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, {"v62", "v65"} },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, {"v62", "v65"} },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, {"v60", "v62", "v65"} },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, {"v60", "v62", "v65"} },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, {"v60", "v62", "v65"} },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, {"v60", "v62", "v65"} },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, {"v60", "v62", "v65"} },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, {"v60", "v62", "v65"} },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, {"v60", "v62", "v65"} },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, {"v60", "v62", "v65"} },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, {"v60", "v62", "v65"} },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, {"v60", "v62", "v65"} },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, {"v60", "v62", "v65"} },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, {"v60", "v62", "v65"} },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, {"v60", "v62", "v65"} },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, {"v60", "v62", "v65"} },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, {"v60", "v62", "v65"} },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, {"v60", "v62", "v65"} },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, {"v60", "v62", "v65"} },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, {"v60", "v62", "v65"} },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, {"v65"} },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, {"v65"} },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, {"v65"} },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, {"v65"} },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, {"v60", "v62", "v65"} },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, {"v60", "v62", "v65"} },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, {"v60", "v62", "v65"} },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, {"v60", "v62", "v65"} },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vmux, {"v60", "v62", "v65"} },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, {"v60", "v62", "v65"} },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, {"v65"} },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, {"v65"} },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, {"v60", "v62", "v65"} },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, {"v60", "v62", "v65"} },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, {"v60", "v62", "v65"} },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, {"v60", "v62", "v65"} },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, {"v60", "v62", "v65"} },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, {"v60", "v62", "v65"} },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, {"v60", "v62", "v65"} },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, {"v60", "v62", "v65"} },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, {"v60", "v62", "v65"} },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, {"v60", "v62", "v65"} },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vnot, {"v60", "v62", "v65"} },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, {"v60", "v62", "v65"} },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vor, {"v60", "v62", "v65"} },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, {"v60", "v62", "v65"} },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, {"v60", "v62", "v65"} },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, {"v60", "v62", "v65"} },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, {"v60", "v62", "v65"} },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, {"v60", "v62", "v65"} },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, {"v60", "v62", "v65"} },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, {"v60", "v62", "v65"} },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, {"v60", "v62", "v65"} },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, {"v60", "v62", "v65"} },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, {"v60", "v62", "v65"} },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, {"v60", "v62", "v65"} },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, {"v60", "v62", "v65"} },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, {"v60", "v62", "v65"} },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, {"v60", "v62", "v65"} },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, {"v60", "v62", "v65"} },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, {"v60", "v62", "v65"} },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, {"v60", "v62", "v65"} },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, {"v60", "v62", "v65"} },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, {"v60", "v62", "v65"} },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, {"v65"} },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, {"v65"} },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, {"v65"} },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, {"v65"} },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, {"v65"} },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, {"v65"} },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, {"v60", "v62", "v65"} },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, {"v60", "v62", "v65"} },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, {"v65"} },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, {"v65"} },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, {"v65"} },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, {"v65"} },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, {"v60", "v62", "v65"} },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, {"v60", "v62", "v65"} },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, {"v60", "v62", "v65"} },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, {"v60", "v62", "v65"} },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {"v60", "v62", "v65"} },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {"v60", "v62", "v65"} },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {"v60", "v62", "v65"} },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, {"v60", "v62", "v65"} },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, {"v60", "v62", "v65"} },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, {"v60", "v62", "v65"} },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, {"v60", "v62", "v65"} },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, {"v60", "v62", "v65"} },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, {"v60", "v62", "v65"} },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, {"v60", "v62", "v65"} },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, {"v60", "v62", "v65"} },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, {"v60", "v62", "v65"} },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, {"v60", "v62", "v65"} },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, {"v60", "v62", "v65"} },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, {"v60", "v62", "v65"} },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, {"v60", "v62", "v65"} },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {"v60", "v62", "v65"} },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {"v60", "v62", "v65"} },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {"v60", "v62", "v65"} },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, {"v60", "v62", "v65"} },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, {"v65"} },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, {"v65"} },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, {"v65"} },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, {"v65"} },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, {"v60", "v62", "v65"} },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, {"v60", "v62", "v65"} },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, {"v60", "v62", "v65"} },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, {"v60", "v62", "v65"} },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vror, {"v60", "v62", "v65"} },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, {"v60", "v62", "v65"} },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, {"v60", "v62", "v65"} },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, {"v60", "v62", "v65"} },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, {"v60", "v62", "v65"} },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, {"v60", "v62", "v65"} },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, {"v62", "v65"} },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, {"v62", "v65"} },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, {"v62", "v65"} },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, {"v62", "v65"} },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, {"v60", "v62", "v65"} },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, {"v60", "v62", "v65"} },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, {"v60", "v62", "v65"} },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, {"v60", "v62", "v65"} },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {"v60", "v62", "v65"} },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {"v60", "v62", "v65"} },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {"v60", "v62", "v65"} },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, {"v60", "v62", "v65"} },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, {"v60", "v62", "v65"} },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, {"v60", "v62", "v65"} },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, {"v62", "v65"} },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, {"v62", "v65"} },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, {"v60", "v62", "v65"} },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, {"v60", "v62", "v65"} },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vsb, {"v60", "v62", "v65"} },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, {"v60", "v62", "v65"} },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vsh, {"v60", "v62", "v65"} },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, {"v60", "v62", "v65"} },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, {"v60", "v62", "v65"} },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, {"v60", "v62", "v65"} },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, {"v60", "v62", "v65"} },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, {"v60", "v62", "v65"} },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, {"v60", "v62", "v65"} },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, {"v60", "v62", "v65"} },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, {"v60", "v62", "v65"} },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, {"v60", "v62", "v65"} },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, {"v60", "v62", "v65"} },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, {"v60", "v62", "v65"} },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, {"v60", "v62", "v65"} },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, {"v60", "v62", "v65"} },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, {"v60", "v62", "v65"} },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, {"v60", "v62", "v65"} },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, {"v60", "v62", "v65"} },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, {"v60", "v62", "v65"} },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, {"v60", "v62", "v65"} },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, {"v60", "v62", "v65"} },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, {"v60", "v62", "v65"} },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, {"v60", "v62", "v65"} },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, {"v60", "v62", "v65"} },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, {"v60", "v62", "v65"} },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, {"v62", "v65"} },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, {"v62", "v65"} },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, {"v62", "v65"} },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, {"v62", "v65"} },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, {"v62", "v65"} },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, {"v62", "v65"} },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, {"v60", "v62", "v65"} },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, {"v60", "v62", "v65"} },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, {"v60", "v62", "v65"} },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, {"v60", "v62", "v65"} },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, {"v60", "v62", "v65"} },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, {"v60", "v62", "v65"} },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, {"v60", "v62", "v65"} },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, {"v60", "v62", "v65"} },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, {"v60", "v62", "v65"} },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, {"v60", "v62", "v65"} },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, {"v60", "v62", "v65"} },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, {"v60", "v62", "v65"} },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, {"v60", "v62", "v65"} },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, {"v60", "v62", "v65"} },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, {"v60", "v62", "v65"} },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, {"v60", "v62", "v65"} },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, {"v62", "v65"} },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, {"v62", "v65"} },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, {"v60", "v62", "v65"} },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, {"v60", "v62", "v65"} },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, {"v60", "v62", "v65"} },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, {"v60", "v62", "v65"} },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, {"v60", "v62", "v65"} },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, {"v60", "v62", "v65"} },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, {"v62", "v65"} },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, {"v62", "v65"} },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, {"v62", "v65"} },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, {"v62", "v65"} },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, {"v60", "v62", "v65"} },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, {"v60", "v62", "v65"} },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, {"v60", "v62", "v65"} },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, {"v60", "v62", "v65"} },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, {"v60", "v62", "v65"} },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, {"v60", "v62", "v65"} },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, {"v60", "v62", "v65"} },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, {"v60", "v62", "v65"} },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vswap, {"v60", "v62", "v65"} },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, {"v60", "v62", "v65"} },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, {"v60", "v62", "v65"} },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, {"v60", "v62", "v65"} },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, {"v60", "v62", "v65"} },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, {"v60", "v62", "v65"} },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, {"v60", "v62", "v65"} },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, {"v60", "v62", "v65"} },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, {"v60", "v62", "v65"} },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, {"v60", "v62", "v65"} },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, {"v60", "v62", "v65"} },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, {"v60", "v62", "v65"} },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, {"v60", "v62", "v65"} },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, {"v60", "v62", "v65"} },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, {"v60", "v62", "v65"} },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, {"v60", "v62", "v65"} },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, {"v60", "v62", "v65"} },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, {"v60", "v62", "v65"} },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, {"v60", "v62", "v65"} },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, {"v60", "v62", "v65"} },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, {"v60", "v62", "v65"} },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, {"v60", "v62", "v65"} },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, {"v60", "v62", "v65"} },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, {"v60", "v62", "v65"} },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, {"v60", "v62", "v65"} },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, {"v60", "v62", "v65"} },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vxor, {"v60", "v62", "v65"} },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, {"v60", "v62", "v65"} },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vzb, {"v60", "v62", "v65"} },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, {"v60", "v62", "v65"} },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vzh, {"v60", "v62", "v65"} },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, {"v60", "v62", "v65"} },
2482   };
2483 
2484   const TargetInfo &TI = Context.getTargetInfo();
2485 
2486   auto FC = ValidCPU.find(BuiltinID);
2487   if (FC != ValidCPU.end()) {
2488     const TargetOptions &Opts = TI.getTargetOpts();
2489     StringRef CPU = Opts.CPU;
2490     if (!CPU.empty()) {
2491       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2492       CPU.consume_front("hexagon");
2493       if (llvm::none_of(FC->second, [CPU](StringRef S) { return S == CPU; }))
2494         return Diag(TheCall->getLocStart(),
2495                     diag::err_hexagon_builtin_unsupported_cpu);
2496     }
2497   }
2498 
2499   auto FH = ValidHVX.find(BuiltinID);
2500   if (FH != ValidHVX.end()) {
2501     if (!TI.hasFeature("hvx"))
2502       return Diag(TheCall->getLocStart(),
2503                   diag::err_hexagon_builtin_requires_hvx);
2504 
2505     bool IsValid = llvm::any_of(FH->second,
2506                                 [&TI] (StringRef V) {
2507                                   std::string F = "hvx" + V.str();
2508                                   return TI.hasFeature(F);
2509                                 });
2510     if (!IsValid)
2511       return Diag(TheCall->getLocStart(),
2512                   diag::err_hexagon_builtin_unsupported_hvx);
2513   }
2514 
2515   return false;
2516 }
2517 
2518 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2519   struct ArgInfo {
2520     ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
2521       : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
2522     unsigned OpNum = 0;
2523     bool IsSigned = false;
2524     unsigned BitWidth = 0;
2525     unsigned Align = 0;
2526   };
2527 
2528   static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
2529     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2530     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2531     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2532     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2533     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2534     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2535     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2536     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2537     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2538     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2539     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2540 
2541     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2542     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2543     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2544     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2545     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2546     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2547     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2548     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2549     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2550     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2551     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2552 
2553     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2554     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2555     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2556     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2557     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2558     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2559     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2560     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2561     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2562     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2563     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2564     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2565     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2566     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2567     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2568     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2569     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2570     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2571     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2572     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2573     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2574     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2575     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2576     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2577     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2578     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2579     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2580     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2581     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2582     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2583     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2584     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2585     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2586     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2587     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2588     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2589     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2590     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2591     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2592     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2593     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2594     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2595     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2596     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2597     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2598     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2599     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2600     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2601     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2602     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2603     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2604     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2605                                                       {{ 1, false, 6,  0 }} },
2606     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2607     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2608     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2610     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2611     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2612     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2613                                                       {{ 1, false, 5,  0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2615     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2616     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2617     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2618     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2619     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2620                                                        { 2, false, 5,  0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2622                                                        { 2, false, 6,  0 }} },
2623     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2624                                                        { 3, false, 5,  0 }} },
2625     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2626                                                        { 3, false, 6,  0 }} },
2627     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2629     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2636     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2637     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2641     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2643                                                       {{ 2, false, 4,  0 },
2644                                                        { 3, false, 5,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2646                                                       {{ 2, false, 4,  0 },
2647                                                        { 3, false, 5,  0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2649                                                       {{ 2, false, 4,  0 },
2650                                                        { 3, false, 5,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2652                                                       {{ 2, false, 4,  0 },
2653                                                        { 3, false, 5,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2665                                                        { 2, false, 5,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2667                                                        { 2, false, 6,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2677                                                       {{ 1, false, 4,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2679     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2680                                                       {{ 1, false, 4,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2701                                                       {{ 3, false, 1,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2706                                                       {{ 3, false, 1,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2711                                                       {{ 3, false, 1,  0 }} },
2712   };
2713 
2714   auto F = Infos.find(BuiltinID);
2715   if (F == Infos.end())
2716     return false;
2717 
2718   bool Error = false;
2719 
2720   for (const ArgInfo &A : F->second) {
2721     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
2722     int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
2723     if (!A.Align) {
2724       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2725     } else {
2726       unsigned M = 1 << A.Align;
2727       Min *= M;
2728       Max *= M;
2729       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2730                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2731     }
2732   }
2733   return Error;
2734 }
2735 
2736 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2737                                            CallExpr *TheCall) {
2738   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2739          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2740 }
2741 
2742 
2743 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2744 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2745 // ordering for DSP is unspecified. MSA is ordered by the data format used
2746 // by the underlying instruction i.e., df/m, df/n and then by size.
2747 //
2748 // FIXME: The size tests here should instead be tablegen'd along with the
2749 //        definitions from include/clang/Basic/BuiltinsMips.def.
2750 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2751 //        be too.
2752 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2753   unsigned i = 0, l = 0, u = 0, m = 0;
2754   switch (BuiltinID) {
2755   default: return false;
2756   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2757   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2758   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2759   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2760   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2761   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2762   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2763   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
2764   // df/m field.
2765   // These intrinsics take an unsigned 3 bit immediate.
2766   case Mips::BI__builtin_msa_bclri_b:
2767   case Mips::BI__builtin_msa_bnegi_b:
2768   case Mips::BI__builtin_msa_bseti_b:
2769   case Mips::BI__builtin_msa_sat_s_b:
2770   case Mips::BI__builtin_msa_sat_u_b:
2771   case Mips::BI__builtin_msa_slli_b:
2772   case Mips::BI__builtin_msa_srai_b:
2773   case Mips::BI__builtin_msa_srari_b:
2774   case Mips::BI__builtin_msa_srli_b:
2775   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2776   case Mips::BI__builtin_msa_binsli_b:
2777   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2778   // These intrinsics take an unsigned 4 bit immediate.
2779   case Mips::BI__builtin_msa_bclri_h:
2780   case Mips::BI__builtin_msa_bnegi_h:
2781   case Mips::BI__builtin_msa_bseti_h:
2782   case Mips::BI__builtin_msa_sat_s_h:
2783   case Mips::BI__builtin_msa_sat_u_h:
2784   case Mips::BI__builtin_msa_slli_h:
2785   case Mips::BI__builtin_msa_srai_h:
2786   case Mips::BI__builtin_msa_srari_h:
2787   case Mips::BI__builtin_msa_srli_h:
2788   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2789   case Mips::BI__builtin_msa_binsli_h:
2790   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2791   // These intrinsics take an unsigned 5 bit immediate.
2792   // The first block of intrinsics actually have an unsigned 5 bit field,
2793   // not a df/n field.
2794   case Mips::BI__builtin_msa_clei_u_b:
2795   case Mips::BI__builtin_msa_clei_u_h:
2796   case Mips::BI__builtin_msa_clei_u_w:
2797   case Mips::BI__builtin_msa_clei_u_d:
2798   case Mips::BI__builtin_msa_clti_u_b:
2799   case Mips::BI__builtin_msa_clti_u_h:
2800   case Mips::BI__builtin_msa_clti_u_w:
2801   case Mips::BI__builtin_msa_clti_u_d:
2802   case Mips::BI__builtin_msa_maxi_u_b:
2803   case Mips::BI__builtin_msa_maxi_u_h:
2804   case Mips::BI__builtin_msa_maxi_u_w:
2805   case Mips::BI__builtin_msa_maxi_u_d:
2806   case Mips::BI__builtin_msa_mini_u_b:
2807   case Mips::BI__builtin_msa_mini_u_h:
2808   case Mips::BI__builtin_msa_mini_u_w:
2809   case Mips::BI__builtin_msa_mini_u_d:
2810   case Mips::BI__builtin_msa_addvi_b:
2811   case Mips::BI__builtin_msa_addvi_h:
2812   case Mips::BI__builtin_msa_addvi_w:
2813   case Mips::BI__builtin_msa_addvi_d:
2814   case Mips::BI__builtin_msa_bclri_w:
2815   case Mips::BI__builtin_msa_bnegi_w:
2816   case Mips::BI__builtin_msa_bseti_w:
2817   case Mips::BI__builtin_msa_sat_s_w:
2818   case Mips::BI__builtin_msa_sat_u_w:
2819   case Mips::BI__builtin_msa_slli_w:
2820   case Mips::BI__builtin_msa_srai_w:
2821   case Mips::BI__builtin_msa_srari_w:
2822   case Mips::BI__builtin_msa_srli_w:
2823   case Mips::BI__builtin_msa_srlri_w:
2824   case Mips::BI__builtin_msa_subvi_b:
2825   case Mips::BI__builtin_msa_subvi_h:
2826   case Mips::BI__builtin_msa_subvi_w:
2827   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2828   case Mips::BI__builtin_msa_binsli_w:
2829   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2830   // These intrinsics take an unsigned 6 bit immediate.
2831   case Mips::BI__builtin_msa_bclri_d:
2832   case Mips::BI__builtin_msa_bnegi_d:
2833   case Mips::BI__builtin_msa_bseti_d:
2834   case Mips::BI__builtin_msa_sat_s_d:
2835   case Mips::BI__builtin_msa_sat_u_d:
2836   case Mips::BI__builtin_msa_slli_d:
2837   case Mips::BI__builtin_msa_srai_d:
2838   case Mips::BI__builtin_msa_srari_d:
2839   case Mips::BI__builtin_msa_srli_d:
2840   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2841   case Mips::BI__builtin_msa_binsli_d:
2842   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2843   // These intrinsics take a signed 5 bit immediate.
2844   case Mips::BI__builtin_msa_ceqi_b:
2845   case Mips::BI__builtin_msa_ceqi_h:
2846   case Mips::BI__builtin_msa_ceqi_w:
2847   case Mips::BI__builtin_msa_ceqi_d:
2848   case Mips::BI__builtin_msa_clti_s_b:
2849   case Mips::BI__builtin_msa_clti_s_h:
2850   case Mips::BI__builtin_msa_clti_s_w:
2851   case Mips::BI__builtin_msa_clti_s_d:
2852   case Mips::BI__builtin_msa_clei_s_b:
2853   case Mips::BI__builtin_msa_clei_s_h:
2854   case Mips::BI__builtin_msa_clei_s_w:
2855   case Mips::BI__builtin_msa_clei_s_d:
2856   case Mips::BI__builtin_msa_maxi_s_b:
2857   case Mips::BI__builtin_msa_maxi_s_h:
2858   case Mips::BI__builtin_msa_maxi_s_w:
2859   case Mips::BI__builtin_msa_maxi_s_d:
2860   case Mips::BI__builtin_msa_mini_s_b:
2861   case Mips::BI__builtin_msa_mini_s_h:
2862   case Mips::BI__builtin_msa_mini_s_w:
2863   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2864   // These intrinsics take an unsigned 8 bit immediate.
2865   case Mips::BI__builtin_msa_andi_b:
2866   case Mips::BI__builtin_msa_nori_b:
2867   case Mips::BI__builtin_msa_ori_b:
2868   case Mips::BI__builtin_msa_shf_b:
2869   case Mips::BI__builtin_msa_shf_h:
2870   case Mips::BI__builtin_msa_shf_w:
2871   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2872   case Mips::BI__builtin_msa_bseli_b:
2873   case Mips::BI__builtin_msa_bmnzi_b:
2874   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2875   // df/n format
2876   // These intrinsics take an unsigned 4 bit immediate.
2877   case Mips::BI__builtin_msa_copy_s_b:
2878   case Mips::BI__builtin_msa_copy_u_b:
2879   case Mips::BI__builtin_msa_insve_b:
2880   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2881   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2882   // These intrinsics take an unsigned 3 bit immediate.
2883   case Mips::BI__builtin_msa_copy_s_h:
2884   case Mips::BI__builtin_msa_copy_u_h:
2885   case Mips::BI__builtin_msa_insve_h:
2886   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2887   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2888   // These intrinsics take an unsigned 2 bit immediate.
2889   case Mips::BI__builtin_msa_copy_s_w:
2890   case Mips::BI__builtin_msa_copy_u_w:
2891   case Mips::BI__builtin_msa_insve_w:
2892   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2893   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2894   // These intrinsics take an unsigned 1 bit immediate.
2895   case Mips::BI__builtin_msa_copy_s_d:
2896   case Mips::BI__builtin_msa_copy_u_d:
2897   case Mips::BI__builtin_msa_insve_d:
2898   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2899   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2900   // Memory offsets and immediate loads.
2901   // These intrinsics take a signed 10 bit immediate.
2902   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2903   case Mips::BI__builtin_msa_ldi_h:
2904   case Mips::BI__builtin_msa_ldi_w:
2905   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2906   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2907   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2908   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2909   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2910   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2911   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2912   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2913   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
2914   }
2915 
2916   if (!m)
2917     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2918 
2919   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2920          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2921 }
2922 
2923 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2924   unsigned i = 0, l = 0, u = 0;
2925   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2926                       BuiltinID == PPC::BI__builtin_divdeu ||
2927                       BuiltinID == PPC::BI__builtin_bpermd;
2928   bool IsTarget64Bit = Context.getTargetInfo()
2929                               .getTypeWidth(Context
2930                                             .getTargetInfo()
2931                                             .getIntPtrType()) == 64;
2932   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2933                        BuiltinID == PPC::BI__builtin_divweu ||
2934                        BuiltinID == PPC::BI__builtin_divde ||
2935                        BuiltinID == PPC::BI__builtin_divdeu;
2936 
2937   if (Is64BitBltin && !IsTarget64Bit)
2938       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2939              << TheCall->getSourceRange();
2940 
2941   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2942       (BuiltinID == PPC::BI__builtin_bpermd &&
2943        !Context.getTargetInfo().hasFeature("bpermd")))
2944     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2945            << TheCall->getSourceRange();
2946 
2947   switch (BuiltinID) {
2948   default: return false;
2949   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2950   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2951     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2952            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2953   case PPC::BI__builtin_tbegin:
2954   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2955   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2956   case PPC::BI__builtin_tabortwc:
2957   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2958   case PPC::BI__builtin_tabortwci:
2959   case PPC::BI__builtin_tabortdci:
2960     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2961            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
2962   case PPC::BI__builtin_vsx_xxpermdi:
2963   case PPC::BI__builtin_vsx_xxsldwi:
2964     return SemaBuiltinVSX(TheCall);
2965   }
2966   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2967 }
2968 
2969 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2970                                            CallExpr *TheCall) {
2971   if (BuiltinID == SystemZ::BI__builtin_tabort) {
2972     Expr *Arg = TheCall->getArg(0);
2973     llvm::APSInt AbortCode(32);
2974     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2975         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2976       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2977              << Arg->getSourceRange();
2978   }
2979 
2980   // For intrinsics which take an immediate value as part of the instruction,
2981   // range check them here.
2982   unsigned i = 0, l = 0, u = 0;
2983   switch (BuiltinID) {
2984   default: return false;
2985   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2986   case SystemZ::BI__builtin_s390_verimb:
2987   case SystemZ::BI__builtin_s390_verimh:
2988   case SystemZ::BI__builtin_s390_verimf:
2989   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2990   case SystemZ::BI__builtin_s390_vfaeb:
2991   case SystemZ::BI__builtin_s390_vfaeh:
2992   case SystemZ::BI__builtin_s390_vfaef:
2993   case SystemZ::BI__builtin_s390_vfaebs:
2994   case SystemZ::BI__builtin_s390_vfaehs:
2995   case SystemZ::BI__builtin_s390_vfaefs:
2996   case SystemZ::BI__builtin_s390_vfaezb:
2997   case SystemZ::BI__builtin_s390_vfaezh:
2998   case SystemZ::BI__builtin_s390_vfaezf:
2999   case SystemZ::BI__builtin_s390_vfaezbs:
3000   case SystemZ::BI__builtin_s390_vfaezhs:
3001   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3002   case SystemZ::BI__builtin_s390_vfisb:
3003   case SystemZ::BI__builtin_s390_vfidb:
3004     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3005            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3006   case SystemZ::BI__builtin_s390_vftcisb:
3007   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3008   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3009   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3010   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3011   case SystemZ::BI__builtin_s390_vstrcb:
3012   case SystemZ::BI__builtin_s390_vstrch:
3013   case SystemZ::BI__builtin_s390_vstrcf:
3014   case SystemZ::BI__builtin_s390_vstrczb:
3015   case SystemZ::BI__builtin_s390_vstrczh:
3016   case SystemZ::BI__builtin_s390_vstrczf:
3017   case SystemZ::BI__builtin_s390_vstrcbs:
3018   case SystemZ::BI__builtin_s390_vstrchs:
3019   case SystemZ::BI__builtin_s390_vstrcfs:
3020   case SystemZ::BI__builtin_s390_vstrczbs:
3021   case SystemZ::BI__builtin_s390_vstrczhs:
3022   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3023   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3024   case SystemZ::BI__builtin_s390_vfminsb:
3025   case SystemZ::BI__builtin_s390_vfmaxsb:
3026   case SystemZ::BI__builtin_s390_vfmindb:
3027   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3028   }
3029   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3030 }
3031 
3032 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3033 /// This checks that the target supports __builtin_cpu_supports and
3034 /// that the string argument is constant and valid.
3035 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3036   Expr *Arg = TheCall->getArg(0);
3037 
3038   // Check if the argument is a string literal.
3039   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3040     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3041            << Arg->getSourceRange();
3042 
3043   // Check the contents of the string.
3044   StringRef Feature =
3045       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3046   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3047     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
3048            << Arg->getSourceRange();
3049   return false;
3050 }
3051 
3052 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3053 /// This checks that the target supports __builtin_cpu_is and
3054 /// that the string argument is constant and valid.
3055 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3056   Expr *Arg = TheCall->getArg(0);
3057 
3058   // Check if the argument is a string literal.
3059   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3060     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3061            << Arg->getSourceRange();
3062 
3063   // Check the contents of the string.
3064   StringRef Feature =
3065       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3066   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3067     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
3068            << Arg->getSourceRange();
3069   return false;
3070 }
3071 
3072 // Check if the rounding mode is legal.
3073 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3074   // Indicates if this instruction has rounding control or just SAE.
3075   bool HasRC = false;
3076 
3077   unsigned ArgNum = 0;
3078   switch (BuiltinID) {
3079   default:
3080     return false;
3081   case X86::BI__builtin_ia32_vcvttsd2si32:
3082   case X86::BI__builtin_ia32_vcvttsd2si64:
3083   case X86::BI__builtin_ia32_vcvttsd2usi32:
3084   case X86::BI__builtin_ia32_vcvttsd2usi64:
3085   case X86::BI__builtin_ia32_vcvttss2si32:
3086   case X86::BI__builtin_ia32_vcvttss2si64:
3087   case X86::BI__builtin_ia32_vcvttss2usi32:
3088   case X86::BI__builtin_ia32_vcvttss2usi64:
3089     ArgNum = 1;
3090     break;
3091   case X86::BI__builtin_ia32_maxpd512:
3092   case X86::BI__builtin_ia32_maxps512:
3093   case X86::BI__builtin_ia32_minpd512:
3094   case X86::BI__builtin_ia32_minps512:
3095     ArgNum = 2;
3096     break;
3097   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3098   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3099   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3100   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3101   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3102   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3103   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3104   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3105   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3106   case X86::BI__builtin_ia32_exp2pd_mask:
3107   case X86::BI__builtin_ia32_exp2ps_mask:
3108   case X86::BI__builtin_ia32_getexppd512_mask:
3109   case X86::BI__builtin_ia32_getexpps512_mask:
3110   case X86::BI__builtin_ia32_rcp28pd_mask:
3111   case X86::BI__builtin_ia32_rcp28ps_mask:
3112   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3113   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3114   case X86::BI__builtin_ia32_vcomisd:
3115   case X86::BI__builtin_ia32_vcomiss:
3116   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3117     ArgNum = 3;
3118     break;
3119   case X86::BI__builtin_ia32_cmppd512_mask:
3120   case X86::BI__builtin_ia32_cmpps512_mask:
3121   case X86::BI__builtin_ia32_cmpsd_mask:
3122   case X86::BI__builtin_ia32_cmpss_mask:
3123   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3124   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3125   case X86::BI__builtin_ia32_getexpss128_round_mask:
3126   case X86::BI__builtin_ia32_maxsd_round_mask:
3127   case X86::BI__builtin_ia32_maxss_round_mask:
3128   case X86::BI__builtin_ia32_minsd_round_mask:
3129   case X86::BI__builtin_ia32_minss_round_mask:
3130   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3131   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3132   case X86::BI__builtin_ia32_reducepd512_mask:
3133   case X86::BI__builtin_ia32_reduceps512_mask:
3134   case X86::BI__builtin_ia32_rndscalepd_mask:
3135   case X86::BI__builtin_ia32_rndscaleps_mask:
3136   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3137   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3138     ArgNum = 4;
3139     break;
3140   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3141   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3142   case X86::BI__builtin_ia32_fixupimmps512_mask:
3143   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3144   case X86::BI__builtin_ia32_fixupimmsd_mask:
3145   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3146   case X86::BI__builtin_ia32_fixupimmss_mask:
3147   case X86::BI__builtin_ia32_fixupimmss_maskz:
3148   case X86::BI__builtin_ia32_rangepd512_mask:
3149   case X86::BI__builtin_ia32_rangeps512_mask:
3150   case X86::BI__builtin_ia32_rangesd128_round_mask:
3151   case X86::BI__builtin_ia32_rangess128_round_mask:
3152   case X86::BI__builtin_ia32_reducesd_mask:
3153   case X86::BI__builtin_ia32_reducess_mask:
3154   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3155   case X86::BI__builtin_ia32_rndscaless_round_mask:
3156     ArgNum = 5;
3157     break;
3158   case X86::BI__builtin_ia32_vcvtsd2si64:
3159   case X86::BI__builtin_ia32_vcvtsd2si32:
3160   case X86::BI__builtin_ia32_vcvtsd2usi32:
3161   case X86::BI__builtin_ia32_vcvtsd2usi64:
3162   case X86::BI__builtin_ia32_vcvtss2si32:
3163   case X86::BI__builtin_ia32_vcvtss2si64:
3164   case X86::BI__builtin_ia32_vcvtss2usi32:
3165   case X86::BI__builtin_ia32_vcvtss2usi64:
3166   case X86::BI__builtin_ia32_sqrtpd512:
3167   case X86::BI__builtin_ia32_sqrtps512:
3168     ArgNum = 1;
3169     HasRC = true;
3170     break;
3171   case X86::BI__builtin_ia32_addpd512:
3172   case X86::BI__builtin_ia32_addps512:
3173   case X86::BI__builtin_ia32_divpd512:
3174   case X86::BI__builtin_ia32_divps512:
3175   case X86::BI__builtin_ia32_mulpd512:
3176   case X86::BI__builtin_ia32_mulps512:
3177   case X86::BI__builtin_ia32_subpd512:
3178   case X86::BI__builtin_ia32_subps512:
3179   case X86::BI__builtin_ia32_cvtsi2sd64:
3180   case X86::BI__builtin_ia32_cvtsi2ss32:
3181   case X86::BI__builtin_ia32_cvtsi2ss64:
3182   case X86::BI__builtin_ia32_cvtusi2sd64:
3183   case X86::BI__builtin_ia32_cvtusi2ss32:
3184   case X86::BI__builtin_ia32_cvtusi2ss64:
3185     ArgNum = 2;
3186     HasRC = true;
3187     break;
3188   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3189   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3190   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3191   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3192   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3193   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3194   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3195   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3196   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3197   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3198   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3199     ArgNum = 3;
3200     HasRC = true;
3201     break;
3202   case X86::BI__builtin_ia32_addss_round_mask:
3203   case X86::BI__builtin_ia32_addsd_round_mask:
3204   case X86::BI__builtin_ia32_divss_round_mask:
3205   case X86::BI__builtin_ia32_divsd_round_mask:
3206   case X86::BI__builtin_ia32_mulss_round_mask:
3207   case X86::BI__builtin_ia32_mulsd_round_mask:
3208   case X86::BI__builtin_ia32_subss_round_mask:
3209   case X86::BI__builtin_ia32_subsd_round_mask:
3210   case X86::BI__builtin_ia32_scalefpd512_mask:
3211   case X86::BI__builtin_ia32_scalefps512_mask:
3212   case X86::BI__builtin_ia32_scalefsd_round_mask:
3213   case X86::BI__builtin_ia32_scalefss_round_mask:
3214   case X86::BI__builtin_ia32_getmantpd512_mask:
3215   case X86::BI__builtin_ia32_getmantps512_mask:
3216   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3217   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3218   case X86::BI__builtin_ia32_sqrtss_round_mask:
3219   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3220   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3221   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3222   case X86::BI__builtin_ia32_vfmaddss3_mask:
3223   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3224   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3225   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3226   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3227   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3228   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3229   case X86::BI__builtin_ia32_vfmaddps512_mask:
3230   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3231   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3232   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3233   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3234   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3235   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3236   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3237   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3238   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3239   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3240   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3241     ArgNum = 4;
3242     HasRC = true;
3243     break;
3244   case X86::BI__builtin_ia32_getmantsd_round_mask:
3245   case X86::BI__builtin_ia32_getmantss_round_mask:
3246     ArgNum = 5;
3247     HasRC = true;
3248     break;
3249   }
3250 
3251   llvm::APSInt Result;
3252 
3253   // We can't check the value of a dependent argument.
3254   Expr *Arg = TheCall->getArg(ArgNum);
3255   if (Arg->isTypeDependent() || Arg->isValueDependent())
3256     return false;
3257 
3258   // Check constant-ness first.
3259   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3260     return true;
3261 
3262   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3263   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3264   // combined with ROUND_NO_EXC.
3265   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3266       Result == 8/*ROUND_NO_EXC*/ ||
3267       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3268     return false;
3269 
3270   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
3271     << Arg->getSourceRange();
3272 }
3273 
3274 // Check if the gather/scatter scale is legal.
3275 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3276                                              CallExpr *TheCall) {
3277   unsigned ArgNum = 0;
3278   switch (BuiltinID) {
3279   default:
3280     return false;
3281   case X86::BI__builtin_ia32_gatherpfdpd:
3282   case X86::BI__builtin_ia32_gatherpfdps:
3283   case X86::BI__builtin_ia32_gatherpfqpd:
3284   case X86::BI__builtin_ia32_gatherpfqps:
3285   case X86::BI__builtin_ia32_scatterpfdpd:
3286   case X86::BI__builtin_ia32_scatterpfdps:
3287   case X86::BI__builtin_ia32_scatterpfqpd:
3288   case X86::BI__builtin_ia32_scatterpfqps:
3289     ArgNum = 3;
3290     break;
3291   case X86::BI__builtin_ia32_gatherd_pd:
3292   case X86::BI__builtin_ia32_gatherd_pd256:
3293   case X86::BI__builtin_ia32_gatherq_pd:
3294   case X86::BI__builtin_ia32_gatherq_pd256:
3295   case X86::BI__builtin_ia32_gatherd_ps:
3296   case X86::BI__builtin_ia32_gatherd_ps256:
3297   case X86::BI__builtin_ia32_gatherq_ps:
3298   case X86::BI__builtin_ia32_gatherq_ps256:
3299   case X86::BI__builtin_ia32_gatherd_q:
3300   case X86::BI__builtin_ia32_gatherd_q256:
3301   case X86::BI__builtin_ia32_gatherq_q:
3302   case X86::BI__builtin_ia32_gatherq_q256:
3303   case X86::BI__builtin_ia32_gatherd_d:
3304   case X86::BI__builtin_ia32_gatherd_d256:
3305   case X86::BI__builtin_ia32_gatherq_d:
3306   case X86::BI__builtin_ia32_gatherq_d256:
3307   case X86::BI__builtin_ia32_gather3div2df:
3308   case X86::BI__builtin_ia32_gather3div2di:
3309   case X86::BI__builtin_ia32_gather3div4df:
3310   case X86::BI__builtin_ia32_gather3div4di:
3311   case X86::BI__builtin_ia32_gather3div4sf:
3312   case X86::BI__builtin_ia32_gather3div4si:
3313   case X86::BI__builtin_ia32_gather3div8sf:
3314   case X86::BI__builtin_ia32_gather3div8si:
3315   case X86::BI__builtin_ia32_gather3siv2df:
3316   case X86::BI__builtin_ia32_gather3siv2di:
3317   case X86::BI__builtin_ia32_gather3siv4df:
3318   case X86::BI__builtin_ia32_gather3siv4di:
3319   case X86::BI__builtin_ia32_gather3siv4sf:
3320   case X86::BI__builtin_ia32_gather3siv4si:
3321   case X86::BI__builtin_ia32_gather3siv8sf:
3322   case X86::BI__builtin_ia32_gather3siv8si:
3323   case X86::BI__builtin_ia32_gathersiv8df:
3324   case X86::BI__builtin_ia32_gathersiv16sf:
3325   case X86::BI__builtin_ia32_gatherdiv8df:
3326   case X86::BI__builtin_ia32_gatherdiv16sf:
3327   case X86::BI__builtin_ia32_gathersiv8di:
3328   case X86::BI__builtin_ia32_gathersiv16si:
3329   case X86::BI__builtin_ia32_gatherdiv8di:
3330   case X86::BI__builtin_ia32_gatherdiv16si:
3331   case X86::BI__builtin_ia32_scatterdiv2df:
3332   case X86::BI__builtin_ia32_scatterdiv2di:
3333   case X86::BI__builtin_ia32_scatterdiv4df:
3334   case X86::BI__builtin_ia32_scatterdiv4di:
3335   case X86::BI__builtin_ia32_scatterdiv4sf:
3336   case X86::BI__builtin_ia32_scatterdiv4si:
3337   case X86::BI__builtin_ia32_scatterdiv8sf:
3338   case X86::BI__builtin_ia32_scatterdiv8si:
3339   case X86::BI__builtin_ia32_scattersiv2df:
3340   case X86::BI__builtin_ia32_scattersiv2di:
3341   case X86::BI__builtin_ia32_scattersiv4df:
3342   case X86::BI__builtin_ia32_scattersiv4di:
3343   case X86::BI__builtin_ia32_scattersiv4sf:
3344   case X86::BI__builtin_ia32_scattersiv4si:
3345   case X86::BI__builtin_ia32_scattersiv8sf:
3346   case X86::BI__builtin_ia32_scattersiv8si:
3347   case X86::BI__builtin_ia32_scattersiv8df:
3348   case X86::BI__builtin_ia32_scattersiv16sf:
3349   case X86::BI__builtin_ia32_scatterdiv8df:
3350   case X86::BI__builtin_ia32_scatterdiv16sf:
3351   case X86::BI__builtin_ia32_scattersiv8di:
3352   case X86::BI__builtin_ia32_scattersiv16si:
3353   case X86::BI__builtin_ia32_scatterdiv8di:
3354   case X86::BI__builtin_ia32_scatterdiv16si:
3355     ArgNum = 4;
3356     break;
3357   }
3358 
3359   llvm::APSInt Result;
3360 
3361   // We can't check the value of a dependent argument.
3362   Expr *Arg = TheCall->getArg(ArgNum);
3363   if (Arg->isTypeDependent() || Arg->isValueDependent())
3364     return false;
3365 
3366   // Check constant-ness first.
3367   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3368     return true;
3369 
3370   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3371     return false;
3372 
3373   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
3374     << Arg->getSourceRange();
3375 }
3376 
3377 static bool isX86_32Builtin(unsigned BuiltinID) {
3378   // These builtins only work on x86-32 targets.
3379   switch (BuiltinID) {
3380   case X86::BI__builtin_ia32_readeflags_u32:
3381   case X86::BI__builtin_ia32_writeeflags_u32:
3382     return true;
3383   }
3384 
3385   return false;
3386 }
3387 
3388 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3389   if (BuiltinID == X86::BI__builtin_cpu_supports)
3390     return SemaBuiltinCpuSupports(*this, TheCall);
3391 
3392   if (BuiltinID == X86::BI__builtin_cpu_is)
3393     return SemaBuiltinCpuIs(*this, TheCall);
3394 
3395   // Check for 32-bit only builtins on a 64-bit target.
3396   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3397   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3398     return Diag(TheCall->getCallee()->getLocStart(),
3399                 diag::err_32_bit_builtin_64_bit_tgt);
3400 
3401   // If the intrinsic has rounding or SAE make sure its valid.
3402   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3403     return true;
3404 
3405   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3406   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3407     return true;
3408 
3409   // For intrinsics which take an immediate value as part of the instruction,
3410   // range check them here.
3411   int i = 0, l = 0, u = 0;
3412   switch (BuiltinID) {
3413   default:
3414     return false;
3415   case X86::BI__builtin_ia32_vec_ext_v2si:
3416   case X86::BI__builtin_ia32_vec_ext_v2di:
3417   case X86::BI__builtin_ia32_vextractf128_pd256:
3418   case X86::BI__builtin_ia32_vextractf128_ps256:
3419   case X86::BI__builtin_ia32_vextractf128_si256:
3420   case X86::BI__builtin_ia32_extract128i256:
3421   case X86::BI__builtin_ia32_extractf64x4_mask:
3422   case X86::BI__builtin_ia32_extracti64x4_mask:
3423   case X86::BI__builtin_ia32_extractf32x8_mask:
3424   case X86::BI__builtin_ia32_extracti32x8_mask:
3425   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3426   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3427   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3428   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3429     i = 1; l = 0; u = 1;
3430     break;
3431   case X86::BI__builtin_ia32_vec_set_v2di:
3432   case X86::BI__builtin_ia32_vinsertf128_pd256:
3433   case X86::BI__builtin_ia32_vinsertf128_ps256:
3434   case X86::BI__builtin_ia32_vinsertf128_si256:
3435   case X86::BI__builtin_ia32_insert128i256:
3436   case X86::BI__builtin_ia32_insertf32x8:
3437   case X86::BI__builtin_ia32_inserti32x8:
3438   case X86::BI__builtin_ia32_insertf64x4:
3439   case X86::BI__builtin_ia32_inserti64x4:
3440   case X86::BI__builtin_ia32_insertf64x2_256:
3441   case X86::BI__builtin_ia32_inserti64x2_256:
3442   case X86::BI__builtin_ia32_insertf32x4_256:
3443   case X86::BI__builtin_ia32_inserti32x4_256:
3444     i = 2; l = 0; u = 1;
3445     break;
3446   case X86::BI__builtin_ia32_vpermilpd:
3447   case X86::BI__builtin_ia32_vec_ext_v4hi:
3448   case X86::BI__builtin_ia32_vec_ext_v4si:
3449   case X86::BI__builtin_ia32_vec_ext_v4sf:
3450   case X86::BI__builtin_ia32_vec_ext_v4di:
3451   case X86::BI__builtin_ia32_extractf32x4_mask:
3452   case X86::BI__builtin_ia32_extracti32x4_mask:
3453   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3454   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3455     i = 1; l = 0; u = 3;
3456     break;
3457   case X86::BI_mm_prefetch:
3458   case X86::BI__builtin_ia32_vec_ext_v8hi:
3459   case X86::BI__builtin_ia32_vec_ext_v8si:
3460     i = 1; l = 0; u = 7;
3461     break;
3462   case X86::BI__builtin_ia32_sha1rnds4:
3463   case X86::BI__builtin_ia32_blendpd:
3464   case X86::BI__builtin_ia32_shufpd:
3465   case X86::BI__builtin_ia32_vec_set_v4hi:
3466   case X86::BI__builtin_ia32_vec_set_v4si:
3467   case X86::BI__builtin_ia32_vec_set_v4di:
3468   case X86::BI__builtin_ia32_shuf_f32x4_256:
3469   case X86::BI__builtin_ia32_shuf_f64x2_256:
3470   case X86::BI__builtin_ia32_shuf_i32x4_256:
3471   case X86::BI__builtin_ia32_shuf_i64x2_256:
3472   case X86::BI__builtin_ia32_insertf64x2_512:
3473   case X86::BI__builtin_ia32_inserti64x2_512:
3474   case X86::BI__builtin_ia32_insertf32x4:
3475   case X86::BI__builtin_ia32_inserti32x4:
3476     i = 2; l = 0; u = 3;
3477     break;
3478   case X86::BI__builtin_ia32_vpermil2pd:
3479   case X86::BI__builtin_ia32_vpermil2pd256:
3480   case X86::BI__builtin_ia32_vpermil2ps:
3481   case X86::BI__builtin_ia32_vpermil2ps256:
3482     i = 3; l = 0; u = 3;
3483     break;
3484   case X86::BI__builtin_ia32_cmpb128_mask:
3485   case X86::BI__builtin_ia32_cmpw128_mask:
3486   case X86::BI__builtin_ia32_cmpd128_mask:
3487   case X86::BI__builtin_ia32_cmpq128_mask:
3488   case X86::BI__builtin_ia32_cmpb256_mask:
3489   case X86::BI__builtin_ia32_cmpw256_mask:
3490   case X86::BI__builtin_ia32_cmpd256_mask:
3491   case X86::BI__builtin_ia32_cmpq256_mask:
3492   case X86::BI__builtin_ia32_cmpb512_mask:
3493   case X86::BI__builtin_ia32_cmpw512_mask:
3494   case X86::BI__builtin_ia32_cmpd512_mask:
3495   case X86::BI__builtin_ia32_cmpq512_mask:
3496   case X86::BI__builtin_ia32_ucmpb128_mask:
3497   case X86::BI__builtin_ia32_ucmpw128_mask:
3498   case X86::BI__builtin_ia32_ucmpd128_mask:
3499   case X86::BI__builtin_ia32_ucmpq128_mask:
3500   case X86::BI__builtin_ia32_ucmpb256_mask:
3501   case X86::BI__builtin_ia32_ucmpw256_mask:
3502   case X86::BI__builtin_ia32_ucmpd256_mask:
3503   case X86::BI__builtin_ia32_ucmpq256_mask:
3504   case X86::BI__builtin_ia32_ucmpb512_mask:
3505   case X86::BI__builtin_ia32_ucmpw512_mask:
3506   case X86::BI__builtin_ia32_ucmpd512_mask:
3507   case X86::BI__builtin_ia32_ucmpq512_mask:
3508   case X86::BI__builtin_ia32_vpcomub:
3509   case X86::BI__builtin_ia32_vpcomuw:
3510   case X86::BI__builtin_ia32_vpcomud:
3511   case X86::BI__builtin_ia32_vpcomuq:
3512   case X86::BI__builtin_ia32_vpcomb:
3513   case X86::BI__builtin_ia32_vpcomw:
3514   case X86::BI__builtin_ia32_vpcomd:
3515   case X86::BI__builtin_ia32_vpcomq:
3516   case X86::BI__builtin_ia32_vec_set_v8hi:
3517   case X86::BI__builtin_ia32_vec_set_v8si:
3518     i = 2; l = 0; u = 7;
3519     break;
3520   case X86::BI__builtin_ia32_vpermilpd256:
3521   case X86::BI__builtin_ia32_roundps:
3522   case X86::BI__builtin_ia32_roundpd:
3523   case X86::BI__builtin_ia32_roundps256:
3524   case X86::BI__builtin_ia32_roundpd256:
3525   case X86::BI__builtin_ia32_getmantpd128_mask:
3526   case X86::BI__builtin_ia32_getmantpd256_mask:
3527   case X86::BI__builtin_ia32_getmantps128_mask:
3528   case X86::BI__builtin_ia32_getmantps256_mask:
3529   case X86::BI__builtin_ia32_getmantpd512_mask:
3530   case X86::BI__builtin_ia32_getmantps512_mask:
3531   case X86::BI__builtin_ia32_vec_ext_v16qi:
3532   case X86::BI__builtin_ia32_vec_ext_v16hi:
3533     i = 1; l = 0; u = 15;
3534     break;
3535   case X86::BI__builtin_ia32_pblendd128:
3536   case X86::BI__builtin_ia32_blendps:
3537   case X86::BI__builtin_ia32_blendpd256:
3538   case X86::BI__builtin_ia32_shufpd256:
3539   case X86::BI__builtin_ia32_roundss:
3540   case X86::BI__builtin_ia32_roundsd:
3541   case X86::BI__builtin_ia32_rangepd128_mask:
3542   case X86::BI__builtin_ia32_rangepd256_mask:
3543   case X86::BI__builtin_ia32_rangepd512_mask:
3544   case X86::BI__builtin_ia32_rangeps128_mask:
3545   case X86::BI__builtin_ia32_rangeps256_mask:
3546   case X86::BI__builtin_ia32_rangeps512_mask:
3547   case X86::BI__builtin_ia32_getmantsd_round_mask:
3548   case X86::BI__builtin_ia32_getmantss_round_mask:
3549   case X86::BI__builtin_ia32_vec_set_v16qi:
3550   case X86::BI__builtin_ia32_vec_set_v16hi:
3551     i = 2; l = 0; u = 15;
3552     break;
3553   case X86::BI__builtin_ia32_vec_ext_v32qi:
3554     i = 1; l = 0; u = 31;
3555     break;
3556   case X86::BI__builtin_ia32_cmpps:
3557   case X86::BI__builtin_ia32_cmpss:
3558   case X86::BI__builtin_ia32_cmppd:
3559   case X86::BI__builtin_ia32_cmpsd:
3560   case X86::BI__builtin_ia32_cmpps256:
3561   case X86::BI__builtin_ia32_cmppd256:
3562   case X86::BI__builtin_ia32_cmpps128_mask:
3563   case X86::BI__builtin_ia32_cmppd128_mask:
3564   case X86::BI__builtin_ia32_cmpps256_mask:
3565   case X86::BI__builtin_ia32_cmppd256_mask:
3566   case X86::BI__builtin_ia32_cmpps512_mask:
3567   case X86::BI__builtin_ia32_cmppd512_mask:
3568   case X86::BI__builtin_ia32_cmpsd_mask:
3569   case X86::BI__builtin_ia32_cmpss_mask:
3570   case X86::BI__builtin_ia32_vec_set_v32qi:
3571     i = 2; l = 0; u = 31;
3572     break;
3573   case X86::BI__builtin_ia32_permdf256:
3574   case X86::BI__builtin_ia32_permdi256:
3575   case X86::BI__builtin_ia32_permdf512:
3576   case X86::BI__builtin_ia32_permdi512:
3577   case X86::BI__builtin_ia32_vpermilps:
3578   case X86::BI__builtin_ia32_vpermilps256:
3579   case X86::BI__builtin_ia32_vpermilpd512:
3580   case X86::BI__builtin_ia32_vpermilps512:
3581   case X86::BI__builtin_ia32_pshufd:
3582   case X86::BI__builtin_ia32_pshufd256:
3583   case X86::BI__builtin_ia32_pshufd512:
3584   case X86::BI__builtin_ia32_pshufhw:
3585   case X86::BI__builtin_ia32_pshufhw256:
3586   case X86::BI__builtin_ia32_pshufhw512:
3587   case X86::BI__builtin_ia32_pshuflw:
3588   case X86::BI__builtin_ia32_pshuflw256:
3589   case X86::BI__builtin_ia32_pshuflw512:
3590   case X86::BI__builtin_ia32_vcvtps2ph:
3591   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3592   case X86::BI__builtin_ia32_vcvtps2ph256:
3593   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3594   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3595   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3596   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3597   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3598   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3599   case X86::BI__builtin_ia32_rndscaleps_mask:
3600   case X86::BI__builtin_ia32_rndscalepd_mask:
3601   case X86::BI__builtin_ia32_reducepd128_mask:
3602   case X86::BI__builtin_ia32_reducepd256_mask:
3603   case X86::BI__builtin_ia32_reducepd512_mask:
3604   case X86::BI__builtin_ia32_reduceps128_mask:
3605   case X86::BI__builtin_ia32_reduceps256_mask:
3606   case X86::BI__builtin_ia32_reduceps512_mask:
3607   case X86::BI__builtin_ia32_prold512:
3608   case X86::BI__builtin_ia32_prolq512:
3609   case X86::BI__builtin_ia32_prold128:
3610   case X86::BI__builtin_ia32_prold256:
3611   case X86::BI__builtin_ia32_prolq128:
3612   case X86::BI__builtin_ia32_prolq256:
3613   case X86::BI__builtin_ia32_prord512:
3614   case X86::BI__builtin_ia32_prorq512:
3615   case X86::BI__builtin_ia32_prord128:
3616   case X86::BI__builtin_ia32_prord256:
3617   case X86::BI__builtin_ia32_prorq128:
3618   case X86::BI__builtin_ia32_prorq256:
3619   case X86::BI__builtin_ia32_fpclasspd128_mask:
3620   case X86::BI__builtin_ia32_fpclasspd256_mask:
3621   case X86::BI__builtin_ia32_fpclassps128_mask:
3622   case X86::BI__builtin_ia32_fpclassps256_mask:
3623   case X86::BI__builtin_ia32_fpclassps512_mask:
3624   case X86::BI__builtin_ia32_fpclasspd512_mask:
3625   case X86::BI__builtin_ia32_fpclasssd_mask:
3626   case X86::BI__builtin_ia32_fpclassss_mask:
3627   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3628   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3629   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3630   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3631   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3632   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3633     i = 1; l = 0; u = 255;
3634     break;
3635   case X86::BI__builtin_ia32_vperm2f128_pd256:
3636   case X86::BI__builtin_ia32_vperm2f128_ps256:
3637   case X86::BI__builtin_ia32_vperm2f128_si256:
3638   case X86::BI__builtin_ia32_permti256:
3639   case X86::BI__builtin_ia32_pblendw128:
3640   case X86::BI__builtin_ia32_pblendw256:
3641   case X86::BI__builtin_ia32_blendps256:
3642   case X86::BI__builtin_ia32_pblendd256:
3643   case X86::BI__builtin_ia32_palignr128:
3644   case X86::BI__builtin_ia32_palignr256:
3645   case X86::BI__builtin_ia32_palignr512:
3646   case X86::BI__builtin_ia32_alignq512:
3647   case X86::BI__builtin_ia32_alignd512:
3648   case X86::BI__builtin_ia32_alignd128:
3649   case X86::BI__builtin_ia32_alignd256:
3650   case X86::BI__builtin_ia32_alignq128:
3651   case X86::BI__builtin_ia32_alignq256:
3652   case X86::BI__builtin_ia32_vcomisd:
3653   case X86::BI__builtin_ia32_vcomiss:
3654   case X86::BI__builtin_ia32_shuf_f32x4:
3655   case X86::BI__builtin_ia32_shuf_f64x2:
3656   case X86::BI__builtin_ia32_shuf_i32x4:
3657   case X86::BI__builtin_ia32_shuf_i64x2:
3658   case X86::BI__builtin_ia32_shufpd512:
3659   case X86::BI__builtin_ia32_shufps:
3660   case X86::BI__builtin_ia32_shufps256:
3661   case X86::BI__builtin_ia32_shufps512:
3662   case X86::BI__builtin_ia32_dbpsadbw128:
3663   case X86::BI__builtin_ia32_dbpsadbw256:
3664   case X86::BI__builtin_ia32_dbpsadbw512:
3665   case X86::BI__builtin_ia32_vpshldd128:
3666   case X86::BI__builtin_ia32_vpshldd256:
3667   case X86::BI__builtin_ia32_vpshldd512:
3668   case X86::BI__builtin_ia32_vpshldq128:
3669   case X86::BI__builtin_ia32_vpshldq256:
3670   case X86::BI__builtin_ia32_vpshldq512:
3671   case X86::BI__builtin_ia32_vpshldw128:
3672   case X86::BI__builtin_ia32_vpshldw256:
3673   case X86::BI__builtin_ia32_vpshldw512:
3674   case X86::BI__builtin_ia32_vpshrdd128:
3675   case X86::BI__builtin_ia32_vpshrdd256:
3676   case X86::BI__builtin_ia32_vpshrdd512:
3677   case X86::BI__builtin_ia32_vpshrdq128:
3678   case X86::BI__builtin_ia32_vpshrdq256:
3679   case X86::BI__builtin_ia32_vpshrdq512:
3680   case X86::BI__builtin_ia32_vpshrdw128:
3681   case X86::BI__builtin_ia32_vpshrdw256:
3682   case X86::BI__builtin_ia32_vpshrdw512:
3683     i = 2; l = 0; u = 255;
3684     break;
3685   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3686   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3687   case X86::BI__builtin_ia32_fixupimmps512_mask:
3688   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3689   case X86::BI__builtin_ia32_fixupimmsd_mask:
3690   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3691   case X86::BI__builtin_ia32_fixupimmss_mask:
3692   case X86::BI__builtin_ia32_fixupimmss_maskz:
3693   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3694   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3695   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3696   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3697   case X86::BI__builtin_ia32_fixupimmps128_mask:
3698   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3699   case X86::BI__builtin_ia32_fixupimmps256_mask:
3700   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3701   case X86::BI__builtin_ia32_pternlogd512_mask:
3702   case X86::BI__builtin_ia32_pternlogd512_maskz:
3703   case X86::BI__builtin_ia32_pternlogq512_mask:
3704   case X86::BI__builtin_ia32_pternlogq512_maskz:
3705   case X86::BI__builtin_ia32_pternlogd128_mask:
3706   case X86::BI__builtin_ia32_pternlogd128_maskz:
3707   case X86::BI__builtin_ia32_pternlogd256_mask:
3708   case X86::BI__builtin_ia32_pternlogd256_maskz:
3709   case X86::BI__builtin_ia32_pternlogq128_mask:
3710   case X86::BI__builtin_ia32_pternlogq128_maskz:
3711   case X86::BI__builtin_ia32_pternlogq256_mask:
3712   case X86::BI__builtin_ia32_pternlogq256_maskz:
3713     i = 3; l = 0; u = 255;
3714     break;
3715   case X86::BI__builtin_ia32_gatherpfdpd:
3716   case X86::BI__builtin_ia32_gatherpfdps:
3717   case X86::BI__builtin_ia32_gatherpfqpd:
3718   case X86::BI__builtin_ia32_gatherpfqps:
3719   case X86::BI__builtin_ia32_scatterpfdpd:
3720   case X86::BI__builtin_ia32_scatterpfdps:
3721   case X86::BI__builtin_ia32_scatterpfqpd:
3722   case X86::BI__builtin_ia32_scatterpfqps:
3723     i = 4; l = 2; u = 3;
3724     break;
3725   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3726   case X86::BI__builtin_ia32_rndscaless_round_mask:
3727     i = 4; l = 0; u = 255;
3728     break;
3729   }
3730 
3731   // Note that we don't force a hard error on the range check here, allowing
3732   // template-generated or macro-generated dead code to potentially have out-of-
3733   // range values. These need to code generate, but don't need to necessarily
3734   // make any sense. We use a warning that defaults to an error.
3735   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3736 }
3737 
3738 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3739 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3740 /// Returns true when the format fits the function and the FormatStringInfo has
3741 /// been populated.
3742 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3743                                FormatStringInfo *FSI) {
3744   FSI->HasVAListArg = Format->getFirstArg() == 0;
3745   FSI->FormatIdx = Format->getFormatIdx() - 1;
3746   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3747 
3748   // The way the format attribute works in GCC, the implicit this argument
3749   // of member functions is counted. However, it doesn't appear in our own
3750   // lists, so decrement format_idx in that case.
3751   if (IsCXXMember) {
3752     if(FSI->FormatIdx == 0)
3753       return false;
3754     --FSI->FormatIdx;
3755     if (FSI->FirstDataArg != 0)
3756       --FSI->FirstDataArg;
3757   }
3758   return true;
3759 }
3760 
3761 /// Checks if a the given expression evaluates to null.
3762 ///
3763 /// Returns true if the value evaluates to null.
3764 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3765   // If the expression has non-null type, it doesn't evaluate to null.
3766   if (auto nullability
3767         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3768     if (*nullability == NullabilityKind::NonNull)
3769       return false;
3770   }
3771 
3772   // As a special case, transparent unions initialized with zero are
3773   // considered null for the purposes of the nonnull attribute.
3774   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3775     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3776       if (const CompoundLiteralExpr *CLE =
3777           dyn_cast<CompoundLiteralExpr>(Expr))
3778         if (const InitListExpr *ILE =
3779             dyn_cast<InitListExpr>(CLE->getInitializer()))
3780           Expr = ILE->getInit(0);
3781   }
3782 
3783   bool Result;
3784   return (!Expr->isValueDependent() &&
3785           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3786           !Result);
3787 }
3788 
3789 static void CheckNonNullArgument(Sema &S,
3790                                  const Expr *ArgExpr,
3791                                  SourceLocation CallSiteLoc) {
3792   if (CheckNonNullExpr(S, ArgExpr))
3793     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3794            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
3795 }
3796 
3797 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3798   FormatStringInfo FSI;
3799   if ((GetFormatStringType(Format) == FST_NSString) &&
3800       getFormatStringInfo(Format, false, &FSI)) {
3801     Idx = FSI.FormatIdx;
3802     return true;
3803   }
3804   return false;
3805 }
3806 
3807 /// Diagnose use of %s directive in an NSString which is being passed
3808 /// as formatting string to formatting method.
3809 static void
3810 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3811                                         const NamedDecl *FDecl,
3812                                         Expr **Args,
3813                                         unsigned NumArgs) {
3814   unsigned Idx = 0;
3815   bool Format = false;
3816   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3817   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3818     Idx = 2;
3819     Format = true;
3820   }
3821   else
3822     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3823       if (S.GetFormatNSStringIdx(I, Idx)) {
3824         Format = true;
3825         break;
3826       }
3827     }
3828   if (!Format || NumArgs <= Idx)
3829     return;
3830   const Expr *FormatExpr = Args[Idx];
3831   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3832     FormatExpr = CSCE->getSubExpr();
3833   const StringLiteral *FormatString;
3834   if (const ObjCStringLiteral *OSL =
3835       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3836     FormatString = OSL->getString();
3837   else
3838     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3839   if (!FormatString)
3840     return;
3841   if (S.FormatStringHasSArg(FormatString)) {
3842     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3843       << "%s" << 1 << 1;
3844     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3845       << FDecl->getDeclName();
3846   }
3847 }
3848 
3849 /// Determine whether the given type has a non-null nullability annotation.
3850 static bool isNonNullType(ASTContext &ctx, QualType type) {
3851   if (auto nullability = type->getNullability(ctx))
3852     return *nullability == NullabilityKind::NonNull;
3853 
3854   return false;
3855 }
3856 
3857 static void CheckNonNullArguments(Sema &S,
3858                                   const NamedDecl *FDecl,
3859                                   const FunctionProtoType *Proto,
3860                                   ArrayRef<const Expr *> Args,
3861                                   SourceLocation CallSiteLoc) {
3862   assert((FDecl || Proto) && "Need a function declaration or prototype");
3863 
3864   // Check the attributes attached to the method/function itself.
3865   llvm::SmallBitVector NonNullArgs;
3866   if (FDecl) {
3867     // Handle the nonnull attribute on the function/method declaration itself.
3868     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3869       if (!NonNull->args_size()) {
3870         // Easy case: all pointer arguments are nonnull.
3871         for (const auto *Arg : Args)
3872           if (S.isValidPointerAttrType(Arg->getType()))
3873             CheckNonNullArgument(S, Arg, CallSiteLoc);
3874         return;
3875       }
3876 
3877       for (const ParamIdx &Idx : NonNull->args()) {
3878         unsigned IdxAST = Idx.getASTIndex();
3879         if (IdxAST >= Args.size())
3880           continue;
3881         if (NonNullArgs.empty())
3882           NonNullArgs.resize(Args.size());
3883         NonNullArgs.set(IdxAST);
3884       }
3885     }
3886   }
3887 
3888   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3889     // Handle the nonnull attribute on the parameters of the
3890     // function/method.
3891     ArrayRef<ParmVarDecl*> parms;
3892     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3893       parms = FD->parameters();
3894     else
3895       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3896 
3897     unsigned ParamIndex = 0;
3898     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3899          I != E; ++I, ++ParamIndex) {
3900       const ParmVarDecl *PVD = *I;
3901       if (PVD->hasAttr<NonNullAttr>() ||
3902           isNonNullType(S.Context, PVD->getType())) {
3903         if (NonNullArgs.empty())
3904           NonNullArgs.resize(Args.size());
3905 
3906         NonNullArgs.set(ParamIndex);
3907       }
3908     }
3909   } else {
3910     // If we have a non-function, non-method declaration but no
3911     // function prototype, try to dig out the function prototype.
3912     if (!Proto) {
3913       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3914         QualType type = VD->getType().getNonReferenceType();
3915         if (auto pointerType = type->getAs<PointerType>())
3916           type = pointerType->getPointeeType();
3917         else if (auto blockType = type->getAs<BlockPointerType>())
3918           type = blockType->getPointeeType();
3919         // FIXME: data member pointers?
3920 
3921         // Dig out the function prototype, if there is one.
3922         Proto = type->getAs<FunctionProtoType>();
3923       }
3924     }
3925 
3926     // Fill in non-null argument information from the nullability
3927     // information on the parameter types (if we have them).
3928     if (Proto) {
3929       unsigned Index = 0;
3930       for (auto paramType : Proto->getParamTypes()) {
3931         if (isNonNullType(S.Context, paramType)) {
3932           if (NonNullArgs.empty())
3933             NonNullArgs.resize(Args.size());
3934 
3935           NonNullArgs.set(Index);
3936         }
3937 
3938         ++Index;
3939       }
3940     }
3941   }
3942 
3943   // Check for non-null arguments.
3944   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3945        ArgIndex != ArgIndexEnd; ++ArgIndex) {
3946     if (NonNullArgs[ArgIndex])
3947       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
3948   }
3949 }
3950 
3951 /// Handles the checks for format strings, non-POD arguments to vararg
3952 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3953 /// attributes.
3954 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
3955                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
3956                      bool IsMemberFunction, SourceLocation Loc,
3957                      SourceRange Range, VariadicCallType CallType) {
3958   // FIXME: We should check as much as we can in the template definition.
3959   if (CurContext->isDependentContext())
3960     return;
3961 
3962   // Printf and scanf checking.
3963   llvm::SmallBitVector CheckedVarArgs;
3964   if (FDecl) {
3965     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3966       // Only create vector if there are format attributes.
3967       CheckedVarArgs.resize(Args.size());
3968 
3969       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3970                            CheckedVarArgs);
3971     }
3972   }
3973 
3974   // Refuse POD arguments that weren't caught by the format string
3975   // checks above.
3976   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3977   if (CallType != VariadicDoesNotApply &&
3978       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3979     unsigned NumParams = Proto ? Proto->getNumParams()
3980                        : FDecl && isa<FunctionDecl>(FDecl)
3981                            ? cast<FunctionDecl>(FDecl)->getNumParams()
3982                        : FDecl && isa<ObjCMethodDecl>(FDecl)
3983                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
3984                        : 0;
3985 
3986     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3987       // Args[ArgIdx] can be null in malformed code.
3988       if (const Expr *Arg = Args[ArgIdx]) {
3989         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3990           checkVariadicArgument(Arg, CallType);
3991       }
3992     }
3993   }
3994 
3995   if (FDecl || Proto) {
3996     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3997 
3998     // Type safety checking.
3999     if (FDecl) {
4000       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4001         CheckArgumentWithTypeTag(I, Args, Loc);
4002     }
4003   }
4004 
4005   if (FD)
4006     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4007 }
4008 
4009 /// CheckConstructorCall - Check a constructor call for correctness and safety
4010 /// properties not enforced by the C type system.
4011 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4012                                 ArrayRef<const Expr *> Args,
4013                                 const FunctionProtoType *Proto,
4014                                 SourceLocation Loc) {
4015   VariadicCallType CallType =
4016     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4017   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4018             Loc, SourceRange(), CallType);
4019 }
4020 
4021 /// CheckFunctionCall - Check a direct function call for various correctness
4022 /// and safety properties not strictly enforced by the C type system.
4023 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4024                              const FunctionProtoType *Proto) {
4025   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4026                               isa<CXXMethodDecl>(FDecl);
4027   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4028                           IsMemberOperatorCall;
4029   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4030                                                   TheCall->getCallee());
4031   Expr** Args = TheCall->getArgs();
4032   unsigned NumArgs = TheCall->getNumArgs();
4033 
4034   Expr *ImplicitThis = nullptr;
4035   if (IsMemberOperatorCall) {
4036     // If this is a call to a member operator, hide the first argument
4037     // from checkCall.
4038     // FIXME: Our choice of AST representation here is less than ideal.
4039     ImplicitThis = Args[0];
4040     ++Args;
4041     --NumArgs;
4042   } else if (IsMemberFunction)
4043     ImplicitThis =
4044         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4045 
4046   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4047             IsMemberFunction, TheCall->getRParenLoc(),
4048             TheCall->getCallee()->getSourceRange(), CallType);
4049 
4050   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4051   // None of the checks below are needed for functions that don't have
4052   // simple names (e.g., C++ conversion functions).
4053   if (!FnInfo)
4054     return false;
4055 
4056   CheckAbsoluteValueFunction(TheCall, FDecl);
4057   CheckMaxUnsignedZero(TheCall, FDecl);
4058 
4059   if (getLangOpts().ObjC1)
4060     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4061 
4062   unsigned CMId = FDecl->getMemoryFunctionKind();
4063   if (CMId == 0)
4064     return false;
4065 
4066   // Handle memory setting and copying functions.
4067   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4068     CheckStrlcpycatArguments(TheCall, FnInfo);
4069   else if (CMId == Builtin::BIstrncat)
4070     CheckStrncatArguments(TheCall, FnInfo);
4071   else
4072     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4073 
4074   return false;
4075 }
4076 
4077 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4078                                ArrayRef<const Expr *> Args) {
4079   VariadicCallType CallType =
4080       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4081 
4082   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4083             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4084             CallType);
4085 
4086   return false;
4087 }
4088 
4089 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4090                             const FunctionProtoType *Proto) {
4091   QualType Ty;
4092   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4093     Ty = V->getType().getNonReferenceType();
4094   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4095     Ty = F->getType().getNonReferenceType();
4096   else
4097     return false;
4098 
4099   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4100       !Ty->isFunctionProtoType())
4101     return false;
4102 
4103   VariadicCallType CallType;
4104   if (!Proto || !Proto->isVariadic()) {
4105     CallType = VariadicDoesNotApply;
4106   } else if (Ty->isBlockPointerType()) {
4107     CallType = VariadicBlock;
4108   } else { // Ty->isFunctionPointerType()
4109     CallType = VariadicFunction;
4110   }
4111 
4112   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4113             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4114             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4115             TheCall->getCallee()->getSourceRange(), CallType);
4116 
4117   return false;
4118 }
4119 
4120 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4121 /// such as function pointers returned from functions.
4122 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4123   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4124                                                   TheCall->getCallee());
4125   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4126             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4127             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4128             TheCall->getCallee()->getSourceRange(), CallType);
4129 
4130   return false;
4131 }
4132 
4133 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4134   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4135     return false;
4136 
4137   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4138   switch (Op) {
4139   case AtomicExpr::AO__c11_atomic_init:
4140   case AtomicExpr::AO__opencl_atomic_init:
4141     llvm_unreachable("There is no ordering argument for an init");
4142 
4143   case AtomicExpr::AO__c11_atomic_load:
4144   case AtomicExpr::AO__opencl_atomic_load:
4145   case AtomicExpr::AO__atomic_load_n:
4146   case AtomicExpr::AO__atomic_load:
4147     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4148            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4149 
4150   case AtomicExpr::AO__c11_atomic_store:
4151   case AtomicExpr::AO__opencl_atomic_store:
4152   case AtomicExpr::AO__atomic_store:
4153   case AtomicExpr::AO__atomic_store_n:
4154     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4155            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4156            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4157 
4158   default:
4159     return true;
4160   }
4161 }
4162 
4163 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4164                                          AtomicExpr::AtomicOp Op) {
4165   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4166   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4167 
4168   // All the non-OpenCL operations take one of the following forms.
4169   // The OpenCL operations take the __c11 forms with one extra argument for
4170   // synchronization scope.
4171   enum {
4172     // C    __c11_atomic_init(A *, C)
4173     Init,
4174 
4175     // C    __c11_atomic_load(A *, int)
4176     Load,
4177 
4178     // void __atomic_load(A *, CP, int)
4179     LoadCopy,
4180 
4181     // void __atomic_store(A *, CP, int)
4182     Copy,
4183 
4184     // C    __c11_atomic_add(A *, M, int)
4185     Arithmetic,
4186 
4187     // C    __atomic_exchange_n(A *, CP, int)
4188     Xchg,
4189 
4190     // void __atomic_exchange(A *, C *, CP, int)
4191     GNUXchg,
4192 
4193     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4194     C11CmpXchg,
4195 
4196     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4197     GNUCmpXchg
4198   } Form = Init;
4199 
4200   const unsigned NumForm = GNUCmpXchg + 1;
4201   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4202   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4203   // where:
4204   //   C is an appropriate type,
4205   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4206   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4207   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4208   //   the int parameters are for orderings.
4209 
4210   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4211       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4212       "need to update code for modified forms");
4213   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4214                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4215                         AtomicExpr::AO__atomic_load,
4216                 "need to update code for modified C11 atomics");
4217   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4218                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4219   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4220                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4221                IsOpenCL;
4222   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4223              Op == AtomicExpr::AO__atomic_store_n ||
4224              Op == AtomicExpr::AO__atomic_exchange_n ||
4225              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4226   bool IsAddSub = false;
4227   bool IsMinMax = false;
4228 
4229   switch (Op) {
4230   case AtomicExpr::AO__c11_atomic_init:
4231   case AtomicExpr::AO__opencl_atomic_init:
4232     Form = Init;
4233     break;
4234 
4235   case AtomicExpr::AO__c11_atomic_load:
4236   case AtomicExpr::AO__opencl_atomic_load:
4237   case AtomicExpr::AO__atomic_load_n:
4238     Form = Load;
4239     break;
4240 
4241   case AtomicExpr::AO__atomic_load:
4242     Form = LoadCopy;
4243     break;
4244 
4245   case AtomicExpr::AO__c11_atomic_store:
4246   case AtomicExpr::AO__opencl_atomic_store:
4247   case AtomicExpr::AO__atomic_store:
4248   case AtomicExpr::AO__atomic_store_n:
4249     Form = Copy;
4250     break;
4251 
4252   case AtomicExpr::AO__c11_atomic_fetch_add:
4253   case AtomicExpr::AO__c11_atomic_fetch_sub:
4254   case AtomicExpr::AO__opencl_atomic_fetch_add:
4255   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4256   case AtomicExpr::AO__opencl_atomic_fetch_min:
4257   case AtomicExpr::AO__opencl_atomic_fetch_max:
4258   case AtomicExpr::AO__atomic_fetch_add:
4259   case AtomicExpr::AO__atomic_fetch_sub:
4260   case AtomicExpr::AO__atomic_add_fetch:
4261   case AtomicExpr::AO__atomic_sub_fetch:
4262     IsAddSub = true;
4263     LLVM_FALLTHROUGH;
4264   case AtomicExpr::AO__c11_atomic_fetch_and:
4265   case AtomicExpr::AO__c11_atomic_fetch_or:
4266   case AtomicExpr::AO__c11_atomic_fetch_xor:
4267   case AtomicExpr::AO__opencl_atomic_fetch_and:
4268   case AtomicExpr::AO__opencl_atomic_fetch_or:
4269   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4270   case AtomicExpr::AO__atomic_fetch_and:
4271   case AtomicExpr::AO__atomic_fetch_or:
4272   case AtomicExpr::AO__atomic_fetch_xor:
4273   case AtomicExpr::AO__atomic_fetch_nand:
4274   case AtomicExpr::AO__atomic_and_fetch:
4275   case AtomicExpr::AO__atomic_or_fetch:
4276   case AtomicExpr::AO__atomic_xor_fetch:
4277   case AtomicExpr::AO__atomic_nand_fetch:
4278     Form = Arithmetic;
4279     break;
4280 
4281   case AtomicExpr::AO__atomic_fetch_min:
4282   case AtomicExpr::AO__atomic_fetch_max:
4283     IsMinMax = true;
4284     Form = Arithmetic;
4285     break;
4286 
4287   case AtomicExpr::AO__c11_atomic_exchange:
4288   case AtomicExpr::AO__opencl_atomic_exchange:
4289   case AtomicExpr::AO__atomic_exchange_n:
4290     Form = Xchg;
4291     break;
4292 
4293   case AtomicExpr::AO__atomic_exchange:
4294     Form = GNUXchg;
4295     break;
4296 
4297   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4298   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4299   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4300   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4301     Form = C11CmpXchg;
4302     break;
4303 
4304   case AtomicExpr::AO__atomic_compare_exchange:
4305   case AtomicExpr::AO__atomic_compare_exchange_n:
4306     Form = GNUCmpXchg;
4307     break;
4308   }
4309 
4310   unsigned AdjustedNumArgs = NumArgs[Form];
4311   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4312     ++AdjustedNumArgs;
4313   // Check we have the right number of arguments.
4314   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4315     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4316       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4317       << TheCall->getCallee()->getSourceRange();
4318     return ExprError();
4319   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4320     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
4321          diag::err_typecheck_call_too_many_args)
4322       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4323       << TheCall->getCallee()->getSourceRange();
4324     return ExprError();
4325   }
4326 
4327   // Inspect the first argument of the atomic operation.
4328   Expr *Ptr = TheCall->getArg(0);
4329   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4330   if (ConvertedPtr.isInvalid())
4331     return ExprError();
4332 
4333   Ptr = ConvertedPtr.get();
4334   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4335   if (!pointerType) {
4336     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
4337       << Ptr->getType() << Ptr->getSourceRange();
4338     return ExprError();
4339   }
4340 
4341   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4342   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4343   QualType ValType = AtomTy; // 'C'
4344   if (IsC11) {
4345     if (!AtomTy->isAtomicType()) {
4346       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
4347         << Ptr->getType() << Ptr->getSourceRange();
4348       return ExprError();
4349     }
4350     if (AtomTy.isConstQualified() ||
4351         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4352       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
4353           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4354           << Ptr->getSourceRange();
4355       return ExprError();
4356     }
4357     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4358   } else if (Form != Load && Form != LoadCopy) {
4359     if (ValType.isConstQualified()) {
4360       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
4361         << Ptr->getType() << Ptr->getSourceRange();
4362       return ExprError();
4363     }
4364   }
4365 
4366   // For an arithmetic operation, the implied arithmetic must be well-formed.
4367   if (Form == Arithmetic) {
4368     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4369     if (IsAddSub && !ValType->isIntegerType()
4370         && !ValType->isPointerType()) {
4371       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4372         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4373       return ExprError();
4374     }
4375     if (IsMinMax) {
4376       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4377       if (!BT || (BT->getKind() != BuiltinType::Int &&
4378                   BT->getKind() != BuiltinType::UInt)) {
4379         Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
4380         return ExprError();
4381       }
4382     }
4383     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4384       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
4385         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4386       return ExprError();
4387     }
4388     if (IsC11 && ValType->isPointerType() &&
4389         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
4390                             diag::err_incomplete_type)) {
4391       return ExprError();
4392     }
4393   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4394     // For __atomic_*_n operations, the value type must be a scalar integral or
4395     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4396     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4397       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4398     return ExprError();
4399   }
4400 
4401   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4402       !AtomTy->isScalarType()) {
4403     // For GNU atomics, require a trivially-copyable type. This is not part of
4404     // the GNU atomics specification, but we enforce it for sanity.
4405     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
4406       << Ptr->getType() << Ptr->getSourceRange();
4407     return ExprError();
4408   }
4409 
4410   switch (ValType.getObjCLifetime()) {
4411   case Qualifiers::OCL_None:
4412   case Qualifiers::OCL_ExplicitNone:
4413     // okay
4414     break;
4415 
4416   case Qualifiers::OCL_Weak:
4417   case Qualifiers::OCL_Strong:
4418   case Qualifiers::OCL_Autoreleasing:
4419     // FIXME: Can this happen? By this point, ValType should be known
4420     // to be trivially copyable.
4421     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
4422       << ValType << Ptr->getSourceRange();
4423     return ExprError();
4424   }
4425 
4426   // All atomic operations have an overload which takes a pointer to a volatile
4427   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4428   // into the result or the other operands. Similarly atomic_load takes a
4429   // pointer to a const 'A'.
4430   ValType.removeLocalVolatile();
4431   ValType.removeLocalConst();
4432   QualType ResultType = ValType;
4433   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4434       Form == Init)
4435     ResultType = Context.VoidTy;
4436   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4437     ResultType = Context.BoolTy;
4438 
4439   // The type of a parameter passed 'by value'. In the GNU atomics, such
4440   // arguments are actually passed as pointers.
4441   QualType ByValType = ValType; // 'CP'
4442   bool IsPassedByAddress = false;
4443   if (!IsC11 && !IsN) {
4444     ByValType = Ptr->getType();
4445     IsPassedByAddress = true;
4446   }
4447 
4448   // The first argument's non-CV pointer type is used to deduce the type of
4449   // subsequent arguments, except for:
4450   //  - weak flag (always converted to bool)
4451   //  - memory order (always converted to int)
4452   //  - scope  (always converted to int)
4453   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4454     QualType Ty;
4455     if (i < NumVals[Form] + 1) {
4456       switch (i) {
4457       case 0:
4458         // The first argument is always a pointer. It has a fixed type.
4459         // It is always dereferenced, a nullptr is undefined.
4460         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
4461         // Nothing else to do: we already know all we want about this pointer.
4462         continue;
4463       case 1:
4464         // The second argument is the non-atomic operand. For arithmetic, this
4465         // is always passed by value, and for a compare_exchange it is always
4466         // passed by address. For the rest, GNU uses by-address and C11 uses
4467         // by-value.
4468         assert(Form != Load);
4469         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4470           Ty = ValType;
4471         else if (Form == Copy || Form == Xchg) {
4472           if (IsPassedByAddress)
4473             // The value pointer is always dereferenced, a nullptr is undefined.
4474             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
4475           Ty = ByValType;
4476         } else if (Form == Arithmetic)
4477           Ty = Context.getPointerDiffType();
4478         else {
4479           Expr *ValArg = TheCall->getArg(i);
4480           // The value pointer is always dereferenced, a nullptr is undefined.
4481           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
4482           LangAS AS = LangAS::Default;
4483           // Keep address space of non-atomic pointer type.
4484           if (const PointerType *PtrTy =
4485                   ValArg->getType()->getAs<PointerType>()) {
4486             AS = PtrTy->getPointeeType().getAddressSpace();
4487           }
4488           Ty = Context.getPointerType(
4489               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4490         }
4491         break;
4492       case 2:
4493         // The third argument to compare_exchange / GNU exchange is the desired
4494         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4495         if (IsPassedByAddress)
4496           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
4497         Ty = ByValType;
4498         break;
4499       case 3:
4500         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4501         Ty = Context.BoolTy;
4502         break;
4503       }
4504     } else {
4505       // The order(s) and scope are always converted to int.
4506       Ty = Context.IntTy;
4507     }
4508 
4509     InitializedEntity Entity =
4510         InitializedEntity::InitializeParameter(Context, Ty, false);
4511     ExprResult Arg = TheCall->getArg(i);
4512     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4513     if (Arg.isInvalid())
4514       return true;
4515     TheCall->setArg(i, Arg.get());
4516   }
4517 
4518   // Permute the arguments into a 'consistent' order.
4519   SmallVector<Expr*, 5> SubExprs;
4520   SubExprs.push_back(Ptr);
4521   switch (Form) {
4522   case Init:
4523     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4524     SubExprs.push_back(TheCall->getArg(1)); // Val1
4525     break;
4526   case Load:
4527     SubExprs.push_back(TheCall->getArg(1)); // Order
4528     break;
4529   case LoadCopy:
4530   case Copy:
4531   case Arithmetic:
4532   case Xchg:
4533     SubExprs.push_back(TheCall->getArg(2)); // Order
4534     SubExprs.push_back(TheCall->getArg(1)); // Val1
4535     break;
4536   case GNUXchg:
4537     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4538     SubExprs.push_back(TheCall->getArg(3)); // Order
4539     SubExprs.push_back(TheCall->getArg(1)); // Val1
4540     SubExprs.push_back(TheCall->getArg(2)); // Val2
4541     break;
4542   case C11CmpXchg:
4543     SubExprs.push_back(TheCall->getArg(3)); // Order
4544     SubExprs.push_back(TheCall->getArg(1)); // Val1
4545     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4546     SubExprs.push_back(TheCall->getArg(2)); // Val2
4547     break;
4548   case GNUCmpXchg:
4549     SubExprs.push_back(TheCall->getArg(4)); // Order
4550     SubExprs.push_back(TheCall->getArg(1)); // Val1
4551     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4552     SubExprs.push_back(TheCall->getArg(2)); // Val2
4553     SubExprs.push_back(TheCall->getArg(3)); // Weak
4554     break;
4555   }
4556 
4557   if (SubExprs.size() >= 2 && Form != Init) {
4558     llvm::APSInt Result(32);
4559     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4560         !isValidOrderingForOp(Result.getSExtValue(), Op))
4561       Diag(SubExprs[1]->getLocStart(),
4562            diag::warn_atomic_op_has_invalid_memory_order)
4563           << SubExprs[1]->getSourceRange();
4564   }
4565 
4566   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4567     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4568     llvm::APSInt Result(32);
4569     if (Scope->isIntegerConstantExpr(Result, Context) &&
4570         !ScopeModel->isValid(Result.getZExtValue())) {
4571       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
4572           << Scope->getSourceRange();
4573     }
4574     SubExprs.push_back(Scope);
4575   }
4576 
4577   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
4578                                             SubExprs, ResultType, Op,
4579                                             TheCall->getRParenLoc());
4580 
4581   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4582        Op == AtomicExpr::AO__c11_atomic_store ||
4583        Op == AtomicExpr::AO__opencl_atomic_load ||
4584        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4585       Context.AtomicUsesUnsupportedLibcall(AE))
4586     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
4587         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4588             Op == AtomicExpr::AO__opencl_atomic_load)
4589                 ? 0 : 1);
4590 
4591   return AE;
4592 }
4593 
4594 /// checkBuiltinArgument - Given a call to a builtin function, perform
4595 /// normal type-checking on the given argument, updating the call in
4596 /// place.  This is useful when a builtin function requires custom
4597 /// type-checking for some of its arguments but not necessarily all of
4598 /// them.
4599 ///
4600 /// Returns true on error.
4601 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4602   FunctionDecl *Fn = E->getDirectCallee();
4603   assert(Fn && "builtin call without direct callee!");
4604 
4605   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4606   InitializedEntity Entity =
4607     InitializedEntity::InitializeParameter(S.Context, Param);
4608 
4609   ExprResult Arg = E->getArg(0);
4610   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4611   if (Arg.isInvalid())
4612     return true;
4613 
4614   E->setArg(ArgIndex, Arg.get());
4615   return false;
4616 }
4617 
4618 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
4619 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
4620 /// type of its first argument.  The main ActOnCallExpr routines have already
4621 /// promoted the types of arguments because all of these calls are prototyped as
4622 /// void(...).
4623 ///
4624 /// This function goes through and does final semantic checking for these
4625 /// builtins,
4626 ExprResult
4627 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4628   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4629   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4630   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4631 
4632   // Ensure that we have at least one argument to do type inference from.
4633   if (TheCall->getNumArgs() < 1) {
4634     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4635       << 0 << 1 << TheCall->getNumArgs()
4636       << TheCall->getCallee()->getSourceRange();
4637     return ExprError();
4638   }
4639 
4640   // Inspect the first argument of the atomic builtin.  This should always be
4641   // a pointer type, whose element is an integral scalar or pointer type.
4642   // Because it is a pointer type, we don't have to worry about any implicit
4643   // casts here.
4644   // FIXME: We don't allow floating point scalars as input.
4645   Expr *FirstArg = TheCall->getArg(0);
4646   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4647   if (FirstArgResult.isInvalid())
4648     return ExprError();
4649   FirstArg = FirstArgResult.get();
4650   TheCall->setArg(0, FirstArg);
4651 
4652   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4653   if (!pointerType) {
4654     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
4655       << FirstArg->getType() << FirstArg->getSourceRange();
4656     return ExprError();
4657   }
4658 
4659   QualType ValType = pointerType->getPointeeType();
4660   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4661       !ValType->isBlockPointerType()) {
4662     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
4663       << FirstArg->getType() << FirstArg->getSourceRange();
4664     return ExprError();
4665   }
4666 
4667   if (ValType.isConstQualified()) {
4668     Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
4669         << FirstArg->getType() << FirstArg->getSourceRange();
4670     return ExprError();
4671   }
4672 
4673   switch (ValType.getObjCLifetime()) {
4674   case Qualifiers::OCL_None:
4675   case Qualifiers::OCL_ExplicitNone:
4676     // okay
4677     break;
4678 
4679   case Qualifiers::OCL_Weak:
4680   case Qualifiers::OCL_Strong:
4681   case Qualifiers::OCL_Autoreleasing:
4682     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
4683       << ValType << FirstArg->getSourceRange();
4684     return ExprError();
4685   }
4686 
4687   // Strip any qualifiers off ValType.
4688   ValType = ValType.getUnqualifiedType();
4689 
4690   // The majority of builtins return a value, but a few have special return
4691   // types, so allow them to override appropriately below.
4692   QualType ResultType = ValType;
4693 
4694   // We need to figure out which concrete builtin this maps onto.  For example,
4695   // __sync_fetch_and_add with a 2 byte object turns into
4696   // __sync_fetch_and_add_2.
4697 #define BUILTIN_ROW(x) \
4698   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4699     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4700 
4701   static const unsigned BuiltinIndices[][5] = {
4702     BUILTIN_ROW(__sync_fetch_and_add),
4703     BUILTIN_ROW(__sync_fetch_and_sub),
4704     BUILTIN_ROW(__sync_fetch_and_or),
4705     BUILTIN_ROW(__sync_fetch_and_and),
4706     BUILTIN_ROW(__sync_fetch_and_xor),
4707     BUILTIN_ROW(__sync_fetch_and_nand),
4708 
4709     BUILTIN_ROW(__sync_add_and_fetch),
4710     BUILTIN_ROW(__sync_sub_and_fetch),
4711     BUILTIN_ROW(__sync_and_and_fetch),
4712     BUILTIN_ROW(__sync_or_and_fetch),
4713     BUILTIN_ROW(__sync_xor_and_fetch),
4714     BUILTIN_ROW(__sync_nand_and_fetch),
4715 
4716     BUILTIN_ROW(__sync_val_compare_and_swap),
4717     BUILTIN_ROW(__sync_bool_compare_and_swap),
4718     BUILTIN_ROW(__sync_lock_test_and_set),
4719     BUILTIN_ROW(__sync_lock_release),
4720     BUILTIN_ROW(__sync_swap)
4721   };
4722 #undef BUILTIN_ROW
4723 
4724   // Determine the index of the size.
4725   unsigned SizeIndex;
4726   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4727   case 1: SizeIndex = 0; break;
4728   case 2: SizeIndex = 1; break;
4729   case 4: SizeIndex = 2; break;
4730   case 8: SizeIndex = 3; break;
4731   case 16: SizeIndex = 4; break;
4732   default:
4733     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
4734       << FirstArg->getType() << FirstArg->getSourceRange();
4735     return ExprError();
4736   }
4737 
4738   // Each of these builtins has one pointer argument, followed by some number of
4739   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4740   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4741   // as the number of fixed args.
4742   unsigned BuiltinID = FDecl->getBuiltinID();
4743   unsigned BuiltinIndex, NumFixed = 1;
4744   bool WarnAboutSemanticsChange = false;
4745   switch (BuiltinID) {
4746   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4747   case Builtin::BI__sync_fetch_and_add:
4748   case Builtin::BI__sync_fetch_and_add_1:
4749   case Builtin::BI__sync_fetch_and_add_2:
4750   case Builtin::BI__sync_fetch_and_add_4:
4751   case Builtin::BI__sync_fetch_and_add_8:
4752   case Builtin::BI__sync_fetch_and_add_16:
4753     BuiltinIndex = 0;
4754     break;
4755 
4756   case Builtin::BI__sync_fetch_and_sub:
4757   case Builtin::BI__sync_fetch_and_sub_1:
4758   case Builtin::BI__sync_fetch_and_sub_2:
4759   case Builtin::BI__sync_fetch_and_sub_4:
4760   case Builtin::BI__sync_fetch_and_sub_8:
4761   case Builtin::BI__sync_fetch_and_sub_16:
4762     BuiltinIndex = 1;
4763     break;
4764 
4765   case Builtin::BI__sync_fetch_and_or:
4766   case Builtin::BI__sync_fetch_and_or_1:
4767   case Builtin::BI__sync_fetch_and_or_2:
4768   case Builtin::BI__sync_fetch_and_or_4:
4769   case Builtin::BI__sync_fetch_and_or_8:
4770   case Builtin::BI__sync_fetch_and_or_16:
4771     BuiltinIndex = 2;
4772     break;
4773 
4774   case Builtin::BI__sync_fetch_and_and:
4775   case Builtin::BI__sync_fetch_and_and_1:
4776   case Builtin::BI__sync_fetch_and_and_2:
4777   case Builtin::BI__sync_fetch_and_and_4:
4778   case Builtin::BI__sync_fetch_and_and_8:
4779   case Builtin::BI__sync_fetch_and_and_16:
4780     BuiltinIndex = 3;
4781     break;
4782 
4783   case Builtin::BI__sync_fetch_and_xor:
4784   case Builtin::BI__sync_fetch_and_xor_1:
4785   case Builtin::BI__sync_fetch_and_xor_2:
4786   case Builtin::BI__sync_fetch_and_xor_4:
4787   case Builtin::BI__sync_fetch_and_xor_8:
4788   case Builtin::BI__sync_fetch_and_xor_16:
4789     BuiltinIndex = 4;
4790     break;
4791 
4792   case Builtin::BI__sync_fetch_and_nand:
4793   case Builtin::BI__sync_fetch_and_nand_1:
4794   case Builtin::BI__sync_fetch_and_nand_2:
4795   case Builtin::BI__sync_fetch_and_nand_4:
4796   case Builtin::BI__sync_fetch_and_nand_8:
4797   case Builtin::BI__sync_fetch_and_nand_16:
4798     BuiltinIndex = 5;
4799     WarnAboutSemanticsChange = true;
4800     break;
4801 
4802   case Builtin::BI__sync_add_and_fetch:
4803   case Builtin::BI__sync_add_and_fetch_1:
4804   case Builtin::BI__sync_add_and_fetch_2:
4805   case Builtin::BI__sync_add_and_fetch_4:
4806   case Builtin::BI__sync_add_and_fetch_8:
4807   case Builtin::BI__sync_add_and_fetch_16:
4808     BuiltinIndex = 6;
4809     break;
4810 
4811   case Builtin::BI__sync_sub_and_fetch:
4812   case Builtin::BI__sync_sub_and_fetch_1:
4813   case Builtin::BI__sync_sub_and_fetch_2:
4814   case Builtin::BI__sync_sub_and_fetch_4:
4815   case Builtin::BI__sync_sub_and_fetch_8:
4816   case Builtin::BI__sync_sub_and_fetch_16:
4817     BuiltinIndex = 7;
4818     break;
4819 
4820   case Builtin::BI__sync_and_and_fetch:
4821   case Builtin::BI__sync_and_and_fetch_1:
4822   case Builtin::BI__sync_and_and_fetch_2:
4823   case Builtin::BI__sync_and_and_fetch_4:
4824   case Builtin::BI__sync_and_and_fetch_8:
4825   case Builtin::BI__sync_and_and_fetch_16:
4826     BuiltinIndex = 8;
4827     break;
4828 
4829   case Builtin::BI__sync_or_and_fetch:
4830   case Builtin::BI__sync_or_and_fetch_1:
4831   case Builtin::BI__sync_or_and_fetch_2:
4832   case Builtin::BI__sync_or_and_fetch_4:
4833   case Builtin::BI__sync_or_and_fetch_8:
4834   case Builtin::BI__sync_or_and_fetch_16:
4835     BuiltinIndex = 9;
4836     break;
4837 
4838   case Builtin::BI__sync_xor_and_fetch:
4839   case Builtin::BI__sync_xor_and_fetch_1:
4840   case Builtin::BI__sync_xor_and_fetch_2:
4841   case Builtin::BI__sync_xor_and_fetch_4:
4842   case Builtin::BI__sync_xor_and_fetch_8:
4843   case Builtin::BI__sync_xor_and_fetch_16:
4844     BuiltinIndex = 10;
4845     break;
4846 
4847   case Builtin::BI__sync_nand_and_fetch:
4848   case Builtin::BI__sync_nand_and_fetch_1:
4849   case Builtin::BI__sync_nand_and_fetch_2:
4850   case Builtin::BI__sync_nand_and_fetch_4:
4851   case Builtin::BI__sync_nand_and_fetch_8:
4852   case Builtin::BI__sync_nand_and_fetch_16:
4853     BuiltinIndex = 11;
4854     WarnAboutSemanticsChange = true;
4855     break;
4856 
4857   case Builtin::BI__sync_val_compare_and_swap:
4858   case Builtin::BI__sync_val_compare_and_swap_1:
4859   case Builtin::BI__sync_val_compare_and_swap_2:
4860   case Builtin::BI__sync_val_compare_and_swap_4:
4861   case Builtin::BI__sync_val_compare_and_swap_8:
4862   case Builtin::BI__sync_val_compare_and_swap_16:
4863     BuiltinIndex = 12;
4864     NumFixed = 2;
4865     break;
4866 
4867   case Builtin::BI__sync_bool_compare_and_swap:
4868   case Builtin::BI__sync_bool_compare_and_swap_1:
4869   case Builtin::BI__sync_bool_compare_and_swap_2:
4870   case Builtin::BI__sync_bool_compare_and_swap_4:
4871   case Builtin::BI__sync_bool_compare_and_swap_8:
4872   case Builtin::BI__sync_bool_compare_and_swap_16:
4873     BuiltinIndex = 13;
4874     NumFixed = 2;
4875     ResultType = Context.BoolTy;
4876     break;
4877 
4878   case Builtin::BI__sync_lock_test_and_set:
4879   case Builtin::BI__sync_lock_test_and_set_1:
4880   case Builtin::BI__sync_lock_test_and_set_2:
4881   case Builtin::BI__sync_lock_test_and_set_4:
4882   case Builtin::BI__sync_lock_test_and_set_8:
4883   case Builtin::BI__sync_lock_test_and_set_16:
4884     BuiltinIndex = 14;
4885     break;
4886 
4887   case Builtin::BI__sync_lock_release:
4888   case Builtin::BI__sync_lock_release_1:
4889   case Builtin::BI__sync_lock_release_2:
4890   case Builtin::BI__sync_lock_release_4:
4891   case Builtin::BI__sync_lock_release_8:
4892   case Builtin::BI__sync_lock_release_16:
4893     BuiltinIndex = 15;
4894     NumFixed = 0;
4895     ResultType = Context.VoidTy;
4896     break;
4897 
4898   case Builtin::BI__sync_swap:
4899   case Builtin::BI__sync_swap_1:
4900   case Builtin::BI__sync_swap_2:
4901   case Builtin::BI__sync_swap_4:
4902   case Builtin::BI__sync_swap_8:
4903   case Builtin::BI__sync_swap_16:
4904     BuiltinIndex = 16;
4905     break;
4906   }
4907 
4908   // Now that we know how many fixed arguments we expect, first check that we
4909   // have at least that many.
4910   if (TheCall->getNumArgs() < 1+NumFixed) {
4911     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4912       << 0 << 1+NumFixed << TheCall->getNumArgs()
4913       << TheCall->getCallee()->getSourceRange();
4914     return ExprError();
4915   }
4916 
4917   if (WarnAboutSemanticsChange) {
4918     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4919       << TheCall->getCallee()->getSourceRange();
4920   }
4921 
4922   // Get the decl for the concrete builtin from this, we can tell what the
4923   // concrete integer type we should convert to is.
4924   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4925   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4926   FunctionDecl *NewBuiltinDecl;
4927   if (NewBuiltinID == BuiltinID)
4928     NewBuiltinDecl = FDecl;
4929   else {
4930     // Perform builtin lookup to avoid redeclaring it.
4931     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4932     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4933     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4934     assert(Res.getFoundDecl());
4935     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4936     if (!NewBuiltinDecl)
4937       return ExprError();
4938   }
4939 
4940   // The first argument --- the pointer --- has a fixed type; we
4941   // deduce the types of the rest of the arguments accordingly.  Walk
4942   // the remaining arguments, converting them to the deduced value type.
4943   for (unsigned i = 0; i != NumFixed; ++i) {
4944     ExprResult Arg = TheCall->getArg(i+1);
4945 
4946     // GCC does an implicit conversion to the pointer or integer ValType.  This
4947     // can fail in some cases (1i -> int**), check for this error case now.
4948     // Initialize the argument.
4949     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4950                                                    ValType, /*consume*/ false);
4951     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4952     if (Arg.isInvalid())
4953       return ExprError();
4954 
4955     // Okay, we have something that *can* be converted to the right type.  Check
4956     // to see if there is a potentially weird extension going on here.  This can
4957     // happen when you do an atomic operation on something like an char* and
4958     // pass in 42.  The 42 gets converted to char.  This is even more strange
4959     // for things like 45.123 -> char, etc.
4960     // FIXME: Do this check.
4961     TheCall->setArg(i+1, Arg.get());
4962   }
4963 
4964   ASTContext& Context = this->getASTContext();
4965 
4966   // Create a new DeclRefExpr to refer to the new decl.
4967   DeclRefExpr* NewDRE = DeclRefExpr::Create(
4968       Context,
4969       DRE->getQualifierLoc(),
4970       SourceLocation(),
4971       NewBuiltinDecl,
4972       /*enclosing*/ false,
4973       DRE->getLocation(),
4974       Context.BuiltinFnTy,
4975       DRE->getValueKind());
4976 
4977   // Set the callee in the CallExpr.
4978   // FIXME: This loses syntactic information.
4979   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4980   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4981                                               CK_BuiltinFnToFnPtr);
4982   TheCall->setCallee(PromotedCall.get());
4983 
4984   // Change the result type of the call to match the original value type. This
4985   // is arbitrary, but the codegen for these builtins ins design to handle it
4986   // gracefully.
4987   TheCall->setType(ResultType);
4988 
4989   return TheCallResult;
4990 }
4991 
4992 /// SemaBuiltinNontemporalOverloaded - We have a call to
4993 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4994 /// overloaded function based on the pointer type of its last argument.
4995 ///
4996 /// This function goes through and does final semantic checking for these
4997 /// builtins.
4998 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4999   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5000   DeclRefExpr *DRE =
5001       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5002   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5003   unsigned BuiltinID = FDecl->getBuiltinID();
5004   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5005           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5006          "Unexpected nontemporal load/store builtin!");
5007   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5008   unsigned numArgs = isStore ? 2 : 1;
5009 
5010   // Ensure that we have the proper number of arguments.
5011   if (checkArgCount(*this, TheCall, numArgs))
5012     return ExprError();
5013 
5014   // Inspect the last argument of the nontemporal builtin.  This should always
5015   // be a pointer type, from which we imply the type of the memory access.
5016   // Because it is a pointer type, we don't have to worry about any implicit
5017   // casts here.
5018   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5019   ExprResult PointerArgResult =
5020       DefaultFunctionArrayLvalueConversion(PointerArg);
5021 
5022   if (PointerArgResult.isInvalid())
5023     return ExprError();
5024   PointerArg = PointerArgResult.get();
5025   TheCall->setArg(numArgs - 1, PointerArg);
5026 
5027   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5028   if (!pointerType) {
5029     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
5030         << PointerArg->getType() << PointerArg->getSourceRange();
5031     return ExprError();
5032   }
5033 
5034   QualType ValType = pointerType->getPointeeType();
5035 
5036   // Strip any qualifiers off ValType.
5037   ValType = ValType.getUnqualifiedType();
5038   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5039       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5040       !ValType->isVectorType()) {
5041     Diag(DRE->getLocStart(),
5042          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5043         << PointerArg->getType() << PointerArg->getSourceRange();
5044     return ExprError();
5045   }
5046 
5047   if (!isStore) {
5048     TheCall->setType(ValType);
5049     return TheCallResult;
5050   }
5051 
5052   ExprResult ValArg = TheCall->getArg(0);
5053   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5054       Context, ValType, /*consume*/ false);
5055   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5056   if (ValArg.isInvalid())
5057     return ExprError();
5058 
5059   TheCall->setArg(0, ValArg.get());
5060   TheCall->setType(Context.VoidTy);
5061   return TheCallResult;
5062 }
5063 
5064 /// CheckObjCString - Checks that the argument to the builtin
5065 /// CFString constructor is correct
5066 /// Note: It might also make sense to do the UTF-16 conversion here (would
5067 /// simplify the backend).
5068 bool Sema::CheckObjCString(Expr *Arg) {
5069   Arg = Arg->IgnoreParenCasts();
5070   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5071 
5072   if (!Literal || !Literal->isAscii()) {
5073     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
5074       << Arg->getSourceRange();
5075     return true;
5076   }
5077 
5078   if (Literal->containsNonAsciiOrNull()) {
5079     StringRef String = Literal->getString();
5080     unsigned NumBytes = String.size();
5081     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5082     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5083     llvm::UTF16 *ToPtr = &ToBuf[0];
5084 
5085     llvm::ConversionResult Result =
5086         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5087                                  ToPtr + NumBytes, llvm::strictConversion);
5088     // Check for conversion failure.
5089     if (Result != llvm::conversionOK)
5090       Diag(Arg->getLocStart(),
5091            diag::warn_cfstring_truncated) << Arg->getSourceRange();
5092   }
5093   return false;
5094 }
5095 
5096 /// CheckObjCString - Checks that the format string argument to the os_log()
5097 /// and os_trace() functions is correct, and converts it to const char *.
5098 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5099   Arg = Arg->IgnoreParenCasts();
5100   auto *Literal = dyn_cast<StringLiteral>(Arg);
5101   if (!Literal) {
5102     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5103       Literal = ObjcLiteral->getString();
5104     }
5105   }
5106 
5107   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5108     return ExprError(
5109         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
5110         << Arg->getSourceRange());
5111   }
5112 
5113   ExprResult Result(Literal);
5114   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5115   InitializedEntity Entity =
5116       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5117   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5118   return Result;
5119 }
5120 
5121 /// Check that the user is calling the appropriate va_start builtin for the
5122 /// target and calling convention.
5123 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5124   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5125   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5126   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5127   bool IsWindows = TT.isOSWindows();
5128   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5129   if (IsX64 || IsAArch64) {
5130     CallingConv CC = CC_C;
5131     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5132       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5133     if (IsMSVAStart) {
5134       // Don't allow this in System V ABI functions.
5135       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5136         return S.Diag(Fn->getLocStart(),
5137                       diag::err_ms_va_start_used_in_sysv_function);
5138     } else {
5139       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5140       // On x64 Windows, don't allow this in System V ABI functions.
5141       // (Yes, that means there's no corresponding way to support variadic
5142       // System V ABI functions on Windows.)
5143       if ((IsWindows && CC == CC_X86_64SysV) ||
5144           (!IsWindows && CC == CC_Win64))
5145         return S.Diag(Fn->getLocStart(),
5146                       diag::err_va_start_used_in_wrong_abi_function)
5147                << !IsWindows;
5148     }
5149     return false;
5150   }
5151 
5152   if (IsMSVAStart)
5153     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
5154   return false;
5155 }
5156 
5157 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5158                                              ParmVarDecl **LastParam = nullptr) {
5159   // Determine whether the current function, block, or obj-c method is variadic
5160   // and get its parameter list.
5161   bool IsVariadic = false;
5162   ArrayRef<ParmVarDecl *> Params;
5163   DeclContext *Caller = S.CurContext;
5164   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5165     IsVariadic = Block->isVariadic();
5166     Params = Block->parameters();
5167   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5168     IsVariadic = FD->isVariadic();
5169     Params = FD->parameters();
5170   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5171     IsVariadic = MD->isVariadic();
5172     // FIXME: This isn't correct for methods (results in bogus warning).
5173     Params = MD->parameters();
5174   } else if (isa<CapturedDecl>(Caller)) {
5175     // We don't support va_start in a CapturedDecl.
5176     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
5177     return true;
5178   } else {
5179     // This must be some other declcontext that parses exprs.
5180     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
5181     return true;
5182   }
5183 
5184   if (!IsVariadic) {
5185     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
5186     return true;
5187   }
5188 
5189   if (LastParam)
5190     *LastParam = Params.empty() ? nullptr : Params.back();
5191 
5192   return false;
5193 }
5194 
5195 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5196 /// for validity.  Emit an error and return true on failure; return false
5197 /// on success.
5198 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5199   Expr *Fn = TheCall->getCallee();
5200 
5201   if (checkVAStartABI(*this, BuiltinID, Fn))
5202     return true;
5203 
5204   if (TheCall->getNumArgs() > 2) {
5205     Diag(TheCall->getArg(2)->getLocStart(),
5206          diag::err_typecheck_call_too_many_args)
5207       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5208       << Fn->getSourceRange()
5209       << SourceRange(TheCall->getArg(2)->getLocStart(),
5210                      (*(TheCall->arg_end()-1))->getLocEnd());
5211     return true;
5212   }
5213 
5214   if (TheCall->getNumArgs() < 2) {
5215     return Diag(TheCall->getLocEnd(),
5216       diag::err_typecheck_call_too_few_args_at_least)
5217       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5218   }
5219 
5220   // Type-check the first argument normally.
5221   if (checkBuiltinArgument(*this, TheCall, 0))
5222     return true;
5223 
5224   // Check that the current function is variadic, and get its last parameter.
5225   ParmVarDecl *LastParam;
5226   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5227     return true;
5228 
5229   // Verify that the second argument to the builtin is the last argument of the
5230   // current function or method.
5231   bool SecondArgIsLastNamedArgument = false;
5232   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5233 
5234   // These are valid if SecondArgIsLastNamedArgument is false after the next
5235   // block.
5236   QualType Type;
5237   SourceLocation ParamLoc;
5238   bool IsCRegister = false;
5239 
5240   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5241     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5242       SecondArgIsLastNamedArgument = PV == LastParam;
5243 
5244       Type = PV->getType();
5245       ParamLoc = PV->getLocation();
5246       IsCRegister =
5247           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5248     }
5249   }
5250 
5251   if (!SecondArgIsLastNamedArgument)
5252     Diag(TheCall->getArg(1)->getLocStart(),
5253          diag::warn_second_arg_of_va_start_not_last_named_param);
5254   else if (IsCRegister || Type->isReferenceType() ||
5255            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5256              // Promotable integers are UB, but enumerations need a bit of
5257              // extra checking to see what their promotable type actually is.
5258              if (!Type->isPromotableIntegerType())
5259                return false;
5260              if (!Type->isEnumeralType())
5261                return true;
5262              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5263              return !(ED &&
5264                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5265            }()) {
5266     unsigned Reason = 0;
5267     if (Type->isReferenceType())  Reason = 1;
5268     else if (IsCRegister)         Reason = 2;
5269     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
5270     Diag(ParamLoc, diag::note_parameter_type) << Type;
5271   }
5272 
5273   TheCall->setType(Context.VoidTy);
5274   return false;
5275 }
5276 
5277 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5278   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5279   //                 const char *named_addr);
5280 
5281   Expr *Func = Call->getCallee();
5282 
5283   if (Call->getNumArgs() < 3)
5284     return Diag(Call->getLocEnd(),
5285                 diag::err_typecheck_call_too_few_args_at_least)
5286            << 0 /*function call*/ << 3 << Call->getNumArgs();
5287 
5288   // Type-check the first argument normally.
5289   if (checkBuiltinArgument(*this, Call, 0))
5290     return true;
5291 
5292   // Check that the current function is variadic.
5293   if (checkVAStartIsInVariadicFunction(*this, Func))
5294     return true;
5295 
5296   // __va_start on Windows does not validate the parameter qualifiers
5297 
5298   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5299   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5300 
5301   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5302   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5303 
5304   const QualType &ConstCharPtrTy =
5305       Context.getPointerType(Context.CharTy.withConst());
5306   if (!Arg1Ty->isPointerType() ||
5307       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5308     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
5309         << Arg1->getType() << ConstCharPtrTy
5310         << 1 /* different class */
5311         << 0 /* qualifier difference */
5312         << 3 /* parameter mismatch */
5313         << 2 << Arg1->getType() << ConstCharPtrTy;
5314 
5315   const QualType SizeTy = Context.getSizeType();
5316   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5317     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
5318         << Arg2->getType() << SizeTy
5319         << 1 /* different class */
5320         << 0 /* qualifier difference */
5321         << 3 /* parameter mismatch */
5322         << 3 << Arg2->getType() << SizeTy;
5323 
5324   return false;
5325 }
5326 
5327 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5328 /// friends.  This is declared to take (...), so we have to check everything.
5329 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5330   if (TheCall->getNumArgs() < 2)
5331     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
5332       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
5333   if (TheCall->getNumArgs() > 2)
5334     return Diag(TheCall->getArg(2)->getLocStart(),
5335                 diag::err_typecheck_call_too_many_args)
5336       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5337       << SourceRange(TheCall->getArg(2)->getLocStart(),
5338                      (*(TheCall->arg_end()-1))->getLocEnd());
5339 
5340   ExprResult OrigArg0 = TheCall->getArg(0);
5341   ExprResult OrigArg1 = TheCall->getArg(1);
5342 
5343   // Do standard promotions between the two arguments, returning their common
5344   // type.
5345   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5346   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5347     return true;
5348 
5349   // Make sure any conversions are pushed back into the call; this is
5350   // type safe since unordered compare builtins are declared as "_Bool
5351   // foo(...)".
5352   TheCall->setArg(0, OrigArg0.get());
5353   TheCall->setArg(1, OrigArg1.get());
5354 
5355   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5356     return false;
5357 
5358   // If the common type isn't a real floating type, then the arguments were
5359   // invalid for this operation.
5360   if (Res.isNull() || !Res->isRealFloatingType())
5361     return Diag(OrigArg0.get()->getLocStart(),
5362                 diag::err_typecheck_call_invalid_ordered_compare)
5363       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5364       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
5365 
5366   return false;
5367 }
5368 
5369 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5370 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5371 /// to check everything. We expect the last argument to be a floating point
5372 /// value.
5373 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5374   if (TheCall->getNumArgs() < NumArgs)
5375     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
5376       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
5377   if (TheCall->getNumArgs() > NumArgs)
5378     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
5379                 diag::err_typecheck_call_too_many_args)
5380       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5381       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
5382                      (*(TheCall->arg_end()-1))->getLocEnd());
5383 
5384   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5385 
5386   if (OrigArg->isTypeDependent())
5387     return false;
5388 
5389   // This operation requires a non-_Complex floating-point number.
5390   if (!OrigArg->getType()->isRealFloatingType())
5391     return Diag(OrigArg->getLocStart(),
5392                 diag::err_typecheck_call_invalid_unary_fp)
5393       << OrigArg->getType() << OrigArg->getSourceRange();
5394 
5395   // If this is an implicit conversion from float -> float, double, or
5396   // long double, remove it.
5397   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5398     // Only remove standard FloatCasts, leaving other casts inplace
5399     if (Cast->getCastKind() == CK_FloatingCast) {
5400       Expr *CastArg = Cast->getSubExpr();
5401       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5402         assert(
5403             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5404              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5405              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5406             "promotion from float to either float, double, or long double is "
5407             "the only expected cast here");
5408         Cast->setSubExpr(nullptr);
5409         TheCall->setArg(NumArgs-1, CastArg);
5410       }
5411     }
5412   }
5413 
5414   return false;
5415 }
5416 
5417 // Customized Sema Checking for VSX builtins that have the following signature:
5418 // vector [...] builtinName(vector [...], vector [...], const int);
5419 // Which takes the same type of vectors (any legal vector type) for the first
5420 // two arguments and takes compile time constant for the third argument.
5421 // Example builtins are :
5422 // vector double vec_xxpermdi(vector double, vector double, int);
5423 // vector short vec_xxsldwi(vector short, vector short, int);
5424 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5425   unsigned ExpectedNumArgs = 3;
5426   if (TheCall->getNumArgs() < ExpectedNumArgs)
5427     return Diag(TheCall->getLocEnd(),
5428                 diag::err_typecheck_call_too_few_args_at_least)
5429            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
5430            << TheCall->getSourceRange();
5431 
5432   if (TheCall->getNumArgs() > ExpectedNumArgs)
5433     return Diag(TheCall->getLocEnd(),
5434                 diag::err_typecheck_call_too_many_args_at_most)
5435            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5436            << TheCall->getSourceRange();
5437 
5438   // Check the third argument is a compile time constant
5439   llvm::APSInt Value;
5440   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5441     return Diag(TheCall->getLocStart(),
5442                 diag::err_vsx_builtin_nonconstant_argument)
5443            << 3 /* argument index */ << TheCall->getDirectCallee()
5444            << SourceRange(TheCall->getArg(2)->getLocStart(),
5445                           TheCall->getArg(2)->getLocEnd());
5446 
5447   QualType Arg1Ty = TheCall->getArg(0)->getType();
5448   QualType Arg2Ty = TheCall->getArg(1)->getType();
5449 
5450   // Check the type of argument 1 and argument 2 are vectors.
5451   SourceLocation BuiltinLoc = TheCall->getLocStart();
5452   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5453       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5454     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5455            << TheCall->getDirectCallee()
5456            << SourceRange(TheCall->getArg(0)->getLocStart(),
5457                           TheCall->getArg(1)->getLocEnd());
5458   }
5459 
5460   // Check the first two arguments are the same type.
5461   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5462     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5463            << TheCall->getDirectCallee()
5464            << SourceRange(TheCall->getArg(0)->getLocStart(),
5465                           TheCall->getArg(1)->getLocEnd());
5466   }
5467 
5468   // When default clang type checking is turned off and the customized type
5469   // checking is used, the returning type of the function must be explicitly
5470   // set. Otherwise it is _Bool by default.
5471   TheCall->setType(Arg1Ty);
5472 
5473   return false;
5474 }
5475 
5476 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5477 // This is declared to take (...), so we have to check everything.
5478 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5479   if (TheCall->getNumArgs() < 2)
5480     return ExprError(Diag(TheCall->getLocEnd(),
5481                           diag::err_typecheck_call_too_few_args_at_least)
5482                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5483                      << TheCall->getSourceRange());
5484 
5485   // Determine which of the following types of shufflevector we're checking:
5486   // 1) unary, vector mask: (lhs, mask)
5487   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5488   QualType resType = TheCall->getArg(0)->getType();
5489   unsigned numElements = 0;
5490 
5491   if (!TheCall->getArg(0)->isTypeDependent() &&
5492       !TheCall->getArg(1)->isTypeDependent()) {
5493     QualType LHSType = TheCall->getArg(0)->getType();
5494     QualType RHSType = TheCall->getArg(1)->getType();
5495 
5496     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5497       return ExprError(Diag(TheCall->getLocStart(),
5498                             diag::err_vec_builtin_non_vector)
5499                        << TheCall->getDirectCallee()
5500                        << SourceRange(TheCall->getArg(0)->getLocStart(),
5501                                       TheCall->getArg(1)->getLocEnd()));
5502 
5503     numElements = LHSType->getAs<VectorType>()->getNumElements();
5504     unsigned numResElements = TheCall->getNumArgs() - 2;
5505 
5506     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5507     // with mask.  If so, verify that RHS is an integer vector type with the
5508     // same number of elts as lhs.
5509     if (TheCall->getNumArgs() == 2) {
5510       if (!RHSType->hasIntegerRepresentation() ||
5511           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5512         return ExprError(Diag(TheCall->getLocStart(),
5513                               diag::err_vec_builtin_incompatible_vector)
5514                          << TheCall->getDirectCallee()
5515                          << SourceRange(TheCall->getArg(1)->getLocStart(),
5516                                         TheCall->getArg(1)->getLocEnd()));
5517     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5518       return ExprError(Diag(TheCall->getLocStart(),
5519                             diag::err_vec_builtin_incompatible_vector)
5520                        << TheCall->getDirectCallee()
5521                        << SourceRange(TheCall->getArg(0)->getLocStart(),
5522                                       TheCall->getArg(1)->getLocEnd()));
5523     } else if (numElements != numResElements) {
5524       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5525       resType = Context.getVectorType(eltType, numResElements,
5526                                       VectorType::GenericVector);
5527     }
5528   }
5529 
5530   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5531     if (TheCall->getArg(i)->isTypeDependent() ||
5532         TheCall->getArg(i)->isValueDependent())
5533       continue;
5534 
5535     llvm::APSInt Result(32);
5536     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5537       return ExprError(Diag(TheCall->getLocStart(),
5538                             diag::err_shufflevector_nonconstant_argument)
5539                        << TheCall->getArg(i)->getSourceRange());
5540 
5541     // Allow -1 which will be translated to undef in the IR.
5542     if (Result.isSigned() && Result.isAllOnesValue())
5543       continue;
5544 
5545     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5546       return ExprError(Diag(TheCall->getLocStart(),
5547                             diag::err_shufflevector_argument_too_large)
5548                        << TheCall->getArg(i)->getSourceRange());
5549   }
5550 
5551   SmallVector<Expr*, 32> exprs;
5552 
5553   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5554     exprs.push_back(TheCall->getArg(i));
5555     TheCall->setArg(i, nullptr);
5556   }
5557 
5558   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5559                                          TheCall->getCallee()->getLocStart(),
5560                                          TheCall->getRParenLoc());
5561 }
5562 
5563 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5564 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5565                                        SourceLocation BuiltinLoc,
5566                                        SourceLocation RParenLoc) {
5567   ExprValueKind VK = VK_RValue;
5568   ExprObjectKind OK = OK_Ordinary;
5569   QualType DstTy = TInfo->getType();
5570   QualType SrcTy = E->getType();
5571 
5572   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5573     return ExprError(Diag(BuiltinLoc,
5574                           diag::err_convertvector_non_vector)
5575                      << E->getSourceRange());
5576   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5577     return ExprError(Diag(BuiltinLoc,
5578                           diag::err_convertvector_non_vector_type));
5579 
5580   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5581     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5582     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5583     if (SrcElts != DstElts)
5584       return ExprError(Diag(BuiltinLoc,
5585                             diag::err_convertvector_incompatible_vector)
5586                        << E->getSourceRange());
5587   }
5588 
5589   return new (Context)
5590       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5591 }
5592 
5593 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5594 // This is declared to take (const void*, ...) and can take two
5595 // optional constant int args.
5596 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5597   unsigned NumArgs = TheCall->getNumArgs();
5598 
5599   if (NumArgs > 3)
5600     return Diag(TheCall->getLocEnd(),
5601              diag::err_typecheck_call_too_many_args_at_most)
5602              << 0 /*function call*/ << 3 << NumArgs
5603              << TheCall->getSourceRange();
5604 
5605   // Argument 0 is checked for us and the remaining arguments must be
5606   // constant integers.
5607   for (unsigned i = 1; i != NumArgs; ++i)
5608     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5609       return true;
5610 
5611   return false;
5612 }
5613 
5614 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5615 // __assume does not evaluate its arguments, and should warn if its argument
5616 // has side effects.
5617 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5618   Expr *Arg = TheCall->getArg(0);
5619   if (Arg->isInstantiationDependent()) return false;
5620 
5621   if (Arg->HasSideEffects(Context))
5622     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
5623       << Arg->getSourceRange()
5624       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5625 
5626   return false;
5627 }
5628 
5629 /// Handle __builtin_alloca_with_align. This is declared
5630 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5631 /// than 8.
5632 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5633   // The alignment must be a constant integer.
5634   Expr *Arg = TheCall->getArg(1);
5635 
5636   // We can't check the value of a dependent argument.
5637   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5638     if (const auto *UE =
5639             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5640       if (UE->getKind() == UETT_AlignOf)
5641         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
5642           << Arg->getSourceRange();
5643 
5644     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5645 
5646     if (!Result.isPowerOf2())
5647       return Diag(TheCall->getLocStart(),
5648                   diag::err_alignment_not_power_of_two)
5649            << Arg->getSourceRange();
5650 
5651     if (Result < Context.getCharWidth())
5652       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
5653            << (unsigned)Context.getCharWidth()
5654            << Arg->getSourceRange();
5655 
5656     if (Result > std::numeric_limits<int32_t>::max())
5657       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
5658            << std::numeric_limits<int32_t>::max()
5659            << Arg->getSourceRange();
5660   }
5661 
5662   return false;
5663 }
5664 
5665 /// Handle __builtin_assume_aligned. This is declared
5666 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5667 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5668   unsigned NumArgs = TheCall->getNumArgs();
5669 
5670   if (NumArgs > 3)
5671     return Diag(TheCall->getLocEnd(),
5672              diag::err_typecheck_call_too_many_args_at_most)
5673              << 0 /*function call*/ << 3 << NumArgs
5674              << TheCall->getSourceRange();
5675 
5676   // The alignment must be a constant integer.
5677   Expr *Arg = TheCall->getArg(1);
5678 
5679   // We can't check the value of a dependent argument.
5680   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5681     llvm::APSInt Result;
5682     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5683       return true;
5684 
5685     if (!Result.isPowerOf2())
5686       return Diag(TheCall->getLocStart(),
5687                   diag::err_alignment_not_power_of_two)
5688            << Arg->getSourceRange();
5689   }
5690 
5691   if (NumArgs > 2) {
5692     ExprResult Arg(TheCall->getArg(2));
5693     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5694       Context.getSizeType(), false);
5695     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5696     if (Arg.isInvalid()) return true;
5697     TheCall->setArg(2, Arg.get());
5698   }
5699 
5700   return false;
5701 }
5702 
5703 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5704   unsigned BuiltinID =
5705       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5706   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5707 
5708   unsigned NumArgs = TheCall->getNumArgs();
5709   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5710   if (NumArgs < NumRequiredArgs) {
5711     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
5712            << 0 /* function call */ << NumRequiredArgs << NumArgs
5713            << TheCall->getSourceRange();
5714   }
5715   if (NumArgs >= NumRequiredArgs + 0x100) {
5716     return Diag(TheCall->getLocEnd(),
5717                 diag::err_typecheck_call_too_many_args_at_most)
5718            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5719            << TheCall->getSourceRange();
5720   }
5721   unsigned i = 0;
5722 
5723   // For formatting call, check buffer arg.
5724   if (!IsSizeCall) {
5725     ExprResult Arg(TheCall->getArg(i));
5726     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5727         Context, Context.VoidPtrTy, false);
5728     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5729     if (Arg.isInvalid())
5730       return true;
5731     TheCall->setArg(i, Arg.get());
5732     i++;
5733   }
5734 
5735   // Check string literal arg.
5736   unsigned FormatIdx = i;
5737   {
5738     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5739     if (Arg.isInvalid())
5740       return true;
5741     TheCall->setArg(i, Arg.get());
5742     i++;
5743   }
5744 
5745   // Make sure variadic args are scalar.
5746   unsigned FirstDataArg = i;
5747   while (i < NumArgs) {
5748     ExprResult Arg = DefaultVariadicArgumentPromotion(
5749         TheCall->getArg(i), VariadicFunction, nullptr);
5750     if (Arg.isInvalid())
5751       return true;
5752     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5753     if (ArgSize.getQuantity() >= 0x100) {
5754       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
5755              << i << (int)ArgSize.getQuantity() << 0xff
5756              << TheCall->getSourceRange();
5757     }
5758     TheCall->setArg(i, Arg.get());
5759     i++;
5760   }
5761 
5762   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5763   // call to avoid duplicate diagnostics.
5764   if (!IsSizeCall) {
5765     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5766     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5767     bool Success = CheckFormatArguments(
5768         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5769         VariadicFunction, TheCall->getLocStart(), SourceRange(),
5770         CheckedVarArgs);
5771     if (!Success)
5772       return true;
5773   }
5774 
5775   if (IsSizeCall) {
5776     TheCall->setType(Context.getSizeType());
5777   } else {
5778     TheCall->setType(Context.VoidPtrTy);
5779   }
5780   return false;
5781 }
5782 
5783 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5784 /// TheCall is a constant expression.
5785 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5786                                   llvm::APSInt &Result) {
5787   Expr *Arg = TheCall->getArg(ArgNum);
5788   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5789   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5790 
5791   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5792 
5793   if (!Arg->isIntegerConstantExpr(Result, Context))
5794     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
5795                 << FDecl->getDeclName() <<  Arg->getSourceRange();
5796 
5797   return false;
5798 }
5799 
5800 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5801 /// TheCall is a constant expression in the range [Low, High].
5802 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5803                                        int Low, int High, bool RangeIsError) {
5804   llvm::APSInt Result;
5805 
5806   // We can't check the value of a dependent argument.
5807   Expr *Arg = TheCall->getArg(ArgNum);
5808   if (Arg->isTypeDependent() || Arg->isValueDependent())
5809     return false;
5810 
5811   // Check constant-ness first.
5812   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5813     return true;
5814 
5815   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5816     if (RangeIsError)
5817       return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
5818              << Result.toString(10) << Low << High << Arg->getSourceRange();
5819     else
5820       // Defer the warning until we know if the code will be emitted so that
5821       // dead code can ignore this.
5822       DiagRuntimeBehavior(TheCall->getLocStart(), TheCall,
5823                             PDiag(diag::warn_argument_invalid_range)
5824                                 << Result.toString(10) << Low << High
5825                                 << Arg->getSourceRange());
5826   }
5827 
5828   return false;
5829 }
5830 
5831 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5832 /// TheCall is a constant expression is a multiple of Num..
5833 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5834                                           unsigned Num) {
5835   llvm::APSInt Result;
5836 
5837   // We can't check the value of a dependent argument.
5838   Expr *Arg = TheCall->getArg(ArgNum);
5839   if (Arg->isTypeDependent() || Arg->isValueDependent())
5840     return false;
5841 
5842   // Check constant-ness first.
5843   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5844     return true;
5845 
5846   if (Result.getSExtValue() % Num != 0)
5847     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5848       << Num << Arg->getSourceRange();
5849 
5850   return false;
5851 }
5852 
5853 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5854 /// TheCall is an ARM/AArch64 special register string literal.
5855 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5856                                     int ArgNum, unsigned ExpectedFieldNum,
5857                                     bool AllowName) {
5858   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5859                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5860                       BuiltinID == ARM::BI__builtin_arm_rsr ||
5861                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
5862                       BuiltinID == ARM::BI__builtin_arm_wsr ||
5863                       BuiltinID == ARM::BI__builtin_arm_wsrp;
5864   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5865                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5866                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
5867                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5868                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
5869                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
5870   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5871 
5872   // We can't check the value of a dependent argument.
5873   Expr *Arg = TheCall->getArg(ArgNum);
5874   if (Arg->isTypeDependent() || Arg->isValueDependent())
5875     return false;
5876 
5877   // Check if the argument is a string literal.
5878   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5879     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5880            << Arg->getSourceRange();
5881 
5882   // Check the type of special register given.
5883   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5884   SmallVector<StringRef, 6> Fields;
5885   Reg.split(Fields, ":");
5886 
5887   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5888     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5889            << Arg->getSourceRange();
5890 
5891   // If the string is the name of a register then we cannot check that it is
5892   // valid here but if the string is of one the forms described in ACLE then we
5893   // can check that the supplied fields are integers and within the valid
5894   // ranges.
5895   if (Fields.size() > 1) {
5896     bool FiveFields = Fields.size() == 5;
5897 
5898     bool ValidString = true;
5899     if (IsARMBuiltin) {
5900       ValidString &= Fields[0].startswith_lower("cp") ||
5901                      Fields[0].startswith_lower("p");
5902       if (ValidString)
5903         Fields[0] =
5904           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5905 
5906       ValidString &= Fields[2].startswith_lower("c");
5907       if (ValidString)
5908         Fields[2] = Fields[2].drop_front(1);
5909 
5910       if (FiveFields) {
5911         ValidString &= Fields[3].startswith_lower("c");
5912         if (ValidString)
5913           Fields[3] = Fields[3].drop_front(1);
5914       }
5915     }
5916 
5917     SmallVector<int, 5> Ranges;
5918     if (FiveFields)
5919       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
5920     else
5921       Ranges.append({15, 7, 15});
5922 
5923     for (unsigned i=0; i<Fields.size(); ++i) {
5924       int IntField;
5925       ValidString &= !Fields[i].getAsInteger(10, IntField);
5926       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5927     }
5928 
5929     if (!ValidString)
5930       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5931              << Arg->getSourceRange();
5932   } else if (IsAArch64Builtin && Fields.size() == 1) {
5933     // If the register name is one of those that appear in the condition below
5934     // and the special register builtin being used is one of the write builtins,
5935     // then we require that the argument provided for writing to the register
5936     // is an integer constant expression. This is because it will be lowered to
5937     // an MSR (immediate) instruction, so we need to know the immediate at
5938     // compile time.
5939     if (TheCall->getNumArgs() != 2)
5940       return false;
5941 
5942     std::string RegLower = Reg.lower();
5943     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5944         RegLower != "pan" && RegLower != "uao")
5945       return false;
5946 
5947     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5948   }
5949 
5950   return false;
5951 }
5952 
5953 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
5954 /// This checks that the target supports __builtin_longjmp and
5955 /// that val is a constant 1.
5956 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
5957   if (!Context.getTargetInfo().hasSjLjLowering())
5958     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5959              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5960 
5961   Expr *Arg = TheCall->getArg(1);
5962   llvm::APSInt Result;
5963 
5964   // TODO: This is less than ideal. Overload this to take a value.
5965   if (SemaBuiltinConstantArg(TheCall, 1, Result))
5966     return true;
5967 
5968   if (Result != 1)
5969     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5970              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5971 
5972   return false;
5973 }
5974 
5975 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5976 /// This checks that the target supports __builtin_setjmp.
5977 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5978   if (!Context.getTargetInfo().hasSjLjLowering())
5979     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5980              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5981   return false;
5982 }
5983 
5984 namespace {
5985 
5986 class UncoveredArgHandler {
5987   enum { Unknown = -1, AllCovered = -2 };
5988 
5989   signed FirstUncoveredArg = Unknown;
5990   SmallVector<const Expr *, 4> DiagnosticExprs;
5991 
5992 public:
5993   UncoveredArgHandler() = default;
5994 
5995   bool hasUncoveredArg() const {
5996     return (FirstUncoveredArg >= 0);
5997   }
5998 
5999   unsigned getUncoveredArg() const {
6000     assert(hasUncoveredArg() && "no uncovered argument");
6001     return FirstUncoveredArg;
6002   }
6003 
6004   void setAllCovered() {
6005     // A string has been found with all arguments covered, so clear out
6006     // the diagnostics.
6007     DiagnosticExprs.clear();
6008     FirstUncoveredArg = AllCovered;
6009   }
6010 
6011   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6012     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6013 
6014     // Don't update if a previous string covers all arguments.
6015     if (FirstUncoveredArg == AllCovered)
6016       return;
6017 
6018     // UncoveredArgHandler tracks the highest uncovered argument index
6019     // and with it all the strings that match this index.
6020     if (NewFirstUncoveredArg == FirstUncoveredArg)
6021       DiagnosticExprs.push_back(StrExpr);
6022     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6023       DiagnosticExprs.clear();
6024       DiagnosticExprs.push_back(StrExpr);
6025       FirstUncoveredArg = NewFirstUncoveredArg;
6026     }
6027   }
6028 
6029   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6030 };
6031 
6032 enum StringLiteralCheckType {
6033   SLCT_NotALiteral,
6034   SLCT_UncheckedLiteral,
6035   SLCT_CheckedLiteral
6036 };
6037 
6038 } // namespace
6039 
6040 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6041                                      BinaryOperatorKind BinOpKind,
6042                                      bool AddendIsRight) {
6043   unsigned BitWidth = Offset.getBitWidth();
6044   unsigned AddendBitWidth = Addend.getBitWidth();
6045   // There might be negative interim results.
6046   if (Addend.isUnsigned()) {
6047     Addend = Addend.zext(++AddendBitWidth);
6048     Addend.setIsSigned(true);
6049   }
6050   // Adjust the bit width of the APSInts.
6051   if (AddendBitWidth > BitWidth) {
6052     Offset = Offset.sext(AddendBitWidth);
6053     BitWidth = AddendBitWidth;
6054   } else if (BitWidth > AddendBitWidth) {
6055     Addend = Addend.sext(BitWidth);
6056   }
6057 
6058   bool Ov = false;
6059   llvm::APSInt ResOffset = Offset;
6060   if (BinOpKind == BO_Add)
6061     ResOffset = Offset.sadd_ov(Addend, Ov);
6062   else {
6063     assert(AddendIsRight && BinOpKind == BO_Sub &&
6064            "operator must be add or sub with addend on the right");
6065     ResOffset = Offset.ssub_ov(Addend, Ov);
6066   }
6067 
6068   // We add an offset to a pointer here so we should support an offset as big as
6069   // possible.
6070   if (Ov) {
6071     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6072            "index (intermediate) result too big");
6073     Offset = Offset.sext(2 * BitWidth);
6074     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6075     return;
6076   }
6077 
6078   Offset = ResOffset;
6079 }
6080 
6081 namespace {
6082 
6083 // This is a wrapper class around StringLiteral to support offsetted string
6084 // literals as format strings. It takes the offset into account when returning
6085 // the string and its length or the source locations to display notes correctly.
6086 class FormatStringLiteral {
6087   const StringLiteral *FExpr;
6088   int64_t Offset;
6089 
6090  public:
6091   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6092       : FExpr(fexpr), Offset(Offset) {}
6093 
6094   StringRef getString() const {
6095     return FExpr->getString().drop_front(Offset);
6096   }
6097 
6098   unsigned getByteLength() const {
6099     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6100   }
6101 
6102   unsigned getLength() const { return FExpr->getLength() - Offset; }
6103   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6104 
6105   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6106 
6107   QualType getType() const { return FExpr->getType(); }
6108 
6109   bool isAscii() const { return FExpr->isAscii(); }
6110   bool isWide() const { return FExpr->isWide(); }
6111   bool isUTF8() const { return FExpr->isUTF8(); }
6112   bool isUTF16() const { return FExpr->isUTF16(); }
6113   bool isUTF32() const { return FExpr->isUTF32(); }
6114   bool isPascal() const { return FExpr->isPascal(); }
6115 
6116   SourceLocation getLocationOfByte(
6117       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6118       const TargetInfo &Target, unsigned *StartToken = nullptr,
6119       unsigned *StartTokenByteOffset = nullptr) const {
6120     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6121                                     StartToken, StartTokenByteOffset);
6122   }
6123 
6124   SourceLocation getLocStart() const LLVM_READONLY {
6125     return FExpr->getLocStart().getLocWithOffset(Offset);
6126   }
6127 
6128   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
6129 };
6130 
6131 }  // namespace
6132 
6133 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6134                               const Expr *OrigFormatExpr,
6135                               ArrayRef<const Expr *> Args,
6136                               bool HasVAListArg, unsigned format_idx,
6137                               unsigned firstDataArg,
6138                               Sema::FormatStringType Type,
6139                               bool inFunctionCall,
6140                               Sema::VariadicCallType CallType,
6141                               llvm::SmallBitVector &CheckedVarArgs,
6142                               UncoveredArgHandler &UncoveredArg);
6143 
6144 // Determine if an expression is a string literal or constant string.
6145 // If this function returns false on the arguments to a function expecting a
6146 // format string, we will usually need to emit a warning.
6147 // True string literals are then checked by CheckFormatString.
6148 static StringLiteralCheckType
6149 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6150                       bool HasVAListArg, unsigned format_idx,
6151                       unsigned firstDataArg, Sema::FormatStringType Type,
6152                       Sema::VariadicCallType CallType, bool InFunctionCall,
6153                       llvm::SmallBitVector &CheckedVarArgs,
6154                       UncoveredArgHandler &UncoveredArg,
6155                       llvm::APSInt Offset) {
6156  tryAgain:
6157   assert(Offset.isSigned() && "invalid offset");
6158 
6159   if (E->isTypeDependent() || E->isValueDependent())
6160     return SLCT_NotALiteral;
6161 
6162   E = E->IgnoreParenCasts();
6163 
6164   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6165     // Technically -Wformat-nonliteral does not warn about this case.
6166     // The behavior of printf and friends in this case is implementation
6167     // dependent.  Ideally if the format string cannot be null then
6168     // it should have a 'nonnull' attribute in the function prototype.
6169     return SLCT_UncheckedLiteral;
6170 
6171   switch (E->getStmtClass()) {
6172   case Stmt::BinaryConditionalOperatorClass:
6173   case Stmt::ConditionalOperatorClass: {
6174     // The expression is a literal if both sub-expressions were, and it was
6175     // completely checked only if both sub-expressions were checked.
6176     const AbstractConditionalOperator *C =
6177         cast<AbstractConditionalOperator>(E);
6178 
6179     // Determine whether it is necessary to check both sub-expressions, for
6180     // example, because the condition expression is a constant that can be
6181     // evaluated at compile time.
6182     bool CheckLeft = true, CheckRight = true;
6183 
6184     bool Cond;
6185     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6186       if (Cond)
6187         CheckRight = false;
6188       else
6189         CheckLeft = false;
6190     }
6191 
6192     // We need to maintain the offsets for the right and the left hand side
6193     // separately to check if every possible indexed expression is a valid
6194     // string literal. They might have different offsets for different string
6195     // literals in the end.
6196     StringLiteralCheckType Left;
6197     if (!CheckLeft)
6198       Left = SLCT_UncheckedLiteral;
6199     else {
6200       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6201                                    HasVAListArg, format_idx, firstDataArg,
6202                                    Type, CallType, InFunctionCall,
6203                                    CheckedVarArgs, UncoveredArg, Offset);
6204       if (Left == SLCT_NotALiteral || !CheckRight) {
6205         return Left;
6206       }
6207     }
6208 
6209     StringLiteralCheckType Right =
6210         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6211                               HasVAListArg, format_idx, firstDataArg,
6212                               Type, CallType, InFunctionCall, CheckedVarArgs,
6213                               UncoveredArg, Offset);
6214 
6215     return (CheckLeft && Left < Right) ? Left : Right;
6216   }
6217 
6218   case Stmt::ImplicitCastExprClass:
6219     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6220     goto tryAgain;
6221 
6222   case Stmt::OpaqueValueExprClass:
6223     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6224       E = src;
6225       goto tryAgain;
6226     }
6227     return SLCT_NotALiteral;
6228 
6229   case Stmt::PredefinedExprClass:
6230     // While __func__, etc., are technically not string literals, they
6231     // cannot contain format specifiers and thus are not a security
6232     // liability.
6233     return SLCT_UncheckedLiteral;
6234 
6235   case Stmt::DeclRefExprClass: {
6236     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6237 
6238     // As an exception, do not flag errors for variables binding to
6239     // const string literals.
6240     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6241       bool isConstant = false;
6242       QualType T = DR->getType();
6243 
6244       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6245         isConstant = AT->getElementType().isConstant(S.Context);
6246       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6247         isConstant = T.isConstant(S.Context) &&
6248                      PT->getPointeeType().isConstant(S.Context);
6249       } else if (T->isObjCObjectPointerType()) {
6250         // In ObjC, there is usually no "const ObjectPointer" type,
6251         // so don't check if the pointee type is constant.
6252         isConstant = T.isConstant(S.Context);
6253       }
6254 
6255       if (isConstant) {
6256         if (const Expr *Init = VD->getAnyInitializer()) {
6257           // Look through initializers like const char c[] = { "foo" }
6258           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6259             if (InitList->isStringLiteralInit())
6260               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6261           }
6262           return checkFormatStringExpr(S, Init, Args,
6263                                        HasVAListArg, format_idx,
6264                                        firstDataArg, Type, CallType,
6265                                        /*InFunctionCall*/ false, CheckedVarArgs,
6266                                        UncoveredArg, Offset);
6267         }
6268       }
6269 
6270       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6271       // special check to see if the format string is a function parameter
6272       // of the function calling the printf function.  If the function
6273       // has an attribute indicating it is a printf-like function, then we
6274       // should suppress warnings concerning non-literals being used in a call
6275       // to a vprintf function.  For example:
6276       //
6277       // void
6278       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6279       //      va_list ap;
6280       //      va_start(ap, fmt);
6281       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6282       //      ...
6283       // }
6284       if (HasVAListArg) {
6285         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6286           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6287             int PVIndex = PV->getFunctionScopeIndex() + 1;
6288             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6289               // adjust for implicit parameter
6290               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6291                 if (MD->isInstance())
6292                   ++PVIndex;
6293               // We also check if the formats are compatible.
6294               // We can't pass a 'scanf' string to a 'printf' function.
6295               if (PVIndex == PVFormat->getFormatIdx() &&
6296                   Type == S.GetFormatStringType(PVFormat))
6297                 return SLCT_UncheckedLiteral;
6298             }
6299           }
6300         }
6301       }
6302     }
6303 
6304     return SLCT_NotALiteral;
6305   }
6306 
6307   case Stmt::CallExprClass:
6308   case Stmt::CXXMemberCallExprClass: {
6309     const CallExpr *CE = cast<CallExpr>(E);
6310     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6311       bool IsFirst = true;
6312       StringLiteralCheckType CommonResult;
6313       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6314         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6315         StringLiteralCheckType Result = checkFormatStringExpr(
6316             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6317             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6318         if (IsFirst) {
6319           CommonResult = Result;
6320           IsFirst = false;
6321         }
6322       }
6323       if (!IsFirst)
6324         return CommonResult;
6325 
6326       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6327         unsigned BuiltinID = FD->getBuiltinID();
6328         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6329             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6330           const Expr *Arg = CE->getArg(0);
6331           return checkFormatStringExpr(S, Arg, Args,
6332                                        HasVAListArg, format_idx,
6333                                        firstDataArg, Type, CallType,
6334                                        InFunctionCall, CheckedVarArgs,
6335                                        UncoveredArg, Offset);
6336         }
6337       }
6338     }
6339 
6340     return SLCT_NotALiteral;
6341   }
6342   case Stmt::ObjCMessageExprClass: {
6343     const auto *ME = cast<ObjCMessageExpr>(E);
6344     if (const auto *ND = ME->getMethodDecl()) {
6345       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6346         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6347         return checkFormatStringExpr(
6348             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6349             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6350       }
6351     }
6352 
6353     return SLCT_NotALiteral;
6354   }
6355   case Stmt::ObjCStringLiteralClass:
6356   case Stmt::StringLiteralClass: {
6357     const StringLiteral *StrE = nullptr;
6358 
6359     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6360       StrE = ObjCFExpr->getString();
6361     else
6362       StrE = cast<StringLiteral>(E);
6363 
6364     if (StrE) {
6365       if (Offset.isNegative() || Offset > StrE->getLength()) {
6366         // TODO: It would be better to have an explicit warning for out of
6367         // bounds literals.
6368         return SLCT_NotALiteral;
6369       }
6370       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6371       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6372                         firstDataArg, Type, InFunctionCall, CallType,
6373                         CheckedVarArgs, UncoveredArg);
6374       return SLCT_CheckedLiteral;
6375     }
6376 
6377     return SLCT_NotALiteral;
6378   }
6379   case Stmt::BinaryOperatorClass: {
6380     llvm::APSInt LResult;
6381     llvm::APSInt RResult;
6382 
6383     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6384 
6385     // A string literal + an int offset is still a string literal.
6386     if (BinOp->isAdditiveOp()) {
6387       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6388       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6389 
6390       if (LIsInt != RIsInt) {
6391         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6392 
6393         if (LIsInt) {
6394           if (BinOpKind == BO_Add) {
6395             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
6396             E = BinOp->getRHS();
6397             goto tryAgain;
6398           }
6399         } else {
6400           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
6401           E = BinOp->getLHS();
6402           goto tryAgain;
6403         }
6404       }
6405     }
6406 
6407     return SLCT_NotALiteral;
6408   }
6409   case Stmt::UnaryOperatorClass: {
6410     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6411     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6412     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6413       llvm::APSInt IndexResult;
6414       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6415         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
6416         E = ASE->getBase();
6417         goto tryAgain;
6418       }
6419     }
6420 
6421     return SLCT_NotALiteral;
6422   }
6423 
6424   default:
6425     return SLCT_NotALiteral;
6426   }
6427 }
6428 
6429 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6430   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6431       .Case("scanf", FST_Scanf)
6432       .Cases("printf", "printf0", FST_Printf)
6433       .Cases("NSString", "CFString", FST_NSString)
6434       .Case("strftime", FST_Strftime)
6435       .Case("strfmon", FST_Strfmon)
6436       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6437       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6438       .Case("os_trace", FST_OSLog)
6439       .Case("os_log", FST_OSLog)
6440       .Default(FST_Unknown);
6441 }
6442 
6443 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6444 /// functions) for correct use of format strings.
6445 /// Returns true if a format string has been fully checked.
6446 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6447                                 ArrayRef<const Expr *> Args,
6448                                 bool IsCXXMember,
6449                                 VariadicCallType CallType,
6450                                 SourceLocation Loc, SourceRange Range,
6451                                 llvm::SmallBitVector &CheckedVarArgs) {
6452   FormatStringInfo FSI;
6453   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6454     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6455                                 FSI.FirstDataArg, GetFormatStringType(Format),
6456                                 CallType, Loc, Range, CheckedVarArgs);
6457   return false;
6458 }
6459 
6460 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6461                                 bool HasVAListArg, unsigned format_idx,
6462                                 unsigned firstDataArg, FormatStringType Type,
6463                                 VariadicCallType CallType,
6464                                 SourceLocation Loc, SourceRange Range,
6465                                 llvm::SmallBitVector &CheckedVarArgs) {
6466   // CHECK: printf/scanf-like function is called with no format string.
6467   if (format_idx >= Args.size()) {
6468     Diag(Loc, diag::warn_missing_format_string) << Range;
6469     return false;
6470   }
6471 
6472   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6473 
6474   // CHECK: format string is not a string literal.
6475   //
6476   // Dynamically generated format strings are difficult to
6477   // automatically vet at compile time.  Requiring that format strings
6478   // are string literals: (1) permits the checking of format strings by
6479   // the compiler and thereby (2) can practically remove the source of
6480   // many format string exploits.
6481 
6482   // Format string can be either ObjC string (e.g. @"%d") or
6483   // C string (e.g. "%d")
6484   // ObjC string uses the same format specifiers as C string, so we can use
6485   // the same format string checking logic for both ObjC and C strings.
6486   UncoveredArgHandler UncoveredArg;
6487   StringLiteralCheckType CT =
6488       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6489                             format_idx, firstDataArg, Type, CallType,
6490                             /*IsFunctionCall*/ true, CheckedVarArgs,
6491                             UncoveredArg,
6492                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6493 
6494   // Generate a diagnostic where an uncovered argument is detected.
6495   if (UncoveredArg.hasUncoveredArg()) {
6496     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6497     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6498     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6499   }
6500 
6501   if (CT != SLCT_NotALiteral)
6502     // Literal format string found, check done!
6503     return CT == SLCT_CheckedLiteral;
6504 
6505   // Strftime is particular as it always uses a single 'time' argument,
6506   // so it is safe to pass a non-literal string.
6507   if (Type == FST_Strftime)
6508     return false;
6509 
6510   // Do not emit diag when the string param is a macro expansion and the
6511   // format is either NSString or CFString. This is a hack to prevent
6512   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6513   // which are usually used in place of NS and CF string literals.
6514   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
6515   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6516     return false;
6517 
6518   // If there are no arguments specified, warn with -Wformat-security, otherwise
6519   // warn only with -Wformat-nonliteral.
6520   if (Args.size() == firstDataArg) {
6521     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6522       << OrigFormatExpr->getSourceRange();
6523     switch (Type) {
6524     default:
6525       break;
6526     case FST_Kprintf:
6527     case FST_FreeBSDKPrintf:
6528     case FST_Printf:
6529       Diag(FormatLoc, diag::note_format_security_fixit)
6530         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6531       break;
6532     case FST_NSString:
6533       Diag(FormatLoc, diag::note_format_security_fixit)
6534         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6535       break;
6536     }
6537   } else {
6538     Diag(FormatLoc, diag::warn_format_nonliteral)
6539       << OrigFormatExpr->getSourceRange();
6540   }
6541   return false;
6542 }
6543 
6544 namespace {
6545 
6546 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6547 protected:
6548   Sema &S;
6549   const FormatStringLiteral *FExpr;
6550   const Expr *OrigFormatExpr;
6551   const Sema::FormatStringType FSType;
6552   const unsigned FirstDataArg;
6553   const unsigned NumDataArgs;
6554   const char *Beg; // Start of format string.
6555   const bool HasVAListArg;
6556   ArrayRef<const Expr *> Args;
6557   unsigned FormatIdx;
6558   llvm::SmallBitVector CoveredArgs;
6559   bool usesPositionalArgs = false;
6560   bool atFirstArg = true;
6561   bool inFunctionCall;
6562   Sema::VariadicCallType CallType;
6563   llvm::SmallBitVector &CheckedVarArgs;
6564   UncoveredArgHandler &UncoveredArg;
6565 
6566 public:
6567   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6568                      const Expr *origFormatExpr,
6569                      const Sema::FormatStringType type, unsigned firstDataArg,
6570                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6571                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6572                      bool inFunctionCall, Sema::VariadicCallType callType,
6573                      llvm::SmallBitVector &CheckedVarArgs,
6574                      UncoveredArgHandler &UncoveredArg)
6575       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6576         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6577         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6578         inFunctionCall(inFunctionCall), CallType(callType),
6579         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6580     CoveredArgs.resize(numDataArgs);
6581     CoveredArgs.reset();
6582   }
6583 
6584   void DoneProcessing();
6585 
6586   void HandleIncompleteSpecifier(const char *startSpecifier,
6587                                  unsigned specifierLen) override;
6588 
6589   void HandleInvalidLengthModifier(
6590                            const analyze_format_string::FormatSpecifier &FS,
6591                            const analyze_format_string::ConversionSpecifier &CS,
6592                            const char *startSpecifier, unsigned specifierLen,
6593                            unsigned DiagID);
6594 
6595   void HandleNonStandardLengthModifier(
6596                     const analyze_format_string::FormatSpecifier &FS,
6597                     const char *startSpecifier, unsigned specifierLen);
6598 
6599   void HandleNonStandardConversionSpecifier(
6600                     const analyze_format_string::ConversionSpecifier &CS,
6601                     const char *startSpecifier, unsigned specifierLen);
6602 
6603   void HandlePosition(const char *startPos, unsigned posLen) override;
6604 
6605   void HandleInvalidPosition(const char *startSpecifier,
6606                              unsigned specifierLen,
6607                              analyze_format_string::PositionContext p) override;
6608 
6609   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6610 
6611   void HandleNullChar(const char *nullCharacter) override;
6612 
6613   template <typename Range>
6614   static void
6615   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6616                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6617                        bool IsStringLocation, Range StringRange,
6618                        ArrayRef<FixItHint> Fixit = None);
6619 
6620 protected:
6621   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6622                                         const char *startSpec,
6623                                         unsigned specifierLen,
6624                                         const char *csStart, unsigned csLen);
6625 
6626   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6627                                          const char *startSpec,
6628                                          unsigned specifierLen);
6629 
6630   SourceRange getFormatStringRange();
6631   CharSourceRange getSpecifierRange(const char *startSpecifier,
6632                                     unsigned specifierLen);
6633   SourceLocation getLocationOfByte(const char *x);
6634 
6635   const Expr *getDataArg(unsigned i) const;
6636 
6637   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6638                     const analyze_format_string::ConversionSpecifier &CS,
6639                     const char *startSpecifier, unsigned specifierLen,
6640                     unsigned argIndex);
6641 
6642   template <typename Range>
6643   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6644                             bool IsStringLocation, Range StringRange,
6645                             ArrayRef<FixItHint> Fixit = None);
6646 };
6647 
6648 } // namespace
6649 
6650 SourceRange CheckFormatHandler::getFormatStringRange() {
6651   return OrigFormatExpr->getSourceRange();
6652 }
6653 
6654 CharSourceRange CheckFormatHandler::
6655 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6656   SourceLocation Start = getLocationOfByte(startSpecifier);
6657   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6658 
6659   // Advance the end SourceLocation by one due to half-open ranges.
6660   End = End.getLocWithOffset(1);
6661 
6662   return CharSourceRange::getCharRange(Start, End);
6663 }
6664 
6665 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6666   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6667                                   S.getLangOpts(), S.Context.getTargetInfo());
6668 }
6669 
6670 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6671                                                    unsigned specifierLen){
6672   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6673                        getLocationOfByte(startSpecifier),
6674                        /*IsStringLocation*/true,
6675                        getSpecifierRange(startSpecifier, specifierLen));
6676 }
6677 
6678 void CheckFormatHandler::HandleInvalidLengthModifier(
6679     const analyze_format_string::FormatSpecifier &FS,
6680     const analyze_format_string::ConversionSpecifier &CS,
6681     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6682   using namespace analyze_format_string;
6683 
6684   const LengthModifier &LM = FS.getLengthModifier();
6685   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6686 
6687   // See if we know how to fix this length modifier.
6688   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6689   if (FixedLM) {
6690     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6691                          getLocationOfByte(LM.getStart()),
6692                          /*IsStringLocation*/true,
6693                          getSpecifierRange(startSpecifier, specifierLen));
6694 
6695     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6696       << FixedLM->toString()
6697       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6698 
6699   } else {
6700     FixItHint Hint;
6701     if (DiagID == diag::warn_format_nonsensical_length)
6702       Hint = FixItHint::CreateRemoval(LMRange);
6703 
6704     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6705                          getLocationOfByte(LM.getStart()),
6706                          /*IsStringLocation*/true,
6707                          getSpecifierRange(startSpecifier, specifierLen),
6708                          Hint);
6709   }
6710 }
6711 
6712 void CheckFormatHandler::HandleNonStandardLengthModifier(
6713     const analyze_format_string::FormatSpecifier &FS,
6714     const char *startSpecifier, unsigned specifierLen) {
6715   using namespace analyze_format_string;
6716 
6717   const LengthModifier &LM = FS.getLengthModifier();
6718   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6719 
6720   // See if we know how to fix this length modifier.
6721   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6722   if (FixedLM) {
6723     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6724                            << LM.toString() << 0,
6725                          getLocationOfByte(LM.getStart()),
6726                          /*IsStringLocation*/true,
6727                          getSpecifierRange(startSpecifier, specifierLen));
6728 
6729     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6730       << FixedLM->toString()
6731       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6732 
6733   } else {
6734     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6735                            << LM.toString() << 0,
6736                          getLocationOfByte(LM.getStart()),
6737                          /*IsStringLocation*/true,
6738                          getSpecifierRange(startSpecifier, specifierLen));
6739   }
6740 }
6741 
6742 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6743     const analyze_format_string::ConversionSpecifier &CS,
6744     const char *startSpecifier, unsigned specifierLen) {
6745   using namespace analyze_format_string;
6746 
6747   // See if we know how to fix this conversion specifier.
6748   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6749   if (FixedCS) {
6750     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6751                           << CS.toString() << /*conversion specifier*/1,
6752                          getLocationOfByte(CS.getStart()),
6753                          /*IsStringLocation*/true,
6754                          getSpecifierRange(startSpecifier, specifierLen));
6755 
6756     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6757     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6758       << FixedCS->toString()
6759       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6760   } else {
6761     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6762                           << CS.toString() << /*conversion specifier*/1,
6763                          getLocationOfByte(CS.getStart()),
6764                          /*IsStringLocation*/true,
6765                          getSpecifierRange(startSpecifier, specifierLen));
6766   }
6767 }
6768 
6769 void CheckFormatHandler::HandlePosition(const char *startPos,
6770                                         unsigned posLen) {
6771   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6772                                getLocationOfByte(startPos),
6773                                /*IsStringLocation*/true,
6774                                getSpecifierRange(startPos, posLen));
6775 }
6776 
6777 void
6778 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6779                                      analyze_format_string::PositionContext p) {
6780   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6781                          << (unsigned) p,
6782                        getLocationOfByte(startPos), /*IsStringLocation*/true,
6783                        getSpecifierRange(startPos, posLen));
6784 }
6785 
6786 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6787                                             unsigned posLen) {
6788   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6789                                getLocationOfByte(startPos),
6790                                /*IsStringLocation*/true,
6791                                getSpecifierRange(startPos, posLen));
6792 }
6793 
6794 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6795   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6796     // The presence of a null character is likely an error.
6797     EmitFormatDiagnostic(
6798       S.PDiag(diag::warn_printf_format_string_contains_null_char),
6799       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6800       getFormatStringRange());
6801   }
6802 }
6803 
6804 // Note that this may return NULL if there was an error parsing or building
6805 // one of the argument expressions.
6806 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6807   return Args[FirstDataArg + i];
6808 }
6809 
6810 void CheckFormatHandler::DoneProcessing() {
6811   // Does the number of data arguments exceed the number of
6812   // format conversions in the format string?
6813   if (!HasVAListArg) {
6814       // Find any arguments that weren't covered.
6815     CoveredArgs.flip();
6816     signed notCoveredArg = CoveredArgs.find_first();
6817     if (notCoveredArg >= 0) {
6818       assert((unsigned)notCoveredArg < NumDataArgs);
6819       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6820     } else {
6821       UncoveredArg.setAllCovered();
6822     }
6823   }
6824 }
6825 
6826 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6827                                    const Expr *ArgExpr) {
6828   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6829          "Invalid state");
6830 
6831   if (!ArgExpr)
6832     return;
6833 
6834   SourceLocation Loc = ArgExpr->getLocStart();
6835 
6836   if (S.getSourceManager().isInSystemMacro(Loc))
6837     return;
6838 
6839   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6840   for (auto E : DiagnosticExprs)
6841     PDiag << E->getSourceRange();
6842 
6843   CheckFormatHandler::EmitFormatDiagnostic(
6844                                   S, IsFunctionCall, DiagnosticExprs[0],
6845                                   PDiag, Loc, /*IsStringLocation*/false,
6846                                   DiagnosticExprs[0]->getSourceRange());
6847 }
6848 
6849 bool
6850 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6851                                                      SourceLocation Loc,
6852                                                      const char *startSpec,
6853                                                      unsigned specifierLen,
6854                                                      const char *csStart,
6855                                                      unsigned csLen) {
6856   bool keepGoing = true;
6857   if (argIndex < NumDataArgs) {
6858     // Consider the argument coverered, even though the specifier doesn't
6859     // make sense.
6860     CoveredArgs.set(argIndex);
6861   }
6862   else {
6863     // If argIndex exceeds the number of data arguments we
6864     // don't issue a warning because that is just a cascade of warnings (and
6865     // they may have intended '%%' anyway). We don't want to continue processing
6866     // the format string after this point, however, as we will like just get
6867     // gibberish when trying to match arguments.
6868     keepGoing = false;
6869   }
6870 
6871   StringRef Specifier(csStart, csLen);
6872 
6873   // If the specifier in non-printable, it could be the first byte of a UTF-8
6874   // sequence. In that case, print the UTF-8 code point. If not, print the byte
6875   // hex value.
6876   std::string CodePointStr;
6877   if (!llvm::sys::locale::isPrint(*csStart)) {
6878     llvm::UTF32 CodePoint;
6879     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6880     const llvm::UTF8 *E =
6881         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6882     llvm::ConversionResult Result =
6883         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6884 
6885     if (Result != llvm::conversionOK) {
6886       unsigned char FirstChar = *csStart;
6887       CodePoint = (llvm::UTF32)FirstChar;
6888     }
6889 
6890     llvm::raw_string_ostream OS(CodePointStr);
6891     if (CodePoint < 256)
6892       OS << "\\x" << llvm::format("%02x", CodePoint);
6893     else if (CodePoint <= 0xFFFF)
6894       OS << "\\u" << llvm::format("%04x", CodePoint);
6895     else
6896       OS << "\\U" << llvm::format("%08x", CodePoint);
6897     OS.flush();
6898     Specifier = CodePointStr;
6899   }
6900 
6901   EmitFormatDiagnostic(
6902       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6903       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6904 
6905   return keepGoing;
6906 }
6907 
6908 void
6909 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6910                                                       const char *startSpec,
6911                                                       unsigned specifierLen) {
6912   EmitFormatDiagnostic(
6913     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6914     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6915 }
6916 
6917 bool
6918 CheckFormatHandler::CheckNumArgs(
6919   const analyze_format_string::FormatSpecifier &FS,
6920   const analyze_format_string::ConversionSpecifier &CS,
6921   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6922 
6923   if (argIndex >= NumDataArgs) {
6924     PartialDiagnostic PDiag = FS.usesPositionalArg()
6925       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6926            << (argIndex+1) << NumDataArgs)
6927       : S.PDiag(diag::warn_printf_insufficient_data_args);
6928     EmitFormatDiagnostic(
6929       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6930       getSpecifierRange(startSpecifier, specifierLen));
6931 
6932     // Since more arguments than conversion tokens are given, by extension
6933     // all arguments are covered, so mark this as so.
6934     UncoveredArg.setAllCovered();
6935     return false;
6936   }
6937   return true;
6938 }
6939 
6940 template<typename Range>
6941 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6942                                               SourceLocation Loc,
6943                                               bool IsStringLocation,
6944                                               Range StringRange,
6945                                               ArrayRef<FixItHint> FixIt) {
6946   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
6947                        Loc, IsStringLocation, StringRange, FixIt);
6948 }
6949 
6950 /// If the format string is not within the function call, emit a note
6951 /// so that the function call and string are in diagnostic messages.
6952 ///
6953 /// \param InFunctionCall if true, the format string is within the function
6954 /// call and only one diagnostic message will be produced.  Otherwise, an
6955 /// extra note will be emitted pointing to location of the format string.
6956 ///
6957 /// \param ArgumentExpr the expression that is passed as the format string
6958 /// argument in the function call.  Used for getting locations when two
6959 /// diagnostics are emitted.
6960 ///
6961 /// \param PDiag the callee should already have provided any strings for the
6962 /// diagnostic message.  This function only adds locations and fixits
6963 /// to diagnostics.
6964 ///
6965 /// \param Loc primary location for diagnostic.  If two diagnostics are
6966 /// required, one will be at Loc and a new SourceLocation will be created for
6967 /// the other one.
6968 ///
6969 /// \param IsStringLocation if true, Loc points to the format string should be
6970 /// used for the note.  Otherwise, Loc points to the argument list and will
6971 /// be used with PDiag.
6972 ///
6973 /// \param StringRange some or all of the string to highlight.  This is
6974 /// templated so it can accept either a CharSourceRange or a SourceRange.
6975 ///
6976 /// \param FixIt optional fix it hint for the format string.
6977 template <typename Range>
6978 void CheckFormatHandler::EmitFormatDiagnostic(
6979     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6980     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6981     Range StringRange, ArrayRef<FixItHint> FixIt) {
6982   if (InFunctionCall) {
6983     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6984     D << StringRange;
6985     D << FixIt;
6986   } else {
6987     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6988       << ArgumentExpr->getSourceRange();
6989 
6990     const Sema::SemaDiagnosticBuilder &Note =
6991       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6992              diag::note_format_string_defined);
6993 
6994     Note << StringRange;
6995     Note << FixIt;
6996   }
6997 }
6998 
6999 //===--- CHECK: Printf format string checking ------------------------------===//
7000 
7001 namespace {
7002 
7003 class CheckPrintfHandler : public CheckFormatHandler {
7004 public:
7005   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7006                      const Expr *origFormatExpr,
7007                      const Sema::FormatStringType type, unsigned firstDataArg,
7008                      unsigned numDataArgs, bool isObjC, const char *beg,
7009                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7010                      unsigned formatIdx, bool inFunctionCall,
7011                      Sema::VariadicCallType CallType,
7012                      llvm::SmallBitVector &CheckedVarArgs,
7013                      UncoveredArgHandler &UncoveredArg)
7014       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7015                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7016                            inFunctionCall, CallType, CheckedVarArgs,
7017                            UncoveredArg) {}
7018 
7019   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7020 
7021   /// Returns true if '%@' specifiers are allowed in the format string.
7022   bool allowsObjCArg() const {
7023     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7024            FSType == Sema::FST_OSTrace;
7025   }
7026 
7027   bool HandleInvalidPrintfConversionSpecifier(
7028                                       const analyze_printf::PrintfSpecifier &FS,
7029                                       const char *startSpecifier,
7030                                       unsigned specifierLen) override;
7031 
7032   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7033                              const char *startSpecifier,
7034                              unsigned specifierLen) override;
7035   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7036                        const char *StartSpecifier,
7037                        unsigned SpecifierLen,
7038                        const Expr *E);
7039 
7040   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7041                     const char *startSpecifier, unsigned specifierLen);
7042   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7043                            const analyze_printf::OptionalAmount &Amt,
7044                            unsigned type,
7045                            const char *startSpecifier, unsigned specifierLen);
7046   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7047                   const analyze_printf::OptionalFlag &flag,
7048                   const char *startSpecifier, unsigned specifierLen);
7049   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7050                          const analyze_printf::OptionalFlag &ignoredFlag,
7051                          const analyze_printf::OptionalFlag &flag,
7052                          const char *startSpecifier, unsigned specifierLen);
7053   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7054                            const Expr *E);
7055 
7056   void HandleEmptyObjCModifierFlag(const char *startFlag,
7057                                    unsigned flagLen) override;
7058 
7059   void HandleInvalidObjCModifierFlag(const char *startFlag,
7060                                             unsigned flagLen) override;
7061 
7062   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7063                                            const char *flagsEnd,
7064                                            const char *conversionPosition)
7065                                              override;
7066 };
7067 
7068 } // namespace
7069 
7070 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7071                                       const analyze_printf::PrintfSpecifier &FS,
7072                                       const char *startSpecifier,
7073                                       unsigned specifierLen) {
7074   const analyze_printf::PrintfConversionSpecifier &CS =
7075     FS.getConversionSpecifier();
7076 
7077   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7078                                           getLocationOfByte(CS.getStart()),
7079                                           startSpecifier, specifierLen,
7080                                           CS.getStart(), CS.getLength());
7081 }
7082 
7083 bool CheckPrintfHandler::HandleAmount(
7084                                const analyze_format_string::OptionalAmount &Amt,
7085                                unsigned k, const char *startSpecifier,
7086                                unsigned specifierLen) {
7087   if (Amt.hasDataArgument()) {
7088     if (!HasVAListArg) {
7089       unsigned argIndex = Amt.getArgIndex();
7090       if (argIndex >= NumDataArgs) {
7091         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7092                                << k,
7093                              getLocationOfByte(Amt.getStart()),
7094                              /*IsStringLocation*/true,
7095                              getSpecifierRange(startSpecifier, specifierLen));
7096         // Don't do any more checking.  We will just emit
7097         // spurious errors.
7098         return false;
7099       }
7100 
7101       // Type check the data argument.  It should be an 'int'.
7102       // Although not in conformance with C99, we also allow the argument to be
7103       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7104       // doesn't emit a warning for that case.
7105       CoveredArgs.set(argIndex);
7106       const Expr *Arg = getDataArg(argIndex);
7107       if (!Arg)
7108         return false;
7109 
7110       QualType T = Arg->getType();
7111 
7112       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7113       assert(AT.isValid());
7114 
7115       if (!AT.matchesType(S.Context, T)) {
7116         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7117                                << k << AT.getRepresentativeTypeName(S.Context)
7118                                << T << Arg->getSourceRange(),
7119                              getLocationOfByte(Amt.getStart()),
7120                              /*IsStringLocation*/true,
7121                              getSpecifierRange(startSpecifier, specifierLen));
7122         // Don't do any more checking.  We will just emit
7123         // spurious errors.
7124         return false;
7125       }
7126     }
7127   }
7128   return true;
7129 }
7130 
7131 void CheckPrintfHandler::HandleInvalidAmount(
7132                                       const analyze_printf::PrintfSpecifier &FS,
7133                                       const analyze_printf::OptionalAmount &Amt,
7134                                       unsigned type,
7135                                       const char *startSpecifier,
7136                                       unsigned specifierLen) {
7137   const analyze_printf::PrintfConversionSpecifier &CS =
7138     FS.getConversionSpecifier();
7139 
7140   FixItHint fixit =
7141     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7142       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7143                                  Amt.getConstantLength()))
7144       : FixItHint();
7145 
7146   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7147                          << type << CS.toString(),
7148                        getLocationOfByte(Amt.getStart()),
7149                        /*IsStringLocation*/true,
7150                        getSpecifierRange(startSpecifier, specifierLen),
7151                        fixit);
7152 }
7153 
7154 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7155                                     const analyze_printf::OptionalFlag &flag,
7156                                     const char *startSpecifier,
7157                                     unsigned specifierLen) {
7158   // Warn about pointless flag with a fixit removal.
7159   const analyze_printf::PrintfConversionSpecifier &CS =
7160     FS.getConversionSpecifier();
7161   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7162                          << flag.toString() << CS.toString(),
7163                        getLocationOfByte(flag.getPosition()),
7164                        /*IsStringLocation*/true,
7165                        getSpecifierRange(startSpecifier, specifierLen),
7166                        FixItHint::CreateRemoval(
7167                          getSpecifierRange(flag.getPosition(), 1)));
7168 }
7169 
7170 void CheckPrintfHandler::HandleIgnoredFlag(
7171                                 const analyze_printf::PrintfSpecifier &FS,
7172                                 const analyze_printf::OptionalFlag &ignoredFlag,
7173                                 const analyze_printf::OptionalFlag &flag,
7174                                 const char *startSpecifier,
7175                                 unsigned specifierLen) {
7176   // Warn about ignored flag with a fixit removal.
7177   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7178                          << ignoredFlag.toString() << flag.toString(),
7179                        getLocationOfByte(ignoredFlag.getPosition()),
7180                        /*IsStringLocation*/true,
7181                        getSpecifierRange(startSpecifier, specifierLen),
7182                        FixItHint::CreateRemoval(
7183                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7184 }
7185 
7186 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7187                                                      unsigned flagLen) {
7188   // Warn about an empty flag.
7189   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7190                        getLocationOfByte(startFlag),
7191                        /*IsStringLocation*/true,
7192                        getSpecifierRange(startFlag, flagLen));
7193 }
7194 
7195 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7196                                                        unsigned flagLen) {
7197   // Warn about an invalid flag.
7198   auto Range = getSpecifierRange(startFlag, flagLen);
7199   StringRef flag(startFlag, flagLen);
7200   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7201                       getLocationOfByte(startFlag),
7202                       /*IsStringLocation*/true,
7203                       Range, FixItHint::CreateRemoval(Range));
7204 }
7205 
7206 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7207     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7208     // Warn about using '[...]' without a '@' conversion.
7209     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7210     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7211     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7212                          getLocationOfByte(conversionPosition),
7213                          /*IsStringLocation*/true,
7214                          Range, FixItHint::CreateRemoval(Range));
7215 }
7216 
7217 // Determines if the specified is a C++ class or struct containing
7218 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7219 // "c_str()").
7220 template<typename MemberKind>
7221 static llvm::SmallPtrSet<MemberKind*, 1>
7222 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7223   const RecordType *RT = Ty->getAs<RecordType>();
7224   llvm::SmallPtrSet<MemberKind*, 1> Results;
7225 
7226   if (!RT)
7227     return Results;
7228   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7229   if (!RD || !RD->getDefinition())
7230     return Results;
7231 
7232   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7233                  Sema::LookupMemberName);
7234   R.suppressDiagnostics();
7235 
7236   // We just need to include all members of the right kind turned up by the
7237   // filter, at this point.
7238   if (S.LookupQualifiedName(R, RT->getDecl()))
7239     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7240       NamedDecl *decl = (*I)->getUnderlyingDecl();
7241       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7242         Results.insert(FK);
7243     }
7244   return Results;
7245 }
7246 
7247 /// Check if we could call '.c_str()' on an object.
7248 ///
7249 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7250 /// allow the call, or if it would be ambiguous).
7251 bool Sema::hasCStrMethod(const Expr *E) {
7252   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7253 
7254   MethodSet Results =
7255       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7256   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7257        MI != ME; ++MI)
7258     if ((*MI)->getMinRequiredArguments() == 0)
7259       return true;
7260   return false;
7261 }
7262 
7263 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7264 // better diagnostic if so. AT is assumed to be valid.
7265 // Returns true when a c_str() conversion method is found.
7266 bool CheckPrintfHandler::checkForCStrMembers(
7267     const analyze_printf::ArgType &AT, const Expr *E) {
7268   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7269 
7270   MethodSet Results =
7271       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7272 
7273   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7274        MI != ME; ++MI) {
7275     const CXXMethodDecl *Method = *MI;
7276     if (Method->getMinRequiredArguments() == 0 &&
7277         AT.matchesType(S.Context, Method->getReturnType())) {
7278       // FIXME: Suggest parens if the expression needs them.
7279       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
7280       S.Diag(E->getLocStart(), diag::note_printf_c_str)
7281           << "c_str()"
7282           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7283       return true;
7284     }
7285   }
7286 
7287   return false;
7288 }
7289 
7290 bool
7291 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7292                                             &FS,
7293                                           const char *startSpecifier,
7294                                           unsigned specifierLen) {
7295   using namespace analyze_format_string;
7296   using namespace analyze_printf;
7297 
7298   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7299 
7300   if (FS.consumesDataArgument()) {
7301     if (atFirstArg) {
7302         atFirstArg = false;
7303         usesPositionalArgs = FS.usesPositionalArg();
7304     }
7305     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7306       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7307                                         startSpecifier, specifierLen);
7308       return false;
7309     }
7310   }
7311 
7312   // First check if the field width, precision, and conversion specifier
7313   // have matching data arguments.
7314   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7315                     startSpecifier, specifierLen)) {
7316     return false;
7317   }
7318 
7319   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7320                     startSpecifier, specifierLen)) {
7321     return false;
7322   }
7323 
7324   if (!CS.consumesDataArgument()) {
7325     // FIXME: Technically specifying a precision or field width here
7326     // makes no sense.  Worth issuing a warning at some point.
7327     return true;
7328   }
7329 
7330   // Consume the argument.
7331   unsigned argIndex = FS.getArgIndex();
7332   if (argIndex < NumDataArgs) {
7333     // The check to see if the argIndex is valid will come later.
7334     // We set the bit here because we may exit early from this
7335     // function if we encounter some other error.
7336     CoveredArgs.set(argIndex);
7337   }
7338 
7339   // FreeBSD kernel extensions.
7340   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7341       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7342     // We need at least two arguments.
7343     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7344       return false;
7345 
7346     // Claim the second argument.
7347     CoveredArgs.set(argIndex + 1);
7348 
7349     // Type check the first argument (int for %b, pointer for %D)
7350     const Expr *Ex = getDataArg(argIndex);
7351     const analyze_printf::ArgType &AT =
7352       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7353         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7354     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7355       EmitFormatDiagnostic(
7356         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7357         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7358         << false << Ex->getSourceRange(),
7359         Ex->getLocStart(), /*IsStringLocation*/false,
7360         getSpecifierRange(startSpecifier, specifierLen));
7361 
7362     // Type check the second argument (char * for both %b and %D)
7363     Ex = getDataArg(argIndex + 1);
7364     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7365     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7366       EmitFormatDiagnostic(
7367         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7368         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7369         << false << Ex->getSourceRange(),
7370         Ex->getLocStart(), /*IsStringLocation*/false,
7371         getSpecifierRange(startSpecifier, specifierLen));
7372 
7373      return true;
7374   }
7375 
7376   // Check for using an Objective-C specific conversion specifier
7377   // in a non-ObjC literal.
7378   if (!allowsObjCArg() && CS.isObjCArg()) {
7379     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7380                                                   specifierLen);
7381   }
7382 
7383   // %P can only be used with os_log.
7384   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7385     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7386                                                   specifierLen);
7387   }
7388 
7389   // %n is not allowed with os_log.
7390   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7391     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7392                          getLocationOfByte(CS.getStart()),
7393                          /*IsStringLocation*/ false,
7394                          getSpecifierRange(startSpecifier, specifierLen));
7395 
7396     return true;
7397   }
7398 
7399   // Only scalars are allowed for os_trace.
7400   if (FSType == Sema::FST_OSTrace &&
7401       (CS.getKind() == ConversionSpecifier::PArg ||
7402        CS.getKind() == ConversionSpecifier::sArg ||
7403        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7404     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7405                                                   specifierLen);
7406   }
7407 
7408   // Check for use of public/private annotation outside of os_log().
7409   if (FSType != Sema::FST_OSLog) {
7410     if (FS.isPublic().isSet()) {
7411       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7412                                << "public",
7413                            getLocationOfByte(FS.isPublic().getPosition()),
7414                            /*IsStringLocation*/ false,
7415                            getSpecifierRange(startSpecifier, specifierLen));
7416     }
7417     if (FS.isPrivate().isSet()) {
7418       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7419                                << "private",
7420                            getLocationOfByte(FS.isPrivate().getPosition()),
7421                            /*IsStringLocation*/ false,
7422                            getSpecifierRange(startSpecifier, specifierLen));
7423     }
7424   }
7425 
7426   // Check for invalid use of field width
7427   if (!FS.hasValidFieldWidth()) {
7428     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7429         startSpecifier, specifierLen);
7430   }
7431 
7432   // Check for invalid use of precision
7433   if (!FS.hasValidPrecision()) {
7434     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7435         startSpecifier, specifierLen);
7436   }
7437 
7438   // Precision is mandatory for %P specifier.
7439   if (CS.getKind() == ConversionSpecifier::PArg &&
7440       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7441     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7442                          getLocationOfByte(startSpecifier),
7443                          /*IsStringLocation*/ false,
7444                          getSpecifierRange(startSpecifier, specifierLen));
7445   }
7446 
7447   // Check each flag does not conflict with any other component.
7448   if (!FS.hasValidThousandsGroupingPrefix())
7449     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7450   if (!FS.hasValidLeadingZeros())
7451     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7452   if (!FS.hasValidPlusPrefix())
7453     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7454   if (!FS.hasValidSpacePrefix())
7455     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7456   if (!FS.hasValidAlternativeForm())
7457     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7458   if (!FS.hasValidLeftJustified())
7459     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7460 
7461   // Check that flags are not ignored by another flag
7462   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7463     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7464         startSpecifier, specifierLen);
7465   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7466     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7467             startSpecifier, specifierLen);
7468 
7469   // Check the length modifier is valid with the given conversion specifier.
7470   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
7471     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7472                                 diag::warn_format_nonsensical_length);
7473   else if (!FS.hasStandardLengthModifier())
7474     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7475   else if (!FS.hasStandardLengthConversionCombination())
7476     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7477                                 diag::warn_format_non_standard_conversion_spec);
7478 
7479   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7480     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7481 
7482   // The remaining checks depend on the data arguments.
7483   if (HasVAListArg)
7484     return true;
7485 
7486   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7487     return false;
7488 
7489   const Expr *Arg = getDataArg(argIndex);
7490   if (!Arg)
7491     return true;
7492 
7493   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7494 }
7495 
7496 static bool requiresParensToAddCast(const Expr *E) {
7497   // FIXME: We should have a general way to reason about operator
7498   // precedence and whether parens are actually needed here.
7499   // Take care of a few common cases where they aren't.
7500   const Expr *Inside = E->IgnoreImpCasts();
7501   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7502     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7503 
7504   switch (Inside->getStmtClass()) {
7505   case Stmt::ArraySubscriptExprClass:
7506   case Stmt::CallExprClass:
7507   case Stmt::CharacterLiteralClass:
7508   case Stmt::CXXBoolLiteralExprClass:
7509   case Stmt::DeclRefExprClass:
7510   case Stmt::FloatingLiteralClass:
7511   case Stmt::IntegerLiteralClass:
7512   case Stmt::MemberExprClass:
7513   case Stmt::ObjCArrayLiteralClass:
7514   case Stmt::ObjCBoolLiteralExprClass:
7515   case Stmt::ObjCBoxedExprClass:
7516   case Stmt::ObjCDictionaryLiteralClass:
7517   case Stmt::ObjCEncodeExprClass:
7518   case Stmt::ObjCIvarRefExprClass:
7519   case Stmt::ObjCMessageExprClass:
7520   case Stmt::ObjCPropertyRefExprClass:
7521   case Stmt::ObjCStringLiteralClass:
7522   case Stmt::ObjCSubscriptRefExprClass:
7523   case Stmt::ParenExprClass:
7524   case Stmt::StringLiteralClass:
7525   case Stmt::UnaryOperatorClass:
7526     return false;
7527   default:
7528     return true;
7529   }
7530 }
7531 
7532 static std::pair<QualType, StringRef>
7533 shouldNotPrintDirectly(const ASTContext &Context,
7534                        QualType IntendedTy,
7535                        const Expr *E) {
7536   // Use a 'while' to peel off layers of typedefs.
7537   QualType TyTy = IntendedTy;
7538   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7539     StringRef Name = UserTy->getDecl()->getName();
7540     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7541       .Case("CFIndex", Context.getNSIntegerType())
7542       .Case("NSInteger", Context.getNSIntegerType())
7543       .Case("NSUInteger", Context.getNSUIntegerType())
7544       .Case("SInt32", Context.IntTy)
7545       .Case("UInt32", Context.UnsignedIntTy)
7546       .Default(QualType());
7547 
7548     if (!CastTy.isNull())
7549       return std::make_pair(CastTy, Name);
7550 
7551     TyTy = UserTy->desugar();
7552   }
7553 
7554   // Strip parens if necessary.
7555   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7556     return shouldNotPrintDirectly(Context,
7557                                   PE->getSubExpr()->getType(),
7558                                   PE->getSubExpr());
7559 
7560   // If this is a conditional expression, then its result type is constructed
7561   // via usual arithmetic conversions and thus there might be no necessary
7562   // typedef sugar there.  Recurse to operands to check for NSInteger &
7563   // Co. usage condition.
7564   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7565     QualType TrueTy, FalseTy;
7566     StringRef TrueName, FalseName;
7567 
7568     std::tie(TrueTy, TrueName) =
7569       shouldNotPrintDirectly(Context,
7570                              CO->getTrueExpr()->getType(),
7571                              CO->getTrueExpr());
7572     std::tie(FalseTy, FalseName) =
7573       shouldNotPrintDirectly(Context,
7574                              CO->getFalseExpr()->getType(),
7575                              CO->getFalseExpr());
7576 
7577     if (TrueTy == FalseTy)
7578       return std::make_pair(TrueTy, TrueName);
7579     else if (TrueTy.isNull())
7580       return std::make_pair(FalseTy, FalseName);
7581     else if (FalseTy.isNull())
7582       return std::make_pair(TrueTy, TrueName);
7583   }
7584 
7585   return std::make_pair(QualType(), StringRef());
7586 }
7587 
7588 bool
7589 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7590                                     const char *StartSpecifier,
7591                                     unsigned SpecifierLen,
7592                                     const Expr *E) {
7593   using namespace analyze_format_string;
7594   using namespace analyze_printf;
7595 
7596   // Now type check the data expression that matches the
7597   // format specifier.
7598   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7599   if (!AT.isValid())
7600     return true;
7601 
7602   QualType ExprTy = E->getType();
7603   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7604     ExprTy = TET->getUnderlyingExpr()->getType();
7605   }
7606 
7607   const analyze_printf::ArgType::MatchKind Match =
7608       AT.matchesType(S.Context, ExprTy);
7609   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7610   if (Match == analyze_printf::ArgType::Match)
7611     return true;
7612 
7613   // Look through argument promotions for our error message's reported type.
7614   // This includes the integral and floating promotions, but excludes array
7615   // and function pointer decay; seeing that an argument intended to be a
7616   // string has type 'char [6]' is probably more confusing than 'char *'.
7617   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7618     if (ICE->getCastKind() == CK_IntegralCast ||
7619         ICE->getCastKind() == CK_FloatingCast) {
7620       E = ICE->getSubExpr();
7621       ExprTy = E->getType();
7622 
7623       // Check if we didn't match because of an implicit cast from a 'char'
7624       // or 'short' to an 'int'.  This is done because printf is a varargs
7625       // function.
7626       if (ICE->getType() == S.Context.IntTy ||
7627           ICE->getType() == S.Context.UnsignedIntTy) {
7628         // All further checking is done on the subexpression.
7629         if (AT.matchesType(S.Context, ExprTy))
7630           return true;
7631       }
7632     }
7633   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7634     // Special case for 'a', which has type 'int' in C.
7635     // Note, however, that we do /not/ want to treat multibyte constants like
7636     // 'MooV' as characters! This form is deprecated but still exists.
7637     if (ExprTy == S.Context.IntTy)
7638       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7639         ExprTy = S.Context.CharTy;
7640   }
7641 
7642   // Look through enums to their underlying type.
7643   bool IsEnum = false;
7644   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7645     ExprTy = EnumTy->getDecl()->getIntegerType();
7646     IsEnum = true;
7647   }
7648 
7649   // %C in an Objective-C context prints a unichar, not a wchar_t.
7650   // If the argument is an integer of some kind, believe the %C and suggest
7651   // a cast instead of changing the conversion specifier.
7652   QualType IntendedTy = ExprTy;
7653   if (isObjCContext() &&
7654       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7655     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7656         !ExprTy->isCharType()) {
7657       // 'unichar' is defined as a typedef of unsigned short, but we should
7658       // prefer using the typedef if it is visible.
7659       IntendedTy = S.Context.UnsignedShortTy;
7660 
7661       // While we are here, check if the value is an IntegerLiteral that happens
7662       // to be within the valid range.
7663       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7664         const llvm::APInt &V = IL->getValue();
7665         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7666           return true;
7667       }
7668 
7669       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
7670                           Sema::LookupOrdinaryName);
7671       if (S.LookupName(Result, S.getCurScope())) {
7672         NamedDecl *ND = Result.getFoundDecl();
7673         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7674           if (TD->getUnderlyingType() == IntendedTy)
7675             IntendedTy = S.Context.getTypedefType(TD);
7676       }
7677     }
7678   }
7679 
7680   // Special-case some of Darwin's platform-independence types by suggesting
7681   // casts to primitive types that are known to be large enough.
7682   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7683   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7684     QualType CastTy;
7685     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7686     if (!CastTy.isNull()) {
7687       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7688       // (long in ASTContext). Only complain to pedants.
7689       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7690           (AT.isSizeT() || AT.isPtrdiffT()) &&
7691           AT.matchesType(S.Context, CastTy))
7692         Pedantic = true;
7693       IntendedTy = CastTy;
7694       ShouldNotPrintDirectly = true;
7695     }
7696   }
7697 
7698   // We may be able to offer a FixItHint if it is a supported type.
7699   PrintfSpecifier fixedFS = FS;
7700   bool Success =
7701       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7702 
7703   if (Success) {
7704     // Get the fix string from the fixed format specifier
7705     SmallString<16> buf;
7706     llvm::raw_svector_ostream os(buf);
7707     fixedFS.toString(os);
7708 
7709     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7710 
7711     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7712       unsigned Diag =
7713           Pedantic
7714               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7715               : diag::warn_format_conversion_argument_type_mismatch;
7716       // In this case, the specifier is wrong and should be changed to match
7717       // the argument.
7718       EmitFormatDiagnostic(S.PDiag(Diag)
7719                                << AT.getRepresentativeTypeName(S.Context)
7720                                << IntendedTy << IsEnum << E->getSourceRange(),
7721                            E->getLocStart(),
7722                            /*IsStringLocation*/ false, SpecRange,
7723                            FixItHint::CreateReplacement(SpecRange, os.str()));
7724     } else {
7725       // The canonical type for formatting this value is different from the
7726       // actual type of the expression. (This occurs, for example, with Darwin's
7727       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7728       // should be printed as 'long' for 64-bit compatibility.)
7729       // Rather than emitting a normal format/argument mismatch, we want to
7730       // add a cast to the recommended type (and correct the format string
7731       // if necessary).
7732       SmallString<16> CastBuf;
7733       llvm::raw_svector_ostream CastFix(CastBuf);
7734       CastFix << "(";
7735       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7736       CastFix << ")";
7737 
7738       SmallVector<FixItHint,4> Hints;
7739       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
7740         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7741 
7742       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7743         // If there's already a cast present, just replace it.
7744         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7745         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7746 
7747       } else if (!requiresParensToAddCast(E)) {
7748         // If the expression has high enough precedence,
7749         // just write the C-style cast.
7750         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
7751                                                    CastFix.str()));
7752       } else {
7753         // Otherwise, add parens around the expression as well as the cast.
7754         CastFix << "(";
7755         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
7756                                                    CastFix.str()));
7757 
7758         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
7759         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7760       }
7761 
7762       if (ShouldNotPrintDirectly) {
7763         // The expression has a type that should not be printed directly.
7764         // We extract the name from the typedef because we don't want to show
7765         // the underlying type in the diagnostic.
7766         StringRef Name;
7767         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7768           Name = TypedefTy->getDecl()->getName();
7769         else
7770           Name = CastTyName;
7771         unsigned Diag = Pedantic
7772                             ? diag::warn_format_argument_needs_cast_pedantic
7773                             : diag::warn_format_argument_needs_cast;
7774         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7775                                            << E->getSourceRange(),
7776                              E->getLocStart(), /*IsStringLocation=*/false,
7777                              SpecRange, Hints);
7778       } else {
7779         // In this case, the expression could be printed using a different
7780         // specifier, but we've decided that the specifier is probably correct
7781         // and we should cast instead. Just use the normal warning message.
7782         EmitFormatDiagnostic(
7783           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7784             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7785             << E->getSourceRange(),
7786           E->getLocStart(), /*IsStringLocation*/false,
7787           SpecRange, Hints);
7788       }
7789     }
7790   } else {
7791     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7792                                                    SpecifierLen);
7793     // Since the warning for passing non-POD types to variadic functions
7794     // was deferred until now, we emit a warning for non-POD
7795     // arguments here.
7796     switch (S.isValidVarArgType(ExprTy)) {
7797     case Sema::VAK_Valid:
7798     case Sema::VAK_ValidInCXX11: {
7799       unsigned Diag =
7800           Pedantic
7801               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7802               : diag::warn_format_conversion_argument_type_mismatch;
7803 
7804       EmitFormatDiagnostic(
7805           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7806                         << IsEnum << CSR << E->getSourceRange(),
7807           E->getLocStart(), /*IsStringLocation*/ false, CSR);
7808       break;
7809     }
7810     case Sema::VAK_Undefined:
7811     case Sema::VAK_MSVCUndefined:
7812       EmitFormatDiagnostic(
7813         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7814           << S.getLangOpts().CPlusPlus11
7815           << ExprTy
7816           << CallType
7817           << AT.getRepresentativeTypeName(S.Context)
7818           << CSR
7819           << E->getSourceRange(),
7820         E->getLocStart(), /*IsStringLocation*/false, CSR);
7821       checkForCStrMembers(AT, E);
7822       break;
7823 
7824     case Sema::VAK_Invalid:
7825       if (ExprTy->isObjCObjectType())
7826         EmitFormatDiagnostic(
7827           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7828             << S.getLangOpts().CPlusPlus11
7829             << ExprTy
7830             << CallType
7831             << AT.getRepresentativeTypeName(S.Context)
7832             << CSR
7833             << E->getSourceRange(),
7834           E->getLocStart(), /*IsStringLocation*/false, CSR);
7835       else
7836         // FIXME: If this is an initializer list, suggest removing the braces
7837         // or inserting a cast to the target type.
7838         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
7839           << isa<InitListExpr>(E) << ExprTy << CallType
7840           << AT.getRepresentativeTypeName(S.Context)
7841           << E->getSourceRange();
7842       break;
7843     }
7844 
7845     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7846            "format string specifier index out of range");
7847     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
7848   }
7849 
7850   return true;
7851 }
7852 
7853 //===--- CHECK: Scanf format string checking ------------------------------===//
7854 
7855 namespace {
7856 
7857 class CheckScanfHandler : public CheckFormatHandler {
7858 public:
7859   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
7860                     const Expr *origFormatExpr, Sema::FormatStringType type,
7861                     unsigned firstDataArg, unsigned numDataArgs,
7862                     const char *beg, bool hasVAListArg,
7863                     ArrayRef<const Expr *> Args, unsigned formatIdx,
7864                     bool inFunctionCall, Sema::VariadicCallType CallType,
7865                     llvm::SmallBitVector &CheckedVarArgs,
7866                     UncoveredArgHandler &UncoveredArg)
7867       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7868                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7869                            inFunctionCall, CallType, CheckedVarArgs,
7870                            UncoveredArg) {}
7871 
7872   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7873                             const char *startSpecifier,
7874                             unsigned specifierLen) override;
7875 
7876   bool HandleInvalidScanfConversionSpecifier(
7877           const analyze_scanf::ScanfSpecifier &FS,
7878           const char *startSpecifier,
7879           unsigned specifierLen) override;
7880 
7881   void HandleIncompleteScanList(const char *start, const char *end) override;
7882 };
7883 
7884 } // namespace
7885 
7886 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7887                                                  const char *end) {
7888   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7889                        getLocationOfByte(end), /*IsStringLocation*/true,
7890                        getSpecifierRange(start, end - start));
7891 }
7892 
7893 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7894                                         const analyze_scanf::ScanfSpecifier &FS,
7895                                         const char *startSpecifier,
7896                                         unsigned specifierLen) {
7897   const analyze_scanf::ScanfConversionSpecifier &CS =
7898     FS.getConversionSpecifier();
7899 
7900   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7901                                           getLocationOfByte(CS.getStart()),
7902                                           startSpecifier, specifierLen,
7903                                           CS.getStart(), CS.getLength());
7904 }
7905 
7906 bool CheckScanfHandler::HandleScanfSpecifier(
7907                                        const analyze_scanf::ScanfSpecifier &FS,
7908                                        const char *startSpecifier,
7909                                        unsigned specifierLen) {
7910   using namespace analyze_scanf;
7911   using namespace analyze_format_string;
7912 
7913   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
7914 
7915   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
7916   // be used to decide if we are using positional arguments consistently.
7917   if (FS.consumesDataArgument()) {
7918     if (atFirstArg) {
7919       atFirstArg = false;
7920       usesPositionalArgs = FS.usesPositionalArg();
7921     }
7922     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7923       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7924                                         startSpecifier, specifierLen);
7925       return false;
7926     }
7927   }
7928 
7929   // Check if the field with is non-zero.
7930   const OptionalAmount &Amt = FS.getFieldWidth();
7931   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7932     if (Amt.getConstantAmount() == 0) {
7933       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7934                                                    Amt.getConstantLength());
7935       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7936                            getLocationOfByte(Amt.getStart()),
7937                            /*IsStringLocation*/true, R,
7938                            FixItHint::CreateRemoval(R));
7939     }
7940   }
7941 
7942   if (!FS.consumesDataArgument()) {
7943     // FIXME: Technically specifying a precision or field width here
7944     // makes no sense.  Worth issuing a warning at some point.
7945     return true;
7946   }
7947 
7948   // Consume the argument.
7949   unsigned argIndex = FS.getArgIndex();
7950   if (argIndex < NumDataArgs) {
7951       // The check to see if the argIndex is valid will come later.
7952       // We set the bit here because we may exit early from this
7953       // function if we encounter some other error.
7954     CoveredArgs.set(argIndex);
7955   }
7956 
7957   // Check the length modifier is valid with the given conversion specifier.
7958   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
7959     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7960                                 diag::warn_format_nonsensical_length);
7961   else if (!FS.hasStandardLengthModifier())
7962     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7963   else if (!FS.hasStandardLengthConversionCombination())
7964     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7965                                 diag::warn_format_non_standard_conversion_spec);
7966 
7967   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7968     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7969 
7970   // The remaining checks depend on the data arguments.
7971   if (HasVAListArg)
7972     return true;
7973 
7974   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7975     return false;
7976 
7977   // Check that the argument type matches the format specifier.
7978   const Expr *Ex = getDataArg(argIndex);
7979   if (!Ex)
7980     return true;
7981 
7982   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
7983 
7984   if (!AT.isValid()) {
7985     return true;
7986   }
7987 
7988   analyze_format_string::ArgType::MatchKind Match =
7989       AT.matchesType(S.Context, Ex->getType());
7990   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
7991   if (Match == analyze_format_string::ArgType::Match)
7992     return true;
7993 
7994   ScanfSpecifier fixedFS = FS;
7995   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7996                                  S.getLangOpts(), S.Context);
7997 
7998   unsigned Diag =
7999       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8000                : diag::warn_format_conversion_argument_type_mismatch;
8001 
8002   if (Success) {
8003     // Get the fix string from the fixed format specifier.
8004     SmallString<128> buf;
8005     llvm::raw_svector_ostream os(buf);
8006     fixedFS.toString(os);
8007 
8008     EmitFormatDiagnostic(
8009         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8010                       << Ex->getType() << false << Ex->getSourceRange(),
8011         Ex->getLocStart(),
8012         /*IsStringLocation*/ false,
8013         getSpecifierRange(startSpecifier, specifierLen),
8014         FixItHint::CreateReplacement(
8015             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8016   } else {
8017     EmitFormatDiagnostic(S.PDiag(Diag)
8018                              << AT.getRepresentativeTypeName(S.Context)
8019                              << Ex->getType() << false << Ex->getSourceRange(),
8020                          Ex->getLocStart(),
8021                          /*IsStringLocation*/ false,
8022                          getSpecifierRange(startSpecifier, specifierLen));
8023   }
8024 
8025   return true;
8026 }
8027 
8028 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8029                               const Expr *OrigFormatExpr,
8030                               ArrayRef<const Expr *> Args,
8031                               bool HasVAListArg, unsigned format_idx,
8032                               unsigned firstDataArg,
8033                               Sema::FormatStringType Type,
8034                               bool inFunctionCall,
8035                               Sema::VariadicCallType CallType,
8036                               llvm::SmallBitVector &CheckedVarArgs,
8037                               UncoveredArgHandler &UncoveredArg) {
8038   // CHECK: is the format string a wide literal?
8039   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8040     CheckFormatHandler::EmitFormatDiagnostic(
8041       S, inFunctionCall, Args[format_idx],
8042       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
8043       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
8044     return;
8045   }
8046 
8047   // Str - The format string.  NOTE: this is NOT null-terminated!
8048   StringRef StrRef = FExpr->getString();
8049   const char *Str = StrRef.data();
8050   // Account for cases where the string literal is truncated in a declaration.
8051   const ConstantArrayType *T =
8052     S.Context.getAsConstantArrayType(FExpr->getType());
8053   assert(T && "String literal not of constant array type!");
8054   size_t TypeSize = T->getSize().getZExtValue();
8055   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8056   const unsigned numDataArgs = Args.size() - firstDataArg;
8057 
8058   // Emit a warning if the string literal is truncated and does not contain an
8059   // embedded null character.
8060   if (TypeSize <= StrRef.size() &&
8061       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8062     CheckFormatHandler::EmitFormatDiagnostic(
8063         S, inFunctionCall, Args[format_idx],
8064         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8065         FExpr->getLocStart(),
8066         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8067     return;
8068   }
8069 
8070   // CHECK: empty format string?
8071   if (StrLen == 0 && numDataArgs > 0) {
8072     CheckFormatHandler::EmitFormatDiagnostic(
8073       S, inFunctionCall, Args[format_idx],
8074       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
8075       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
8076     return;
8077   }
8078 
8079   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8080       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8081       Type == Sema::FST_OSTrace) {
8082     CheckPrintfHandler H(
8083         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8084         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8085         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8086         CheckedVarArgs, UncoveredArg);
8087 
8088     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8089                                                   S.getLangOpts(),
8090                                                   S.Context.getTargetInfo(),
8091                                             Type == Sema::FST_FreeBSDKPrintf))
8092       H.DoneProcessing();
8093   } else if (Type == Sema::FST_Scanf) {
8094     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8095                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8096                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8097 
8098     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8099                                                  S.getLangOpts(),
8100                                                  S.Context.getTargetInfo()))
8101       H.DoneProcessing();
8102   } // TODO: handle other formats
8103 }
8104 
8105 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8106   // Str - The format string.  NOTE: this is NOT null-terminated!
8107   StringRef StrRef = FExpr->getString();
8108   const char *Str = StrRef.data();
8109   // Account for cases where the string literal is truncated in a declaration.
8110   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8111   assert(T && "String literal not of constant array type!");
8112   size_t TypeSize = T->getSize().getZExtValue();
8113   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8114   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8115                                                          getLangOpts(),
8116                                                          Context.getTargetInfo());
8117 }
8118 
8119 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8120 
8121 // Returns the related absolute value function that is larger, of 0 if one
8122 // does not exist.
8123 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8124   switch (AbsFunction) {
8125   default:
8126     return 0;
8127 
8128   case Builtin::BI__builtin_abs:
8129     return Builtin::BI__builtin_labs;
8130   case Builtin::BI__builtin_labs:
8131     return Builtin::BI__builtin_llabs;
8132   case Builtin::BI__builtin_llabs:
8133     return 0;
8134 
8135   case Builtin::BI__builtin_fabsf:
8136     return Builtin::BI__builtin_fabs;
8137   case Builtin::BI__builtin_fabs:
8138     return Builtin::BI__builtin_fabsl;
8139   case Builtin::BI__builtin_fabsl:
8140     return 0;
8141 
8142   case Builtin::BI__builtin_cabsf:
8143     return Builtin::BI__builtin_cabs;
8144   case Builtin::BI__builtin_cabs:
8145     return Builtin::BI__builtin_cabsl;
8146   case Builtin::BI__builtin_cabsl:
8147     return 0;
8148 
8149   case Builtin::BIabs:
8150     return Builtin::BIlabs;
8151   case Builtin::BIlabs:
8152     return Builtin::BIllabs;
8153   case Builtin::BIllabs:
8154     return 0;
8155 
8156   case Builtin::BIfabsf:
8157     return Builtin::BIfabs;
8158   case Builtin::BIfabs:
8159     return Builtin::BIfabsl;
8160   case Builtin::BIfabsl:
8161     return 0;
8162 
8163   case Builtin::BIcabsf:
8164    return Builtin::BIcabs;
8165   case Builtin::BIcabs:
8166     return Builtin::BIcabsl;
8167   case Builtin::BIcabsl:
8168     return 0;
8169   }
8170 }
8171 
8172 // Returns the argument type of the absolute value function.
8173 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8174                                              unsigned AbsType) {
8175   if (AbsType == 0)
8176     return QualType();
8177 
8178   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8179   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8180   if (Error != ASTContext::GE_None)
8181     return QualType();
8182 
8183   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8184   if (!FT)
8185     return QualType();
8186 
8187   if (FT->getNumParams() != 1)
8188     return QualType();
8189 
8190   return FT->getParamType(0);
8191 }
8192 
8193 // Returns the best absolute value function, or zero, based on type and
8194 // current absolute value function.
8195 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8196                                    unsigned AbsFunctionKind) {
8197   unsigned BestKind = 0;
8198   uint64_t ArgSize = Context.getTypeSize(ArgType);
8199   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8200        Kind = getLargerAbsoluteValueFunction(Kind)) {
8201     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8202     if (Context.getTypeSize(ParamType) >= ArgSize) {
8203       if (BestKind == 0)
8204         BestKind = Kind;
8205       else if (Context.hasSameType(ParamType, ArgType)) {
8206         BestKind = Kind;
8207         break;
8208       }
8209     }
8210   }
8211   return BestKind;
8212 }
8213 
8214 enum AbsoluteValueKind {
8215   AVK_Integer,
8216   AVK_Floating,
8217   AVK_Complex
8218 };
8219 
8220 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8221   if (T->isIntegralOrEnumerationType())
8222     return AVK_Integer;
8223   if (T->isRealFloatingType())
8224     return AVK_Floating;
8225   if (T->isAnyComplexType())
8226     return AVK_Complex;
8227 
8228   llvm_unreachable("Type not integer, floating, or complex");
8229 }
8230 
8231 // Changes the absolute value function to a different type.  Preserves whether
8232 // the function is a builtin.
8233 static unsigned changeAbsFunction(unsigned AbsKind,
8234                                   AbsoluteValueKind ValueKind) {
8235   switch (ValueKind) {
8236   case AVK_Integer:
8237     switch (AbsKind) {
8238     default:
8239       return 0;
8240     case Builtin::BI__builtin_fabsf:
8241     case Builtin::BI__builtin_fabs:
8242     case Builtin::BI__builtin_fabsl:
8243     case Builtin::BI__builtin_cabsf:
8244     case Builtin::BI__builtin_cabs:
8245     case Builtin::BI__builtin_cabsl:
8246       return Builtin::BI__builtin_abs;
8247     case Builtin::BIfabsf:
8248     case Builtin::BIfabs:
8249     case Builtin::BIfabsl:
8250     case Builtin::BIcabsf:
8251     case Builtin::BIcabs:
8252     case Builtin::BIcabsl:
8253       return Builtin::BIabs;
8254     }
8255   case AVK_Floating:
8256     switch (AbsKind) {
8257     default:
8258       return 0;
8259     case Builtin::BI__builtin_abs:
8260     case Builtin::BI__builtin_labs:
8261     case Builtin::BI__builtin_llabs:
8262     case Builtin::BI__builtin_cabsf:
8263     case Builtin::BI__builtin_cabs:
8264     case Builtin::BI__builtin_cabsl:
8265       return Builtin::BI__builtin_fabsf;
8266     case Builtin::BIabs:
8267     case Builtin::BIlabs:
8268     case Builtin::BIllabs:
8269     case Builtin::BIcabsf:
8270     case Builtin::BIcabs:
8271     case Builtin::BIcabsl:
8272       return Builtin::BIfabsf;
8273     }
8274   case AVK_Complex:
8275     switch (AbsKind) {
8276     default:
8277       return 0;
8278     case Builtin::BI__builtin_abs:
8279     case Builtin::BI__builtin_labs:
8280     case Builtin::BI__builtin_llabs:
8281     case Builtin::BI__builtin_fabsf:
8282     case Builtin::BI__builtin_fabs:
8283     case Builtin::BI__builtin_fabsl:
8284       return Builtin::BI__builtin_cabsf;
8285     case Builtin::BIabs:
8286     case Builtin::BIlabs:
8287     case Builtin::BIllabs:
8288     case Builtin::BIfabsf:
8289     case Builtin::BIfabs:
8290     case Builtin::BIfabsl:
8291       return Builtin::BIcabsf;
8292     }
8293   }
8294   llvm_unreachable("Unable to convert function");
8295 }
8296 
8297 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8298   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8299   if (!FnInfo)
8300     return 0;
8301 
8302   switch (FDecl->getBuiltinID()) {
8303   default:
8304     return 0;
8305   case Builtin::BI__builtin_abs:
8306   case Builtin::BI__builtin_fabs:
8307   case Builtin::BI__builtin_fabsf:
8308   case Builtin::BI__builtin_fabsl:
8309   case Builtin::BI__builtin_labs:
8310   case Builtin::BI__builtin_llabs:
8311   case Builtin::BI__builtin_cabs:
8312   case Builtin::BI__builtin_cabsf:
8313   case Builtin::BI__builtin_cabsl:
8314   case Builtin::BIabs:
8315   case Builtin::BIlabs:
8316   case Builtin::BIllabs:
8317   case Builtin::BIfabs:
8318   case Builtin::BIfabsf:
8319   case Builtin::BIfabsl:
8320   case Builtin::BIcabs:
8321   case Builtin::BIcabsf:
8322   case Builtin::BIcabsl:
8323     return FDecl->getBuiltinID();
8324   }
8325   llvm_unreachable("Unknown Builtin type");
8326 }
8327 
8328 // If the replacement is valid, emit a note with replacement function.
8329 // Additionally, suggest including the proper header if not already included.
8330 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8331                             unsigned AbsKind, QualType ArgType) {
8332   bool EmitHeaderHint = true;
8333   const char *HeaderName = nullptr;
8334   const char *FunctionName = nullptr;
8335   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8336     FunctionName = "std::abs";
8337     if (ArgType->isIntegralOrEnumerationType()) {
8338       HeaderName = "cstdlib";
8339     } else if (ArgType->isRealFloatingType()) {
8340       HeaderName = "cmath";
8341     } else {
8342       llvm_unreachable("Invalid Type");
8343     }
8344 
8345     // Lookup all std::abs
8346     if (NamespaceDecl *Std = S.getStdNamespace()) {
8347       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8348       R.suppressDiagnostics();
8349       S.LookupQualifiedName(R, Std);
8350 
8351       for (const auto *I : R) {
8352         const FunctionDecl *FDecl = nullptr;
8353         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8354           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8355         } else {
8356           FDecl = dyn_cast<FunctionDecl>(I);
8357         }
8358         if (!FDecl)
8359           continue;
8360 
8361         // Found std::abs(), check that they are the right ones.
8362         if (FDecl->getNumParams() != 1)
8363           continue;
8364 
8365         // Check that the parameter type can handle the argument.
8366         QualType ParamType = FDecl->getParamDecl(0)->getType();
8367         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8368             S.Context.getTypeSize(ArgType) <=
8369                 S.Context.getTypeSize(ParamType)) {
8370           // Found a function, don't need the header hint.
8371           EmitHeaderHint = false;
8372           break;
8373         }
8374       }
8375     }
8376   } else {
8377     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8378     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8379 
8380     if (HeaderName) {
8381       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8382       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8383       R.suppressDiagnostics();
8384       S.LookupName(R, S.getCurScope());
8385 
8386       if (R.isSingleResult()) {
8387         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8388         if (FD && FD->getBuiltinID() == AbsKind) {
8389           EmitHeaderHint = false;
8390         } else {
8391           return;
8392         }
8393       } else if (!R.empty()) {
8394         return;
8395       }
8396     }
8397   }
8398 
8399   S.Diag(Loc, diag::note_replace_abs_function)
8400       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8401 
8402   if (!HeaderName)
8403     return;
8404 
8405   if (!EmitHeaderHint)
8406     return;
8407 
8408   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8409                                                     << FunctionName;
8410 }
8411 
8412 template <std::size_t StrLen>
8413 static bool IsStdFunction(const FunctionDecl *FDecl,
8414                           const char (&Str)[StrLen]) {
8415   if (!FDecl)
8416     return false;
8417   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8418     return false;
8419   if (!FDecl->isInStdNamespace())
8420     return false;
8421 
8422   return true;
8423 }
8424 
8425 // Warn when using the wrong abs() function.
8426 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8427                                       const FunctionDecl *FDecl) {
8428   if (Call->getNumArgs() != 1)
8429     return;
8430 
8431   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8432   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8433   if (AbsKind == 0 && !IsStdAbs)
8434     return;
8435 
8436   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8437   QualType ParamType = Call->getArg(0)->getType();
8438 
8439   // Unsigned types cannot be negative.  Suggest removing the absolute value
8440   // function call.
8441   if (ArgType->isUnsignedIntegerType()) {
8442     const char *FunctionName =
8443         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8444     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8445     Diag(Call->getExprLoc(), diag::note_remove_abs)
8446         << FunctionName
8447         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8448     return;
8449   }
8450 
8451   // Taking the absolute value of a pointer is very suspicious, they probably
8452   // wanted to index into an array, dereference a pointer, call a function, etc.
8453   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8454     unsigned DiagType = 0;
8455     if (ArgType->isFunctionType())
8456       DiagType = 1;
8457     else if (ArgType->isArrayType())
8458       DiagType = 2;
8459 
8460     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8461     return;
8462   }
8463 
8464   // std::abs has overloads which prevent most of the absolute value problems
8465   // from occurring.
8466   if (IsStdAbs)
8467     return;
8468 
8469   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8470   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8471 
8472   // The argument and parameter are the same kind.  Check if they are the right
8473   // size.
8474   if (ArgValueKind == ParamValueKind) {
8475     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8476       return;
8477 
8478     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8479     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8480         << FDecl << ArgType << ParamType;
8481 
8482     if (NewAbsKind == 0)
8483       return;
8484 
8485     emitReplacement(*this, Call->getExprLoc(),
8486                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8487     return;
8488   }
8489 
8490   // ArgValueKind != ParamValueKind
8491   // The wrong type of absolute value function was used.  Attempt to find the
8492   // proper one.
8493   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8494   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8495   if (NewAbsKind == 0)
8496     return;
8497 
8498   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8499       << FDecl << ParamValueKind << ArgValueKind;
8500 
8501   emitReplacement(*this, Call->getExprLoc(),
8502                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8503 }
8504 
8505 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8506 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8507                                 const FunctionDecl *FDecl) {
8508   if (!Call || !FDecl) return;
8509 
8510   // Ignore template specializations and macros.
8511   if (inTemplateInstantiation()) return;
8512   if (Call->getExprLoc().isMacroID()) return;
8513 
8514   // Only care about the one template argument, two function parameter std::max
8515   if (Call->getNumArgs() != 2) return;
8516   if (!IsStdFunction(FDecl, "max")) return;
8517   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8518   if (!ArgList) return;
8519   if (ArgList->size() != 1) return;
8520 
8521   // Check that template type argument is unsigned integer.
8522   const auto& TA = ArgList->get(0);
8523   if (TA.getKind() != TemplateArgument::Type) return;
8524   QualType ArgType = TA.getAsType();
8525   if (!ArgType->isUnsignedIntegerType()) return;
8526 
8527   // See if either argument is a literal zero.
8528   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8529     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8530     if (!MTE) return false;
8531     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8532     if (!Num) return false;
8533     if (Num->getValue() != 0) return false;
8534     return true;
8535   };
8536 
8537   const Expr *FirstArg = Call->getArg(0);
8538   const Expr *SecondArg = Call->getArg(1);
8539   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8540   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8541 
8542   // Only warn when exactly one argument is zero.
8543   if (IsFirstArgZero == IsSecondArgZero) return;
8544 
8545   SourceRange FirstRange = FirstArg->getSourceRange();
8546   SourceRange SecondRange = SecondArg->getSourceRange();
8547 
8548   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8549 
8550   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8551       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8552 
8553   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8554   SourceRange RemovalRange;
8555   if (IsFirstArgZero) {
8556     RemovalRange = SourceRange(FirstRange.getBegin(),
8557                                SecondRange.getBegin().getLocWithOffset(-1));
8558   } else {
8559     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8560                                SecondRange.getEnd());
8561   }
8562 
8563   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8564         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8565         << FixItHint::CreateRemoval(RemovalRange);
8566 }
8567 
8568 //===--- CHECK: Standard memory functions ---------------------------------===//
8569 
8570 /// Takes the expression passed to the size_t parameter of functions
8571 /// such as memcmp, strncat, etc and warns if it's a comparison.
8572 ///
8573 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8574 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8575                                            IdentifierInfo *FnName,
8576                                            SourceLocation FnLoc,
8577                                            SourceLocation RParenLoc) {
8578   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8579   if (!Size)
8580     return false;
8581 
8582   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8583   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8584     return false;
8585 
8586   SourceRange SizeRange = Size->getSourceRange();
8587   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8588       << SizeRange << FnName;
8589   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8590       << FnName << FixItHint::CreateInsertion(
8591                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
8592       << FixItHint::CreateRemoval(RParenLoc);
8593   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8594       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8595       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8596                                     ")");
8597 
8598   return true;
8599 }
8600 
8601 /// Determine whether the given type is or contains a dynamic class type
8602 /// (e.g., whether it has a vtable).
8603 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8604                                                      bool &IsContained) {
8605   // Look through array types while ignoring qualifiers.
8606   const Type *Ty = T->getBaseElementTypeUnsafe();
8607   IsContained = false;
8608 
8609   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8610   RD = RD ? RD->getDefinition() : nullptr;
8611   if (!RD || RD->isInvalidDecl())
8612     return nullptr;
8613 
8614   if (RD->isDynamicClass())
8615     return RD;
8616 
8617   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8618   // It's impossible for a class to transitively contain itself by value, so
8619   // infinite recursion is impossible.
8620   for (auto *FD : RD->fields()) {
8621     bool SubContained;
8622     if (const CXXRecordDecl *ContainedRD =
8623             getContainedDynamicClass(FD->getType(), SubContained)) {
8624       IsContained = true;
8625       return ContainedRD;
8626     }
8627   }
8628 
8629   return nullptr;
8630 }
8631 
8632 /// If E is a sizeof expression, returns its argument expression,
8633 /// otherwise returns NULL.
8634 static const Expr *getSizeOfExprArg(const Expr *E) {
8635   if (const UnaryExprOrTypeTraitExpr *SizeOf =
8636       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8637     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
8638       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8639 
8640   return nullptr;
8641 }
8642 
8643 /// If E is a sizeof expression, returns its argument type.
8644 static QualType getSizeOfArgType(const Expr *E) {
8645   if (const UnaryExprOrTypeTraitExpr *SizeOf =
8646       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8647     if (SizeOf->getKind() == UETT_SizeOf)
8648       return SizeOf->getTypeOfArgument();
8649 
8650   return QualType();
8651 }
8652 
8653 namespace {
8654 
8655 struct SearchNonTrivialToInitializeField
8656     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8657   using Super =
8658       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8659 
8660   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8661 
8662   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8663                      SourceLocation SL) {
8664     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8665       asDerived().visitArray(PDIK, AT, SL);
8666       return;
8667     }
8668 
8669     Super::visitWithKind(PDIK, FT, SL);
8670   }
8671 
8672   void visitARCStrong(QualType FT, SourceLocation SL) {
8673     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8674   }
8675   void visitARCWeak(QualType FT, SourceLocation SL) {
8676     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8677   }
8678   void visitStruct(QualType FT, SourceLocation SL) {
8679     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8680       visit(FD->getType(), FD->getLocation());
8681   }
8682   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8683                   const ArrayType *AT, SourceLocation SL) {
8684     visit(getContext().getBaseElementType(AT), SL);
8685   }
8686   void visitTrivial(QualType FT, SourceLocation SL) {}
8687 
8688   static void diag(QualType RT, const Expr *E, Sema &S) {
8689     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8690   }
8691 
8692   ASTContext &getContext() { return S.getASTContext(); }
8693 
8694   const Expr *E;
8695   Sema &S;
8696 };
8697 
8698 struct SearchNonTrivialToCopyField
8699     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8700   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8701 
8702   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8703 
8704   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8705                      SourceLocation SL) {
8706     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8707       asDerived().visitArray(PCK, AT, SL);
8708       return;
8709     }
8710 
8711     Super::visitWithKind(PCK, FT, SL);
8712   }
8713 
8714   void visitARCStrong(QualType FT, SourceLocation SL) {
8715     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8716   }
8717   void visitARCWeak(QualType FT, SourceLocation SL) {
8718     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8719   }
8720   void visitStruct(QualType FT, SourceLocation SL) {
8721     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8722       visit(FD->getType(), FD->getLocation());
8723   }
8724   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8725                   SourceLocation SL) {
8726     visit(getContext().getBaseElementType(AT), SL);
8727   }
8728   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8729                 SourceLocation SL) {}
8730   void visitTrivial(QualType FT, SourceLocation SL) {}
8731   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8732 
8733   static void diag(QualType RT, const Expr *E, Sema &S) {
8734     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8735   }
8736 
8737   ASTContext &getContext() { return S.getASTContext(); }
8738 
8739   const Expr *E;
8740   Sema &S;
8741 };
8742 
8743 }
8744 
8745 /// Check for dangerous or invalid arguments to memset().
8746 ///
8747 /// This issues warnings on known problematic, dangerous or unspecified
8748 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
8749 /// function calls.
8750 ///
8751 /// \param Call The call expression to diagnose.
8752 void Sema::CheckMemaccessArguments(const CallExpr *Call,
8753                                    unsigned BId,
8754                                    IdentifierInfo *FnName) {
8755   assert(BId != 0);
8756 
8757   // It is possible to have a non-standard definition of memset.  Validate
8758   // we have enough arguments, and if not, abort further checking.
8759   unsigned ExpectedNumArgs =
8760       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
8761   if (Call->getNumArgs() < ExpectedNumArgs)
8762     return;
8763 
8764   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
8765                       BId == Builtin::BIstrndup ? 1 : 2);
8766   unsigned LenArg =
8767       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
8768   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
8769 
8770   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
8771                                      Call->getLocStart(), Call->getRParenLoc()))
8772     return;
8773 
8774   // We have special checking when the length is a sizeof expression.
8775   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
8776   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
8777   llvm::FoldingSetNodeID SizeOfArgID;
8778 
8779   // Although widely used, 'bzero' is not a standard function. Be more strict
8780   // with the argument types before allowing diagnostics and only allow the
8781   // form bzero(ptr, sizeof(...)).
8782   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8783   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8784     return;
8785 
8786   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
8787     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
8788     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
8789 
8790     QualType DestTy = Dest->getType();
8791     QualType PointeeTy;
8792     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
8793       PointeeTy = DestPtrTy->getPointeeType();
8794 
8795       // Never warn about void type pointers. This can be used to suppress
8796       // false positives.
8797       if (PointeeTy->isVoidType())
8798         continue;
8799 
8800       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8801       // actually comparing the expressions for equality. Because computing the
8802       // expression IDs can be expensive, we only do this if the diagnostic is
8803       // enabled.
8804       if (SizeOfArg &&
8805           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8806                            SizeOfArg->getExprLoc())) {
8807         // We only compute IDs for expressions if the warning is enabled, and
8808         // cache the sizeof arg's ID.
8809         if (SizeOfArgID == llvm::FoldingSetNodeID())
8810           SizeOfArg->Profile(SizeOfArgID, Context, true);
8811         llvm::FoldingSetNodeID DestID;
8812         Dest->Profile(DestID, Context, true);
8813         if (DestID == SizeOfArgID) {
8814           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
8815           //       over sizeof(src) as well.
8816           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
8817           StringRef ReadableName = FnName->getName();
8818 
8819           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
8820             if (UnaryOp->getOpcode() == UO_AddrOf)
8821               ActionIdx = 1; // If its an address-of operator, just remove it.
8822           if (!PointeeTy->isIncompleteType() &&
8823               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
8824             ActionIdx = 2; // If the pointee's size is sizeof(char),
8825                            // suggest an explicit length.
8826 
8827           // If the function is defined as a builtin macro, do not show macro
8828           // expansion.
8829           SourceLocation SL = SizeOfArg->getExprLoc();
8830           SourceRange DSR = Dest->getSourceRange();
8831           SourceRange SSR = SizeOfArg->getSourceRange();
8832           SourceManager &SM = getSourceManager();
8833 
8834           if (SM.isMacroArgExpansion(SL)) {
8835             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8836             SL = SM.getSpellingLoc(SL);
8837             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8838                              SM.getSpellingLoc(DSR.getEnd()));
8839             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8840                              SM.getSpellingLoc(SSR.getEnd()));
8841           }
8842 
8843           DiagRuntimeBehavior(SL, SizeOfArg,
8844                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
8845                                 << ReadableName
8846                                 << PointeeTy
8847                                 << DestTy
8848                                 << DSR
8849                                 << SSR);
8850           DiagRuntimeBehavior(SL, SizeOfArg,
8851                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8852                                 << ActionIdx
8853                                 << SSR);
8854 
8855           break;
8856         }
8857       }
8858 
8859       // Also check for cases where the sizeof argument is the exact same
8860       // type as the memory argument, and where it points to a user-defined
8861       // record type.
8862       if (SizeOfArgTy != QualType()) {
8863         if (PointeeTy->isRecordType() &&
8864             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8865           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8866                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
8867                                 << FnName << SizeOfArgTy << ArgIdx
8868                                 << PointeeTy << Dest->getSourceRange()
8869                                 << LenExpr->getSourceRange());
8870           break;
8871         }
8872       }
8873     } else if (DestTy->isArrayType()) {
8874       PointeeTy = DestTy;
8875     }
8876 
8877     if (PointeeTy == QualType())
8878       continue;
8879 
8880     // Always complain about dynamic classes.
8881     bool IsContained;
8882     if (const CXXRecordDecl *ContainedRD =
8883             getContainedDynamicClass(PointeeTy, IsContained)) {
8884 
8885       unsigned OperationType = 0;
8886       // "overwritten" if we're warning about the destination for any call
8887       // but memcmp; otherwise a verb appropriate to the call.
8888       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8889         if (BId == Builtin::BImemcpy)
8890           OperationType = 1;
8891         else if(BId == Builtin::BImemmove)
8892           OperationType = 2;
8893         else if (BId == Builtin::BImemcmp)
8894           OperationType = 3;
8895       }
8896 
8897       DiagRuntimeBehavior(
8898         Dest->getExprLoc(), Dest,
8899         PDiag(diag::warn_dyn_class_memaccess)
8900           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8901           << FnName << IsContained << ContainedRD << OperationType
8902           << Call->getCallee()->getSourceRange());
8903     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8904              BId != Builtin::BImemset)
8905       DiagRuntimeBehavior(
8906         Dest->getExprLoc(), Dest,
8907         PDiag(diag::warn_arc_object_memaccess)
8908           << ArgIdx << FnName << PointeeTy
8909           << Call->getCallee()->getSourceRange());
8910     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8911       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8912           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8913         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8914                             PDiag(diag::warn_cstruct_memaccess)
8915                                 << ArgIdx << FnName << PointeeTy << 0);
8916         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8917       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8918                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8919         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8920                             PDiag(diag::warn_cstruct_memaccess)
8921                                 << ArgIdx << FnName << PointeeTy << 1);
8922         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8923       } else {
8924         continue;
8925       }
8926     } else
8927       continue;
8928 
8929     DiagRuntimeBehavior(
8930       Dest->getExprLoc(), Dest,
8931       PDiag(diag::note_bad_memaccess_silence)
8932         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8933     break;
8934   }
8935 }
8936 
8937 // A little helper routine: ignore addition and subtraction of integer literals.
8938 // This intentionally does not ignore all integer constant expressions because
8939 // we don't want to remove sizeof().
8940 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8941   Ex = Ex->IgnoreParenCasts();
8942 
8943   while (true) {
8944     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8945     if (!BO || !BO->isAdditiveOp())
8946       break;
8947 
8948     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8949     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8950 
8951     if (isa<IntegerLiteral>(RHS))
8952       Ex = LHS;
8953     else if (isa<IntegerLiteral>(LHS))
8954       Ex = RHS;
8955     else
8956       break;
8957   }
8958 
8959   return Ex;
8960 }
8961 
8962 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8963                                                       ASTContext &Context) {
8964   // Only handle constant-sized or VLAs, but not flexible members.
8965   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8966     // Only issue the FIXIT for arrays of size > 1.
8967     if (CAT->getSize().getSExtValue() <= 1)
8968       return false;
8969   } else if (!Ty->isVariableArrayType()) {
8970     return false;
8971   }
8972   return true;
8973 }
8974 
8975 // Warn if the user has made the 'size' argument to strlcpy or strlcat
8976 // be the size of the source, instead of the destination.
8977 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8978                                     IdentifierInfo *FnName) {
8979 
8980   // Don't crash if the user has the wrong number of arguments
8981   unsigned NumArgs = Call->getNumArgs();
8982   if ((NumArgs != 3) && (NumArgs != 4))
8983     return;
8984 
8985   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8986   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
8987   const Expr *CompareWithSrc = nullptr;
8988 
8989   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8990                                      Call->getLocStart(), Call->getRParenLoc()))
8991     return;
8992 
8993   // Look for 'strlcpy(dst, x, sizeof(x))'
8994   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8995     CompareWithSrc = Ex;
8996   else {
8997     // Look for 'strlcpy(dst, x, strlen(x))'
8998     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
8999       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9000           SizeCall->getNumArgs() == 1)
9001         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9002     }
9003   }
9004 
9005   if (!CompareWithSrc)
9006     return;
9007 
9008   // Determine if the argument to sizeof/strlen is equal to the source
9009   // argument.  In principle there's all kinds of things you could do
9010   // here, for instance creating an == expression and evaluating it with
9011   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9012   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9013   if (!SrcArgDRE)
9014     return;
9015 
9016   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9017   if (!CompareWithSrcDRE ||
9018       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9019     return;
9020 
9021   const Expr *OriginalSizeArg = Call->getArg(2);
9022   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
9023     << OriginalSizeArg->getSourceRange() << FnName;
9024 
9025   // Output a FIXIT hint if the destination is an array (rather than a
9026   // pointer to an array).  This could be enhanced to handle some
9027   // pointers if we know the actual size, like if DstArg is 'array+2'
9028   // we could say 'sizeof(array)-2'.
9029   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9030   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9031     return;
9032 
9033   SmallString<128> sizeString;
9034   llvm::raw_svector_ostream OS(sizeString);
9035   OS << "sizeof(";
9036   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9037   OS << ")";
9038 
9039   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
9040     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9041                                     OS.str());
9042 }
9043 
9044 /// Check if two expressions refer to the same declaration.
9045 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9046   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9047     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9048       return D1->getDecl() == D2->getDecl();
9049   return false;
9050 }
9051 
9052 static const Expr *getStrlenExprArg(const Expr *E) {
9053   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9054     const FunctionDecl *FD = CE->getDirectCallee();
9055     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9056       return nullptr;
9057     return CE->getArg(0)->IgnoreParenCasts();
9058   }
9059   return nullptr;
9060 }
9061 
9062 // Warn on anti-patterns as the 'size' argument to strncat.
9063 // The correct size argument should look like following:
9064 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9065 void Sema::CheckStrncatArguments(const CallExpr *CE,
9066                                  IdentifierInfo *FnName) {
9067   // Don't crash if the user has the wrong number of arguments.
9068   if (CE->getNumArgs() < 3)
9069     return;
9070   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9071   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9072   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9073 
9074   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
9075                                      CE->getRParenLoc()))
9076     return;
9077 
9078   // Identify common expressions, which are wrongly used as the size argument
9079   // to strncat and may lead to buffer overflows.
9080   unsigned PatternType = 0;
9081   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9082     // - sizeof(dst)
9083     if (referToTheSameDecl(SizeOfArg, DstArg))
9084       PatternType = 1;
9085     // - sizeof(src)
9086     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9087       PatternType = 2;
9088   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9089     if (BE->getOpcode() == BO_Sub) {
9090       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9091       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9092       // - sizeof(dst) - strlen(dst)
9093       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9094           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9095         PatternType = 1;
9096       // - sizeof(src) - (anything)
9097       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9098         PatternType = 2;
9099     }
9100   }
9101 
9102   if (PatternType == 0)
9103     return;
9104 
9105   // Generate the diagnostic.
9106   SourceLocation SL = LenArg->getLocStart();
9107   SourceRange SR = LenArg->getSourceRange();
9108   SourceManager &SM = getSourceManager();
9109 
9110   // If the function is defined as a builtin macro, do not show macro expansion.
9111   if (SM.isMacroArgExpansion(SL)) {
9112     SL = SM.getSpellingLoc(SL);
9113     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9114                      SM.getSpellingLoc(SR.getEnd()));
9115   }
9116 
9117   // Check if the destination is an array (rather than a pointer to an array).
9118   QualType DstTy = DstArg->getType();
9119   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9120                                                                     Context);
9121   if (!isKnownSizeArray) {
9122     if (PatternType == 1)
9123       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9124     else
9125       Diag(SL, diag::warn_strncat_src_size) << SR;
9126     return;
9127   }
9128 
9129   if (PatternType == 1)
9130     Diag(SL, diag::warn_strncat_large_size) << SR;
9131   else
9132     Diag(SL, diag::warn_strncat_src_size) << SR;
9133 
9134   SmallString<128> sizeString;
9135   llvm::raw_svector_ostream OS(sizeString);
9136   OS << "sizeof(";
9137   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9138   OS << ") - ";
9139   OS << "strlen(";
9140   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9141   OS << ") - 1";
9142 
9143   Diag(SL, diag::note_strncat_wrong_size)
9144     << FixItHint::CreateReplacement(SR, OS.str());
9145 }
9146 
9147 //===--- CHECK: Return Address of Stack Variable --------------------------===//
9148 
9149 static const Expr *EvalVal(const Expr *E,
9150                            SmallVectorImpl<const DeclRefExpr *> &refVars,
9151                            const Decl *ParentDecl);
9152 static const Expr *EvalAddr(const Expr *E,
9153                             SmallVectorImpl<const DeclRefExpr *> &refVars,
9154                             const Decl *ParentDecl);
9155 
9156 /// CheckReturnStackAddr - Check if a return statement returns the address
9157 ///   of a stack variable.
9158 static void
9159 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
9160                      SourceLocation ReturnLoc) {
9161   const Expr *stackE = nullptr;
9162   SmallVector<const DeclRefExpr *, 8> refVars;
9163 
9164   // Perform checking for returned stack addresses, local blocks,
9165   // label addresses or references to temporaries.
9166   if (lhsType->isPointerType() ||
9167       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
9168     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
9169   } else if (lhsType->isReferenceType()) {
9170     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
9171   }
9172 
9173   if (!stackE)
9174     return; // Nothing suspicious was found.
9175 
9176   // Parameters are initialized in the calling scope, so taking the address
9177   // of a parameter reference doesn't need a warning.
9178   for (auto *DRE : refVars)
9179     if (isa<ParmVarDecl>(DRE->getDecl()))
9180       return;
9181 
9182   SourceLocation diagLoc;
9183   SourceRange diagRange;
9184   if (refVars.empty()) {
9185     diagLoc = stackE->getLocStart();
9186     diagRange = stackE->getSourceRange();
9187   } else {
9188     // We followed through a reference variable. 'stackE' contains the
9189     // problematic expression but we will warn at the return statement pointing
9190     // at the reference variable. We will later display the "trail" of
9191     // reference variables using notes.
9192     diagLoc = refVars[0]->getLocStart();
9193     diagRange = refVars[0]->getSourceRange();
9194   }
9195 
9196   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
9197     // address of local var
9198     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
9199      << DR->getDecl()->getDeclName() << diagRange;
9200   } else if (isa<BlockExpr>(stackE)) { // local block.
9201     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
9202   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
9203     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
9204   } else { // local temporary.
9205     // If there is an LValue->RValue conversion, then the value of the
9206     // reference type is used, not the reference.
9207     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
9208       if (ICE->getCastKind() == CK_LValueToRValue) {
9209         return;
9210       }
9211     }
9212     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
9213      << lhsType->isReferenceType() << diagRange;
9214   }
9215 
9216   // Display the "trail" of reference variables that we followed until we
9217   // found the problematic expression using notes.
9218   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
9219     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
9220     // If this var binds to another reference var, show the range of the next
9221     // var, otherwise the var binds to the problematic expression, in which case
9222     // show the range of the expression.
9223     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
9224                                     : stackE->getSourceRange();
9225     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
9226         << VD->getDeclName() << range;
9227   }
9228 }
9229 
9230 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
9231 ///  check if the expression in a return statement evaluates to an address
9232 ///  to a location on the stack, a local block, an address of a label, or a
9233 ///  reference to local temporary. The recursion is used to traverse the
9234 ///  AST of the return expression, with recursion backtracking when we
9235 ///  encounter a subexpression that (1) clearly does not lead to one of the
9236 ///  above problematic expressions (2) is something we cannot determine leads to
9237 ///  a problematic expression based on such local checking.
9238 ///
9239 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
9240 ///  the expression that they point to. Such variables are added to the
9241 ///  'refVars' vector so that we know what the reference variable "trail" was.
9242 ///
9243 ///  EvalAddr processes expressions that are pointers that are used as
9244 ///  references (and not L-values).  EvalVal handles all other values.
9245 ///  At the base case of the recursion is a check for the above problematic
9246 ///  expressions.
9247 ///
9248 ///  This implementation handles:
9249 ///
9250 ///   * pointer-to-pointer casts
9251 ///   * implicit conversions from array references to pointers
9252 ///   * taking the address of fields
9253 ///   * arbitrary interplay between "&" and "*" operators
9254 ///   * pointer arithmetic from an address of a stack variable
9255 ///   * taking the address of an array element where the array is on the stack
9256 static const Expr *EvalAddr(const Expr *E,
9257                             SmallVectorImpl<const DeclRefExpr *> &refVars,
9258                             const Decl *ParentDecl) {
9259   if (E->isTypeDependent())
9260     return nullptr;
9261 
9262   // We should only be called for evaluating pointer expressions.
9263   assert((E->getType()->isAnyPointerType() ||
9264           E->getType()->isBlockPointerType() ||
9265           E->getType()->isObjCQualifiedIdType()) &&
9266          "EvalAddr only works on pointers");
9267 
9268   E = E->IgnoreParens();
9269 
9270   // Our "symbolic interpreter" is just a dispatch off the currently
9271   // viewed AST node.  We then recursively traverse the AST by calling
9272   // EvalAddr and EvalVal appropriately.
9273   switch (E->getStmtClass()) {
9274   case Stmt::DeclRefExprClass: {
9275     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
9276 
9277     // If we leave the immediate function, the lifetime isn't about to end.
9278     if (DR->refersToEnclosingVariableOrCapture())
9279       return nullptr;
9280 
9281     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
9282       // If this is a reference variable, follow through to the expression that
9283       // it points to.
9284       if (V->hasLocalStorage() &&
9285           V->getType()->isReferenceType() && V->hasInit()) {
9286         // Add the reference variable to the "trail".
9287         refVars.push_back(DR);
9288         return EvalAddr(V->getInit(), refVars, ParentDecl);
9289       }
9290 
9291     return nullptr;
9292   }
9293 
9294   case Stmt::UnaryOperatorClass: {
9295     // The only unary operator that make sense to handle here
9296     // is AddrOf.  All others don't make sense as pointers.
9297     const UnaryOperator *U = cast<UnaryOperator>(E);
9298 
9299     if (U->getOpcode() == UO_AddrOf)
9300       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
9301     return nullptr;
9302   }
9303 
9304   case Stmt::BinaryOperatorClass: {
9305     // Handle pointer arithmetic.  All other binary operators are not valid
9306     // in this context.
9307     const BinaryOperator *B = cast<BinaryOperator>(E);
9308     BinaryOperatorKind op = B->getOpcode();
9309 
9310     if (op != BO_Add && op != BO_Sub)
9311       return nullptr;
9312 
9313     const Expr *Base = B->getLHS();
9314 
9315     // Determine which argument is the real pointer base.  It could be
9316     // the RHS argument instead of the LHS.
9317     if (!Base->getType()->isPointerType())
9318       Base = B->getRHS();
9319 
9320     assert(Base->getType()->isPointerType());
9321     return EvalAddr(Base, refVars, ParentDecl);
9322   }
9323 
9324   // For conditional operators we need to see if either the LHS or RHS are
9325   // valid DeclRefExpr*s.  If one of them is valid, we return it.
9326   case Stmt::ConditionalOperatorClass: {
9327     const ConditionalOperator *C = cast<ConditionalOperator>(E);
9328 
9329     // Handle the GNU extension for missing LHS.
9330     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
9331     if (const Expr *LHSExpr = C->getLHS()) {
9332       // In C++, we can have a throw-expression, which has 'void' type.
9333       if (!LHSExpr->getType()->isVoidType())
9334         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
9335           return LHS;
9336     }
9337 
9338     // In C++, we can have a throw-expression, which has 'void' type.
9339     if (C->getRHS()->getType()->isVoidType())
9340       return nullptr;
9341 
9342     return EvalAddr(C->getRHS(), refVars, ParentDecl);
9343   }
9344 
9345   case Stmt::BlockExprClass:
9346     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
9347       return E; // local block.
9348     return nullptr;
9349 
9350   case Stmt::AddrLabelExprClass:
9351     return E; // address of label.
9352 
9353   case Stmt::ExprWithCleanupsClass:
9354     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
9355                     ParentDecl);
9356 
9357   // For casts, we need to handle conversions from arrays to
9358   // pointer values, and pointer-to-pointer conversions.
9359   case Stmt::ImplicitCastExprClass:
9360   case Stmt::CStyleCastExprClass:
9361   case Stmt::CXXFunctionalCastExprClass:
9362   case Stmt::ObjCBridgedCastExprClass:
9363   case Stmt::CXXStaticCastExprClass:
9364   case Stmt::CXXDynamicCastExprClass:
9365   case Stmt::CXXConstCastExprClass:
9366   case Stmt::CXXReinterpretCastExprClass: {
9367     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
9368     switch (cast<CastExpr>(E)->getCastKind()) {
9369     case CK_LValueToRValue:
9370     case CK_NoOp:
9371     case CK_BaseToDerived:
9372     case CK_DerivedToBase:
9373     case CK_UncheckedDerivedToBase:
9374     case CK_Dynamic:
9375     case CK_CPointerToObjCPointerCast:
9376     case CK_BlockPointerToObjCPointerCast:
9377     case CK_AnyPointerToBlockPointerCast:
9378       return EvalAddr(SubExpr, refVars, ParentDecl);
9379 
9380     case CK_ArrayToPointerDecay:
9381       return EvalVal(SubExpr, refVars, ParentDecl);
9382 
9383     case CK_BitCast:
9384       if (SubExpr->getType()->isAnyPointerType() ||
9385           SubExpr->getType()->isBlockPointerType() ||
9386           SubExpr->getType()->isObjCQualifiedIdType())
9387         return EvalAddr(SubExpr, refVars, ParentDecl);
9388       else
9389         return nullptr;
9390 
9391     default:
9392       return nullptr;
9393     }
9394   }
9395 
9396   case Stmt::MaterializeTemporaryExprClass:
9397     if (const Expr *Result =
9398             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
9399                      refVars, ParentDecl))
9400       return Result;
9401     return E;
9402 
9403   // Everything else: we simply don't reason about them.
9404   default:
9405     return nullptr;
9406   }
9407 }
9408 
9409 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
9410 ///   See the comments for EvalAddr for more details.
9411 static const Expr *EvalVal(const Expr *E,
9412                            SmallVectorImpl<const DeclRefExpr *> &refVars,
9413                            const Decl *ParentDecl) {
9414   do {
9415     // We should only be called for evaluating non-pointer expressions, or
9416     // expressions with a pointer type that are not used as references but
9417     // instead
9418     // are l-values (e.g., DeclRefExpr with a pointer type).
9419 
9420     // Our "symbolic interpreter" is just a dispatch off the currently
9421     // viewed AST node.  We then recursively traverse the AST by calling
9422     // EvalAddr and EvalVal appropriately.
9423 
9424     E = E->IgnoreParens();
9425     switch (E->getStmtClass()) {
9426     case Stmt::ImplicitCastExprClass: {
9427       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
9428       if (IE->getValueKind() == VK_LValue) {
9429         E = IE->getSubExpr();
9430         continue;
9431       }
9432       return nullptr;
9433     }
9434 
9435     case Stmt::ExprWithCleanupsClass:
9436       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
9437                      ParentDecl);
9438 
9439     case Stmt::DeclRefExprClass: {
9440       // When we hit a DeclRefExpr we are looking at code that refers to a
9441       // variable's name. If it's not a reference variable we check if it has
9442       // local storage within the function, and if so, return the expression.
9443       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
9444 
9445       // If we leave the immediate function, the lifetime isn't about to end.
9446       if (DR->refersToEnclosingVariableOrCapture())
9447         return nullptr;
9448 
9449       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
9450         // Check if it refers to itself, e.g. "int& i = i;".
9451         if (V == ParentDecl)
9452           return DR;
9453 
9454         if (V->hasLocalStorage()) {
9455           if (!V->getType()->isReferenceType())
9456             return DR;
9457 
9458           // Reference variable, follow through to the expression that
9459           // it points to.
9460           if (V->hasInit()) {
9461             // Add the reference variable to the "trail".
9462             refVars.push_back(DR);
9463             return EvalVal(V->getInit(), refVars, V);
9464           }
9465         }
9466       }
9467 
9468       return nullptr;
9469     }
9470 
9471     case Stmt::UnaryOperatorClass: {
9472       // The only unary operator that make sense to handle here
9473       // is Deref.  All others don't resolve to a "name."  This includes
9474       // handling all sorts of rvalues passed to a unary operator.
9475       const UnaryOperator *U = cast<UnaryOperator>(E);
9476 
9477       if (U->getOpcode() == UO_Deref)
9478         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
9479 
9480       return nullptr;
9481     }
9482 
9483     case Stmt::ArraySubscriptExprClass: {
9484       // Array subscripts are potential references to data on the stack.  We
9485       // retrieve the DeclRefExpr* for the array variable if it indeed
9486       // has local storage.
9487       const auto *ASE = cast<ArraySubscriptExpr>(E);
9488       if (ASE->isTypeDependent())
9489         return nullptr;
9490       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
9491     }
9492 
9493     case Stmt::OMPArraySectionExprClass: {
9494       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
9495                       ParentDecl);
9496     }
9497 
9498     case Stmt::ConditionalOperatorClass: {
9499       // For conditional operators we need to see if either the LHS or RHS are
9500       // non-NULL Expr's.  If one is non-NULL, we return it.
9501       const ConditionalOperator *C = cast<ConditionalOperator>(E);
9502 
9503       // Handle the GNU extension for missing LHS.
9504       if (const Expr *LHSExpr = C->getLHS()) {
9505         // In C++, we can have a throw-expression, which has 'void' type.
9506         if (!LHSExpr->getType()->isVoidType())
9507           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
9508             return LHS;
9509       }
9510 
9511       // In C++, we can have a throw-expression, which has 'void' type.
9512       if (C->getRHS()->getType()->isVoidType())
9513         return nullptr;
9514 
9515       return EvalVal(C->getRHS(), refVars, ParentDecl);
9516     }
9517 
9518     // Accesses to members are potential references to data on the stack.
9519     case Stmt::MemberExprClass: {
9520       const MemberExpr *M = cast<MemberExpr>(E);
9521 
9522       // Check for indirect access.  We only want direct field accesses.
9523       if (M->isArrow())
9524         return nullptr;
9525 
9526       // Check whether the member type is itself a reference, in which case
9527       // we're not going to refer to the member, but to what the member refers
9528       // to.
9529       if (M->getMemberDecl()->getType()->isReferenceType())
9530         return nullptr;
9531 
9532       return EvalVal(M->getBase(), refVars, ParentDecl);
9533     }
9534 
9535     case Stmt::MaterializeTemporaryExprClass:
9536       if (const Expr *Result =
9537               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
9538                       refVars, ParentDecl))
9539         return Result;
9540       return E;
9541 
9542     default:
9543       // Check that we don't return or take the address of a reference to a
9544       // temporary. This is only useful in C++.
9545       if (!E->isTypeDependent() && E->isRValue())
9546         return E;
9547 
9548       // Everything else: we simply don't reason about them.
9549       return nullptr;
9550     }
9551   } while (true);
9552 }
9553 
9554 void
9555 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9556                          SourceLocation ReturnLoc,
9557                          bool isObjCMethod,
9558                          const AttrVec *Attrs,
9559                          const FunctionDecl *FD) {
9560   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
9561 
9562   // Check if the return value is null but should not be.
9563   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9564        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9565       CheckNonNullExpr(*this, RetValExp))
9566     Diag(ReturnLoc, diag::warn_null_ret)
9567       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9568 
9569   // C++11 [basic.stc.dynamic.allocation]p4:
9570   //   If an allocation function declared with a non-throwing
9571   //   exception-specification fails to allocate storage, it shall return
9572   //   a null pointer. Any other allocation function that fails to allocate
9573   //   storage shall indicate failure only by throwing an exception [...]
9574   if (FD) {
9575     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9576     if (Op == OO_New || Op == OO_Array_New) {
9577       const FunctionProtoType *Proto
9578         = FD->getType()->castAs<FunctionProtoType>();
9579       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9580           CheckNonNullExpr(*this, RetValExp))
9581         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9582           << FD << getLangOpts().CPlusPlus11;
9583     }
9584   }
9585 }
9586 
9587 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9588 
9589 /// Check for comparisons of floating point operands using != and ==.
9590 /// Issue a warning if these are no self-comparisons, as they are not likely
9591 /// to do what the programmer intended.
9592 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9593   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9594   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9595 
9596   // Special case: check for x == x (which is OK).
9597   // Do not emit warnings for such cases.
9598   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9599     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9600       if (DRL->getDecl() == DRR->getDecl())
9601         return;
9602 
9603   // Special case: check for comparisons against literals that can be exactly
9604   //  represented by APFloat.  In such cases, do not emit a warning.  This
9605   //  is a heuristic: often comparison against such literals are used to
9606   //  detect if a value in a variable has not changed.  This clearly can
9607   //  lead to false negatives.
9608   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9609     if (FLL->isExact())
9610       return;
9611   } else
9612     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9613       if (FLR->isExact())
9614         return;
9615 
9616   // Check for comparisons with builtin types.
9617   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9618     if (CL->getBuiltinCallee())
9619       return;
9620 
9621   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9622     if (CR->getBuiltinCallee())
9623       return;
9624 
9625   // Emit the diagnostic.
9626   Diag(Loc, diag::warn_floatingpoint_eq)
9627     << LHS->getSourceRange() << RHS->getSourceRange();
9628 }
9629 
9630 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9631 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9632 
9633 namespace {
9634 
9635 /// Structure recording the 'active' range of an integer-valued
9636 /// expression.
9637 struct IntRange {
9638   /// The number of bits active in the int.
9639   unsigned Width;
9640 
9641   /// True if the int is known not to have negative values.
9642   bool NonNegative;
9643 
9644   IntRange(unsigned Width, bool NonNegative)
9645       : Width(Width), NonNegative(NonNegative) {}
9646 
9647   /// Returns the range of the bool type.
9648   static IntRange forBoolType() {
9649     return IntRange(1, true);
9650   }
9651 
9652   /// Returns the range of an opaque value of the given integral type.
9653   static IntRange forValueOfType(ASTContext &C, QualType T) {
9654     return forValueOfCanonicalType(C,
9655                           T->getCanonicalTypeInternal().getTypePtr());
9656   }
9657 
9658   /// Returns the range of an opaque value of a canonical integral type.
9659   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9660     assert(T->isCanonicalUnqualified());
9661 
9662     if (const VectorType *VT = dyn_cast<VectorType>(T))
9663       T = VT->getElementType().getTypePtr();
9664     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9665       T = CT->getElementType().getTypePtr();
9666     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9667       T = AT->getValueType().getTypePtr();
9668 
9669     if (!C.getLangOpts().CPlusPlus) {
9670       // For enum types in C code, use the underlying datatype.
9671       if (const EnumType *ET = dyn_cast<EnumType>(T))
9672         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9673     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9674       // For enum types in C++, use the known bit width of the enumerators.
9675       EnumDecl *Enum = ET->getDecl();
9676       // In C++11, enums can have a fixed underlying type. Use this type to
9677       // compute the range.
9678       if (Enum->isFixed()) {
9679         return IntRange(C.getIntWidth(QualType(T, 0)),
9680                         !ET->isSignedIntegerOrEnumerationType());
9681       }
9682 
9683       unsigned NumPositive = Enum->getNumPositiveBits();
9684       unsigned NumNegative = Enum->getNumNegativeBits();
9685 
9686       if (NumNegative == 0)
9687         return IntRange(NumPositive, true/*NonNegative*/);
9688       else
9689         return IntRange(std::max(NumPositive + 1, NumNegative),
9690                         false/*NonNegative*/);
9691     }
9692 
9693     const BuiltinType *BT = cast<BuiltinType>(T);
9694     assert(BT->isInteger());
9695 
9696     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9697   }
9698 
9699   /// Returns the "target" range of a canonical integral type, i.e.
9700   /// the range of values expressible in the type.
9701   ///
9702   /// This matches forValueOfCanonicalType except that enums have the
9703   /// full range of their type, not the range of their enumerators.
9704   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9705     assert(T->isCanonicalUnqualified());
9706 
9707     if (const VectorType *VT = dyn_cast<VectorType>(T))
9708       T = VT->getElementType().getTypePtr();
9709     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9710       T = CT->getElementType().getTypePtr();
9711     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9712       T = AT->getValueType().getTypePtr();
9713     if (const EnumType *ET = dyn_cast<EnumType>(T))
9714       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9715 
9716     const BuiltinType *BT = cast<BuiltinType>(T);
9717     assert(BT->isInteger());
9718 
9719     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9720   }
9721 
9722   /// Returns the supremum of two ranges: i.e. their conservative merge.
9723   static IntRange join(IntRange L, IntRange R) {
9724     return IntRange(std::max(L.Width, R.Width),
9725                     L.NonNegative && R.NonNegative);
9726   }
9727 
9728   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9729   static IntRange meet(IntRange L, IntRange R) {
9730     return IntRange(std::min(L.Width, R.Width),
9731                     L.NonNegative || R.NonNegative);
9732   }
9733 };
9734 
9735 } // namespace
9736 
9737 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9738                               unsigned MaxWidth) {
9739   if (value.isSigned() && value.isNegative())
9740     return IntRange(value.getMinSignedBits(), false);
9741 
9742   if (value.getBitWidth() > MaxWidth)
9743     value = value.trunc(MaxWidth);
9744 
9745   // isNonNegative() just checks the sign bit without considering
9746   // signedness.
9747   return IntRange(value.getActiveBits(), true);
9748 }
9749 
9750 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9751                               unsigned MaxWidth) {
9752   if (result.isInt())
9753     return GetValueRange(C, result.getInt(), MaxWidth);
9754 
9755   if (result.isVector()) {
9756     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9757     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9758       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9759       R = IntRange::join(R, El);
9760     }
9761     return R;
9762   }
9763 
9764   if (result.isComplexInt()) {
9765     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9766     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9767     return IntRange::join(R, I);
9768   }
9769 
9770   // This can happen with lossless casts to intptr_t of "based" lvalues.
9771   // Assume it might use arbitrary bits.
9772   // FIXME: The only reason we need to pass the type in here is to get
9773   // the sign right on this one case.  It would be nice if APValue
9774   // preserved this.
9775   assert(result.isLValue() || result.isAddrLabelDiff());
9776   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9777 }
9778 
9779 static QualType GetExprType(const Expr *E) {
9780   QualType Ty = E->getType();
9781   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9782     Ty = AtomicRHS->getValueType();
9783   return Ty;
9784 }
9785 
9786 /// Pseudo-evaluate the given integer expression, estimating the
9787 /// range of values it might take.
9788 ///
9789 /// \param MaxWidth - the width to which the value will be truncated
9790 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9791   E = E->IgnoreParens();
9792 
9793   // Try a full evaluation first.
9794   Expr::EvalResult result;
9795   if (E->EvaluateAsRValue(result, C))
9796     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9797 
9798   // I think we only want to look through implicit casts here; if the
9799   // user has an explicit widening cast, we should treat the value as
9800   // being of the new, wider type.
9801   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9802     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9803       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9804 
9805     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9806 
9807     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9808                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9809 
9810     // Assume that non-integer casts can span the full range of the type.
9811     if (!isIntegerCast)
9812       return OutputTypeRange;
9813 
9814     IntRange SubRange
9815       = GetExprRange(C, CE->getSubExpr(),
9816                      std::min(MaxWidth, OutputTypeRange.Width));
9817 
9818     // Bail out if the subexpr's range is as wide as the cast type.
9819     if (SubRange.Width >= OutputTypeRange.Width)
9820       return OutputTypeRange;
9821 
9822     // Otherwise, we take the smaller width, and we're non-negative if
9823     // either the output type or the subexpr is.
9824     return IntRange(SubRange.Width,
9825                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9826   }
9827 
9828   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9829     // If we can fold the condition, just take that operand.
9830     bool CondResult;
9831     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9832       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9833                                         : CO->getFalseExpr(),
9834                           MaxWidth);
9835 
9836     // Otherwise, conservatively merge.
9837     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9838     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9839     return IntRange::join(L, R);
9840   }
9841 
9842   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9843     switch (BO->getOpcode()) {
9844     case BO_Cmp:
9845       llvm_unreachable("builtin <=> should have class type");
9846 
9847     // Boolean-valued operations are single-bit and positive.
9848     case BO_LAnd:
9849     case BO_LOr:
9850     case BO_LT:
9851     case BO_GT:
9852     case BO_LE:
9853     case BO_GE:
9854     case BO_EQ:
9855     case BO_NE:
9856       return IntRange::forBoolType();
9857 
9858     // The type of the assignments is the type of the LHS, so the RHS
9859     // is not necessarily the same type.
9860     case BO_MulAssign:
9861     case BO_DivAssign:
9862     case BO_RemAssign:
9863     case BO_AddAssign:
9864     case BO_SubAssign:
9865     case BO_XorAssign:
9866     case BO_OrAssign:
9867       // TODO: bitfields?
9868       return IntRange::forValueOfType(C, GetExprType(E));
9869 
9870     // Simple assignments just pass through the RHS, which will have
9871     // been coerced to the LHS type.
9872     case BO_Assign:
9873       // TODO: bitfields?
9874       return GetExprRange(C, BO->getRHS(), MaxWidth);
9875 
9876     // Operations with opaque sources are black-listed.
9877     case BO_PtrMemD:
9878     case BO_PtrMemI:
9879       return IntRange::forValueOfType(C, GetExprType(E));
9880 
9881     // Bitwise-and uses the *infinum* of the two source ranges.
9882     case BO_And:
9883     case BO_AndAssign:
9884       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9885                             GetExprRange(C, BO->getRHS(), MaxWidth));
9886 
9887     // Left shift gets black-listed based on a judgement call.
9888     case BO_Shl:
9889       // ...except that we want to treat '1 << (blah)' as logically
9890       // positive.  It's an important idiom.
9891       if (IntegerLiteral *I
9892             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9893         if (I->getValue() == 1) {
9894           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9895           return IntRange(R.Width, /*NonNegative*/ true);
9896         }
9897       }
9898       LLVM_FALLTHROUGH;
9899 
9900     case BO_ShlAssign:
9901       return IntRange::forValueOfType(C, GetExprType(E));
9902 
9903     // Right shift by a constant can narrow its left argument.
9904     case BO_Shr:
9905     case BO_ShrAssign: {
9906       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9907 
9908       // If the shift amount is a positive constant, drop the width by
9909       // that much.
9910       llvm::APSInt shift;
9911       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9912           shift.isNonNegative()) {
9913         unsigned zext = shift.getZExtValue();
9914         if (zext >= L.Width)
9915           L.Width = (L.NonNegative ? 0 : 1);
9916         else
9917           L.Width -= zext;
9918       }
9919 
9920       return L;
9921     }
9922 
9923     // Comma acts as its right operand.
9924     case BO_Comma:
9925       return GetExprRange(C, BO->getRHS(), MaxWidth);
9926 
9927     // Black-list pointer subtractions.
9928     case BO_Sub:
9929       if (BO->getLHS()->getType()->isPointerType())
9930         return IntRange::forValueOfType(C, GetExprType(E));
9931       break;
9932 
9933     // The width of a division result is mostly determined by the size
9934     // of the LHS.
9935     case BO_Div: {
9936       // Don't 'pre-truncate' the operands.
9937       unsigned opWidth = C.getIntWidth(GetExprType(E));
9938       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9939 
9940       // If the divisor is constant, use that.
9941       llvm::APSInt divisor;
9942       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9943         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9944         if (log2 >= L.Width)
9945           L.Width = (L.NonNegative ? 0 : 1);
9946         else
9947           L.Width = std::min(L.Width - log2, MaxWidth);
9948         return L;
9949       }
9950 
9951       // Otherwise, just use the LHS's width.
9952       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9953       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9954     }
9955 
9956     // The result of a remainder can't be larger than the result of
9957     // either side.
9958     case BO_Rem: {
9959       // Don't 'pre-truncate' the operands.
9960       unsigned opWidth = C.getIntWidth(GetExprType(E));
9961       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9962       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9963 
9964       IntRange meet = IntRange::meet(L, R);
9965       meet.Width = std::min(meet.Width, MaxWidth);
9966       return meet;
9967     }
9968 
9969     // The default behavior is okay for these.
9970     case BO_Mul:
9971     case BO_Add:
9972     case BO_Xor:
9973     case BO_Or:
9974       break;
9975     }
9976 
9977     // The default case is to treat the operation as if it were closed
9978     // on the narrowest type that encompasses both operands.
9979     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9980     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9981     return IntRange::join(L, R);
9982   }
9983 
9984   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9985     switch (UO->getOpcode()) {
9986     // Boolean-valued operations are white-listed.
9987     case UO_LNot:
9988       return IntRange::forBoolType();
9989 
9990     // Operations with opaque sources are black-listed.
9991     case UO_Deref:
9992     case UO_AddrOf: // should be impossible
9993       return IntRange::forValueOfType(C, GetExprType(E));
9994 
9995     default:
9996       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9997     }
9998   }
9999 
10000   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10001     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
10002 
10003   if (const auto *BitField = E->getSourceBitField())
10004     return IntRange(BitField->getBitWidthValue(C),
10005                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10006 
10007   return IntRange::forValueOfType(C, GetExprType(E));
10008 }
10009 
10010 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
10011   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
10012 }
10013 
10014 /// Checks whether the given value, which currently has the given
10015 /// source semantics, has the same value when coerced through the
10016 /// target semantics.
10017 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10018                                  const llvm::fltSemantics &Src,
10019                                  const llvm::fltSemantics &Tgt) {
10020   llvm::APFloat truncated = value;
10021 
10022   bool ignored;
10023   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10024   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10025 
10026   return truncated.bitwiseIsEqual(value);
10027 }
10028 
10029 /// Checks whether the given value, which currently has the given
10030 /// source semantics, has the same value when coerced through the
10031 /// target semantics.
10032 ///
10033 /// The value might be a vector of floats (or a complex number).
10034 static bool IsSameFloatAfterCast(const APValue &value,
10035                                  const llvm::fltSemantics &Src,
10036                                  const llvm::fltSemantics &Tgt) {
10037   if (value.isFloat())
10038     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10039 
10040   if (value.isVector()) {
10041     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10042       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10043         return false;
10044     return true;
10045   }
10046 
10047   assert(value.isComplexFloat());
10048   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10049           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10050 }
10051 
10052 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
10053 
10054 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10055   // Suppress cases where we are comparing against an enum constant.
10056   if (const DeclRefExpr *DR =
10057       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10058     if (isa<EnumConstantDecl>(DR->getDecl()))
10059       return true;
10060 
10061   // Suppress cases where the '0' value is expanded from a macro.
10062   if (E->getLocStart().isMacroID())
10063     return true;
10064 
10065   return false;
10066 }
10067 
10068 static bool isKnownToHaveUnsignedValue(Expr *E) {
10069   return E->getType()->isIntegerType() &&
10070          (!E->getType()->isSignedIntegerType() ||
10071           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10072 }
10073 
10074 namespace {
10075 /// The promoted range of values of a type. In general this has the
10076 /// following structure:
10077 ///
10078 ///     |-----------| . . . |-----------|
10079 ///     ^           ^       ^           ^
10080 ///    Min       HoleMin  HoleMax      Max
10081 ///
10082 /// ... where there is only a hole if a signed type is promoted to unsigned
10083 /// (in which case Min and Max are the smallest and largest representable
10084 /// values).
10085 struct PromotedRange {
10086   // Min, or HoleMax if there is a hole.
10087   llvm::APSInt PromotedMin;
10088   // Max, or HoleMin if there is a hole.
10089   llvm::APSInt PromotedMax;
10090 
10091   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10092     if (R.Width == 0)
10093       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10094     else if (R.Width >= BitWidth && !Unsigned) {
10095       // Promotion made the type *narrower*. This happens when promoting
10096       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10097       // Treat all values of 'signed int' as being in range for now.
10098       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10099       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10100     } else {
10101       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10102                         .extOrTrunc(BitWidth);
10103       PromotedMin.setIsUnsigned(Unsigned);
10104 
10105       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10106                         .extOrTrunc(BitWidth);
10107       PromotedMax.setIsUnsigned(Unsigned);
10108     }
10109   }
10110 
10111   // Determine whether this range is contiguous (has no hole).
10112   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10113 
10114   // Where a constant value is within the range.
10115   enum ComparisonResult {
10116     LT = 0x1,
10117     LE = 0x2,
10118     GT = 0x4,
10119     GE = 0x8,
10120     EQ = 0x10,
10121     NE = 0x20,
10122     InRangeFlag = 0x40,
10123 
10124     Less = LE | LT | NE,
10125     Min = LE | InRangeFlag,
10126     InRange = InRangeFlag,
10127     Max = GE | InRangeFlag,
10128     Greater = GE | GT | NE,
10129 
10130     OnlyValue = LE | GE | EQ | InRangeFlag,
10131     InHole = NE
10132   };
10133 
10134   ComparisonResult compare(const llvm::APSInt &Value) const {
10135     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10136            Value.isUnsigned() == PromotedMin.isUnsigned());
10137     if (!isContiguous()) {
10138       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10139       if (Value.isMinValue()) return Min;
10140       if (Value.isMaxValue()) return Max;
10141       if (Value >= PromotedMin) return InRange;
10142       if (Value <= PromotedMax) return InRange;
10143       return InHole;
10144     }
10145 
10146     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10147     case -1: return Less;
10148     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10149     case 1:
10150       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10151       case -1: return InRange;
10152       case 0: return Max;
10153       case 1: return Greater;
10154       }
10155     }
10156 
10157     llvm_unreachable("impossible compare result");
10158   }
10159 
10160   static llvm::Optional<StringRef>
10161   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10162     if (Op == BO_Cmp) {
10163       ComparisonResult LTFlag = LT, GTFlag = GT;
10164       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10165 
10166       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10167       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10168       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10169       return llvm::None;
10170     }
10171 
10172     ComparisonResult TrueFlag, FalseFlag;
10173     if (Op == BO_EQ) {
10174       TrueFlag = EQ;
10175       FalseFlag = NE;
10176     } else if (Op == BO_NE) {
10177       TrueFlag = NE;
10178       FalseFlag = EQ;
10179     } else {
10180       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10181         TrueFlag = LT;
10182         FalseFlag = GE;
10183       } else {
10184         TrueFlag = GT;
10185         FalseFlag = LE;
10186       }
10187       if (Op == BO_GE || Op == BO_LE)
10188         std::swap(TrueFlag, FalseFlag);
10189     }
10190     if (R & TrueFlag)
10191       return StringRef("true");
10192     if (R & FalseFlag)
10193       return StringRef("false");
10194     return llvm::None;
10195   }
10196 };
10197 }
10198 
10199 static bool HasEnumType(Expr *E) {
10200   // Strip off implicit integral promotions.
10201   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10202     if (ICE->getCastKind() != CK_IntegralCast &&
10203         ICE->getCastKind() != CK_NoOp)
10204       break;
10205     E = ICE->getSubExpr();
10206   }
10207 
10208   return E->getType()->isEnumeralType();
10209 }
10210 
10211 static int classifyConstantValue(Expr *Constant) {
10212   // The values of this enumeration are used in the diagnostics
10213   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10214   enum ConstantValueKind {
10215     Miscellaneous = 0,
10216     LiteralTrue,
10217     LiteralFalse
10218   };
10219   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10220     return BL->getValue() ? ConstantValueKind::LiteralTrue
10221                           : ConstantValueKind::LiteralFalse;
10222   return ConstantValueKind::Miscellaneous;
10223 }
10224 
10225 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10226                                         Expr *Constant, Expr *Other,
10227                                         const llvm::APSInt &Value,
10228                                         bool RhsConstant) {
10229   if (S.inTemplateInstantiation())
10230     return false;
10231 
10232   Expr *OriginalOther = Other;
10233 
10234   Constant = Constant->IgnoreParenImpCasts();
10235   Other = Other->IgnoreParenImpCasts();
10236 
10237   // Suppress warnings on tautological comparisons between values of the same
10238   // enumeration type. There are only two ways we could warn on this:
10239   //  - If the constant is outside the range of representable values of
10240   //    the enumeration. In such a case, we should warn about the cast
10241   //    to enumeration type, not about the comparison.
10242   //  - If the constant is the maximum / minimum in-range value. For an
10243   //    enumeratin type, such comparisons can be meaningful and useful.
10244   if (Constant->getType()->isEnumeralType() &&
10245       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10246     return false;
10247 
10248   // TODO: Investigate using GetExprRange() to get tighter bounds
10249   // on the bit ranges.
10250   QualType OtherT = Other->getType();
10251   if (const auto *AT = OtherT->getAs<AtomicType>())
10252     OtherT = AT->getValueType();
10253   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10254 
10255   // Whether we're treating Other as being a bool because of the form of
10256   // expression despite it having another type (typically 'int' in C).
10257   bool OtherIsBooleanDespiteType =
10258       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10259   if (OtherIsBooleanDespiteType)
10260     OtherRange = IntRange::forBoolType();
10261 
10262   // Determine the promoted range of the other type and see if a comparison of
10263   // the constant against that range is tautological.
10264   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10265                                    Value.isUnsigned());
10266   auto Cmp = OtherPromotedRange.compare(Value);
10267   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10268   if (!Result)
10269     return false;
10270 
10271   // Suppress the diagnostic for an in-range comparison if the constant comes
10272   // from a macro or enumerator. We don't want to diagnose
10273   //
10274   //   some_long_value <= INT_MAX
10275   //
10276   // when sizeof(int) == sizeof(long).
10277   bool InRange = Cmp & PromotedRange::InRangeFlag;
10278   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10279     return false;
10280 
10281   // If this is a comparison to an enum constant, include that
10282   // constant in the diagnostic.
10283   const EnumConstantDecl *ED = nullptr;
10284   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10285     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10286 
10287   // Should be enough for uint128 (39 decimal digits)
10288   SmallString<64> PrettySourceValue;
10289   llvm::raw_svector_ostream OS(PrettySourceValue);
10290   if (ED)
10291     OS << '\'' << *ED << "' (" << Value << ")";
10292   else
10293     OS << Value;
10294 
10295   // FIXME: We use a somewhat different formatting for the in-range cases and
10296   // cases involving boolean values for historical reasons. We should pick a
10297   // consistent way of presenting these diagnostics.
10298   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10299     S.DiagRuntimeBehavior(
10300       E->getOperatorLoc(), E,
10301       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10302                        : diag::warn_tautological_bool_compare)
10303           << OS.str() << classifyConstantValue(Constant)
10304           << OtherT << OtherIsBooleanDespiteType << *Result
10305           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10306   } else {
10307     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10308                         ? (HasEnumType(OriginalOther)
10309                                ? diag::warn_unsigned_enum_always_true_comparison
10310                                : diag::warn_unsigned_always_true_comparison)
10311                         : diag::warn_tautological_constant_compare;
10312 
10313     S.Diag(E->getOperatorLoc(), Diag)
10314         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10315         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10316   }
10317 
10318   return true;
10319 }
10320 
10321 /// Analyze the operands of the given comparison.  Implements the
10322 /// fallback case from AnalyzeComparison.
10323 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10324   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10325   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10326 }
10327 
10328 /// Implements -Wsign-compare.
10329 ///
10330 /// \param E the binary operator to check for warnings
10331 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10332   // The type the comparison is being performed in.
10333   QualType T = E->getLHS()->getType();
10334 
10335   // Only analyze comparison operators where both sides have been converted to
10336   // the same type.
10337   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10338     return AnalyzeImpConvsInComparison(S, E);
10339 
10340   // Don't analyze value-dependent comparisons directly.
10341   if (E->isValueDependent())
10342     return AnalyzeImpConvsInComparison(S, E);
10343 
10344   Expr *LHS = E->getLHS();
10345   Expr *RHS = E->getRHS();
10346 
10347   if (T->isIntegralType(S.Context)) {
10348     llvm::APSInt RHSValue;
10349     llvm::APSInt LHSValue;
10350 
10351     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10352     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10353 
10354     // We don't care about expressions whose result is a constant.
10355     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10356       return AnalyzeImpConvsInComparison(S, E);
10357 
10358     // We only care about expressions where just one side is literal
10359     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10360       // Is the constant on the RHS or LHS?
10361       const bool RhsConstant = IsRHSIntegralLiteral;
10362       Expr *Const = RhsConstant ? RHS : LHS;
10363       Expr *Other = RhsConstant ? LHS : RHS;
10364       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10365 
10366       // Check whether an integer constant comparison results in a value
10367       // of 'true' or 'false'.
10368       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10369         return AnalyzeImpConvsInComparison(S, E);
10370     }
10371   }
10372 
10373   if (!T->hasUnsignedIntegerRepresentation()) {
10374     // We don't do anything special if this isn't an unsigned integral
10375     // comparison:  we're only interested in integral comparisons, and
10376     // signed comparisons only happen in cases we don't care to warn about.
10377     return AnalyzeImpConvsInComparison(S, E);
10378   }
10379 
10380   LHS = LHS->IgnoreParenImpCasts();
10381   RHS = RHS->IgnoreParenImpCasts();
10382 
10383   if (!S.getLangOpts().CPlusPlus) {
10384     // Avoid warning about comparison of integers with different signs when
10385     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10386     // the type of `E`.
10387     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10388       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10389     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10390       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10391   }
10392 
10393   // Check to see if one of the (unmodified) operands is of different
10394   // signedness.
10395   Expr *signedOperand, *unsignedOperand;
10396   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10397     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10398            "unsigned comparison between two signed integer expressions?");
10399     signedOperand = LHS;
10400     unsignedOperand = RHS;
10401   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10402     signedOperand = RHS;
10403     unsignedOperand = LHS;
10404   } else {
10405     return AnalyzeImpConvsInComparison(S, E);
10406   }
10407 
10408   // Otherwise, calculate the effective range of the signed operand.
10409   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10410 
10411   // Go ahead and analyze implicit conversions in the operands.  Note
10412   // that we skip the implicit conversions on both sides.
10413   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10414   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10415 
10416   // If the signed range is non-negative, -Wsign-compare won't fire.
10417   if (signedRange.NonNegative)
10418     return;
10419 
10420   // For (in)equality comparisons, if the unsigned operand is a
10421   // constant which cannot collide with a overflowed signed operand,
10422   // then reinterpreting the signed operand as unsigned will not
10423   // change the result of the comparison.
10424   if (E->isEqualityOp()) {
10425     unsigned comparisonWidth = S.Context.getIntWidth(T);
10426     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10427 
10428     // We should never be unable to prove that the unsigned operand is
10429     // non-negative.
10430     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10431 
10432     if (unsignedRange.Width < comparisonWidth)
10433       return;
10434   }
10435 
10436   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10437     S.PDiag(diag::warn_mixed_sign_comparison)
10438       << LHS->getType() << RHS->getType()
10439       << LHS->getSourceRange() << RHS->getSourceRange());
10440 }
10441 
10442 /// Analyzes an attempt to assign the given value to a bitfield.
10443 ///
10444 /// Returns true if there was something fishy about the attempt.
10445 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10446                                       SourceLocation InitLoc) {
10447   assert(Bitfield->isBitField());
10448   if (Bitfield->isInvalidDecl())
10449     return false;
10450 
10451   // White-list bool bitfields.
10452   QualType BitfieldType = Bitfield->getType();
10453   if (BitfieldType->isBooleanType())
10454      return false;
10455 
10456   if (BitfieldType->isEnumeralType()) {
10457     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10458     // If the underlying enum type was not explicitly specified as an unsigned
10459     // type and the enum contain only positive values, MSVC++ will cause an
10460     // inconsistency by storing this as a signed type.
10461     if (S.getLangOpts().CPlusPlus11 &&
10462         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10463         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10464         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10465       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10466         << BitfieldEnumDecl->getNameAsString();
10467     }
10468   }
10469 
10470   if (Bitfield->getType()->isBooleanType())
10471     return false;
10472 
10473   // Ignore value- or type-dependent expressions.
10474   if (Bitfield->getBitWidth()->isValueDependent() ||
10475       Bitfield->getBitWidth()->isTypeDependent() ||
10476       Init->isValueDependent() ||
10477       Init->isTypeDependent())
10478     return false;
10479 
10480   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10481   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10482 
10483   llvm::APSInt Value;
10484   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
10485                                    Expr::SE_AllowSideEffects)) {
10486     // The RHS is not constant.  If the RHS has an enum type, make sure the
10487     // bitfield is wide enough to hold all the values of the enum without
10488     // truncation.
10489     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10490       EnumDecl *ED = EnumTy->getDecl();
10491       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10492 
10493       // Enum types are implicitly signed on Windows, so check if there are any
10494       // negative enumerators to see if the enum was intended to be signed or
10495       // not.
10496       bool SignedEnum = ED->getNumNegativeBits() > 0;
10497 
10498       // Check for surprising sign changes when assigning enum values to a
10499       // bitfield of different signedness.  If the bitfield is signed and we
10500       // have exactly the right number of bits to store this unsigned enum,
10501       // suggest changing the enum to an unsigned type. This typically happens
10502       // on Windows where unfixed enums always use an underlying type of 'int'.
10503       unsigned DiagID = 0;
10504       if (SignedEnum && !SignedBitfield) {
10505         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10506       } else if (SignedBitfield && !SignedEnum &&
10507                  ED->getNumPositiveBits() == FieldWidth) {
10508         DiagID = diag::warn_signed_bitfield_enum_conversion;
10509       }
10510 
10511       if (DiagID) {
10512         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10513         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10514         SourceRange TypeRange =
10515             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10516         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10517             << SignedEnum << TypeRange;
10518       }
10519 
10520       // Compute the required bitwidth. If the enum has negative values, we need
10521       // one more bit than the normal number of positive bits to represent the
10522       // sign bit.
10523       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10524                                                   ED->getNumNegativeBits())
10525                                        : ED->getNumPositiveBits();
10526 
10527       // Check the bitwidth.
10528       if (BitsNeeded > FieldWidth) {
10529         Expr *WidthExpr = Bitfield->getBitWidth();
10530         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10531             << Bitfield << ED;
10532         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10533             << BitsNeeded << ED << WidthExpr->getSourceRange();
10534       }
10535     }
10536 
10537     return false;
10538   }
10539 
10540   unsigned OriginalWidth = Value.getBitWidth();
10541 
10542   if (!Value.isSigned() || Value.isNegative())
10543     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10544       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10545         OriginalWidth = Value.getMinSignedBits();
10546 
10547   if (OriginalWidth <= FieldWidth)
10548     return false;
10549 
10550   // Compute the value which the bitfield will contain.
10551   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10552   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10553 
10554   // Check whether the stored value is equal to the original value.
10555   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10556   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10557     return false;
10558 
10559   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10560   // therefore don't strictly fit into a signed bitfield of width 1.
10561   if (FieldWidth == 1 && Value == 1)
10562     return false;
10563 
10564   std::string PrettyValue = Value.toString(10);
10565   std::string PrettyTrunc = TruncatedValue.toString(10);
10566 
10567   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10568     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10569     << Init->getSourceRange();
10570 
10571   return true;
10572 }
10573 
10574 /// Analyze the given simple or compound assignment for warning-worthy
10575 /// operations.
10576 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10577   // Just recurse on the LHS.
10578   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10579 
10580   // We want to recurse on the RHS as normal unless we're assigning to
10581   // a bitfield.
10582   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10583     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10584                                   E->getOperatorLoc())) {
10585       // Recurse, ignoring any implicit conversions on the RHS.
10586       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10587                                         E->getOperatorLoc());
10588     }
10589   }
10590 
10591   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10592 }
10593 
10594 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10595 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10596                             SourceLocation CContext, unsigned diag,
10597                             bool pruneControlFlow = false) {
10598   if (pruneControlFlow) {
10599     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10600                           S.PDiag(diag)
10601                             << SourceType << T << E->getSourceRange()
10602                             << SourceRange(CContext));
10603     return;
10604   }
10605   S.Diag(E->getExprLoc(), diag)
10606     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10607 }
10608 
10609 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10610 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10611                             SourceLocation CContext,
10612                             unsigned diag, bool pruneControlFlow = false) {
10613   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10614 }
10615 
10616 /// Analyze the given compound assignment for the possible losing of
10617 /// floating-point precision.
10618 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10619   assert(isa<CompoundAssignOperator>(E) &&
10620          "Must be compound assignment operation");
10621   // Recurse on the LHS and RHS in here
10622   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10623   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10624 
10625   // Now check the outermost expression
10626   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10627   const auto *RBT = cast<CompoundAssignOperator>(E)
10628                         ->getComputationResultType()
10629                         ->getAs<BuiltinType>();
10630 
10631   // If both source and target are floating points.
10632   if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
10633     // Builtin FP kinds are ordered by increasing FP rank.
10634     if (ResultBT->getKind() < RBT->getKind())
10635       // We don't want to warn for system macro.
10636       if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10637         // warn about dropping FP rank.
10638         DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
10639                         E->getOperatorLoc(),
10640                         diag::warn_impcast_float_result_precision);
10641 }
10642 
10643 /// Diagnose an implicit cast from a floating point value to an integer value.
10644 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10645                                     SourceLocation CContext) {
10646   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10647   const bool PruneWarnings = S.inTemplateInstantiation();
10648 
10649   Expr *InnerE = E->IgnoreParenImpCasts();
10650   // We also want to warn on, e.g., "int i = -1.234"
10651   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10652     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10653       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10654 
10655   const bool IsLiteral =
10656       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10657 
10658   llvm::APFloat Value(0.0);
10659   bool IsConstant =
10660     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10661   if (!IsConstant) {
10662     return DiagnoseImpCast(S, E, T, CContext,
10663                            diag::warn_impcast_float_integer, PruneWarnings);
10664   }
10665 
10666   bool isExact = false;
10667 
10668   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10669                             T->hasUnsignedIntegerRepresentation());
10670   llvm::APFloat::opStatus Result = Value.convertToInteger(
10671       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10672 
10673   if (Result == llvm::APFloat::opOK && isExact) {
10674     if (IsLiteral) return;
10675     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10676                            PruneWarnings);
10677   }
10678 
10679   // Conversion of a floating-point value to a non-bool integer where the
10680   // integral part cannot be represented by the integer type is undefined.
10681   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10682     return DiagnoseImpCast(
10683         S, E, T, CContext,
10684         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10685                   : diag::warn_impcast_float_to_integer_out_of_range,
10686         PruneWarnings);
10687 
10688   unsigned DiagID = 0;
10689   if (IsLiteral) {
10690     // Warn on floating point literal to integer.
10691     DiagID = diag::warn_impcast_literal_float_to_integer;
10692   } else if (IntegerValue == 0) {
10693     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10694       return DiagnoseImpCast(S, E, T, CContext,
10695                              diag::warn_impcast_float_integer, PruneWarnings);
10696     }
10697     // Warn on non-zero to zero conversion.
10698     DiagID = diag::warn_impcast_float_to_integer_zero;
10699   } else {
10700     if (IntegerValue.isUnsigned()) {
10701       if (!IntegerValue.isMaxValue()) {
10702         return DiagnoseImpCast(S, E, T, CContext,
10703                                diag::warn_impcast_float_integer, PruneWarnings);
10704       }
10705     } else {  // IntegerValue.isSigned()
10706       if (!IntegerValue.isMaxSignedValue() &&
10707           !IntegerValue.isMinSignedValue()) {
10708         return DiagnoseImpCast(S, E, T, CContext,
10709                                diag::warn_impcast_float_integer, PruneWarnings);
10710       }
10711     }
10712     // Warn on evaluatable floating point expression to integer conversion.
10713     DiagID = diag::warn_impcast_float_to_integer;
10714   }
10715 
10716   // FIXME: Force the precision of the source value down so we don't print
10717   // digits which are usually useless (we don't really care here if we
10718   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10719   // would automatically print the shortest representation, but it's a bit
10720   // tricky to implement.
10721   SmallString<16> PrettySourceValue;
10722   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10723   precision = (precision * 59 + 195) / 196;
10724   Value.toString(PrettySourceValue, precision);
10725 
10726   SmallString<16> PrettyTargetValue;
10727   if (IsBool)
10728     PrettyTargetValue = Value.isZero() ? "false" : "true";
10729   else
10730     IntegerValue.toString(PrettyTargetValue);
10731 
10732   if (PruneWarnings) {
10733     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10734                           S.PDiag(DiagID)
10735                               << E->getType() << T.getUnqualifiedType()
10736                               << PrettySourceValue << PrettyTargetValue
10737                               << E->getSourceRange() << SourceRange(CContext));
10738   } else {
10739     S.Diag(E->getExprLoc(), DiagID)
10740         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10741         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10742   }
10743 }
10744 
10745 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10746                                       IntRange Range) {
10747   if (!Range.Width) return "0";
10748 
10749   llvm::APSInt ValueInRange = Value;
10750   ValueInRange.setIsSigned(!Range.NonNegative);
10751   ValueInRange = ValueInRange.trunc(Range.Width);
10752   return ValueInRange.toString(10);
10753 }
10754 
10755 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10756   if (!isa<ImplicitCastExpr>(Ex))
10757     return false;
10758 
10759   Expr *InnerE = Ex->IgnoreParenImpCasts();
10760   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10761   const Type *Source =
10762     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10763   if (Target->isDependentType())
10764     return false;
10765 
10766   const BuiltinType *FloatCandidateBT =
10767     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10768   const Type *BoolCandidateType = ToBool ? Target : Source;
10769 
10770   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10771           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10772 }
10773 
10774 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10775                                              SourceLocation CC) {
10776   unsigned NumArgs = TheCall->getNumArgs();
10777   for (unsigned i = 0; i < NumArgs; ++i) {
10778     Expr *CurrA = TheCall->getArg(i);
10779     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10780       continue;
10781 
10782     bool IsSwapped = ((i > 0) &&
10783         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10784     IsSwapped |= ((i < (NumArgs - 1)) &&
10785         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10786     if (IsSwapped) {
10787       // Warn on this floating-point to bool conversion.
10788       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10789                       CurrA->getType(), CC,
10790                       diag::warn_impcast_floating_point_to_bool);
10791     }
10792   }
10793 }
10794 
10795 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10796                                    SourceLocation CC) {
10797   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10798                         E->getExprLoc()))
10799     return;
10800 
10801   // Don't warn on functions which have return type nullptr_t.
10802   if (isa<CallExpr>(E))
10803     return;
10804 
10805   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10806   const Expr::NullPointerConstantKind NullKind =
10807       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10808   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10809     return;
10810 
10811   // Return if target type is a safe conversion.
10812   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10813       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10814     return;
10815 
10816   SourceLocation Loc = E->getSourceRange().getBegin();
10817 
10818   // Venture through the macro stacks to get to the source of macro arguments.
10819   // The new location is a better location than the complete location that was
10820   // passed in.
10821   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10822   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10823 
10824   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10825   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10826     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10827         Loc, S.SourceMgr, S.getLangOpts());
10828     if (MacroName == "NULL")
10829       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10830   }
10831 
10832   // Only warn if the null and context location are in the same macro expansion.
10833   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10834     return;
10835 
10836   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10837       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10838       << FixItHint::CreateReplacement(Loc,
10839                                       S.getFixItZeroLiteralForType(T, Loc));
10840 }
10841 
10842 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10843                                   ObjCArrayLiteral *ArrayLiteral);
10844 
10845 static void
10846 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10847                            ObjCDictionaryLiteral *DictionaryLiteral);
10848 
10849 /// Check a single element within a collection literal against the
10850 /// target element type.
10851 static void checkObjCCollectionLiteralElement(Sema &S,
10852                                               QualType TargetElementType,
10853                                               Expr *Element,
10854                                               unsigned ElementKind) {
10855   // Skip a bitcast to 'id' or qualified 'id'.
10856   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10857     if (ICE->getCastKind() == CK_BitCast &&
10858         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10859       Element = ICE->getSubExpr();
10860   }
10861 
10862   QualType ElementType = Element->getType();
10863   ExprResult ElementResult(Element);
10864   if (ElementType->getAs<ObjCObjectPointerType>() &&
10865       S.CheckSingleAssignmentConstraints(TargetElementType,
10866                                          ElementResult,
10867                                          false, false)
10868         != Sema::Compatible) {
10869     S.Diag(Element->getLocStart(),
10870            diag::warn_objc_collection_literal_element)
10871       << ElementType << ElementKind << TargetElementType
10872       << Element->getSourceRange();
10873   }
10874 
10875   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10876     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10877   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10878     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10879 }
10880 
10881 /// Check an Objective-C array literal being converted to the given
10882 /// target type.
10883 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10884                                   ObjCArrayLiteral *ArrayLiteral) {
10885   if (!S.NSArrayDecl)
10886     return;
10887 
10888   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10889   if (!TargetObjCPtr)
10890     return;
10891 
10892   if (TargetObjCPtr->isUnspecialized() ||
10893       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10894         != S.NSArrayDecl->getCanonicalDecl())
10895     return;
10896 
10897   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10898   if (TypeArgs.size() != 1)
10899     return;
10900 
10901   QualType TargetElementType = TypeArgs[0];
10902   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10903     checkObjCCollectionLiteralElement(S, TargetElementType,
10904                                       ArrayLiteral->getElement(I),
10905                                       0);
10906   }
10907 }
10908 
10909 /// Check an Objective-C dictionary literal being converted to the given
10910 /// target type.
10911 static void
10912 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10913                            ObjCDictionaryLiteral *DictionaryLiteral) {
10914   if (!S.NSDictionaryDecl)
10915     return;
10916 
10917   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10918   if (!TargetObjCPtr)
10919     return;
10920 
10921   if (TargetObjCPtr->isUnspecialized() ||
10922       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10923         != S.NSDictionaryDecl->getCanonicalDecl())
10924     return;
10925 
10926   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10927   if (TypeArgs.size() != 2)
10928     return;
10929 
10930   QualType TargetKeyType = TypeArgs[0];
10931   QualType TargetObjectType = TypeArgs[1];
10932   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10933     auto Element = DictionaryLiteral->getKeyValueElement(I);
10934     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10935     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10936   }
10937 }
10938 
10939 // Helper function to filter out cases for constant width constant conversion.
10940 // Don't warn on char array initialization or for non-decimal values.
10941 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10942                                           SourceLocation CC) {
10943   // If initializing from a constant, and the constant starts with '0',
10944   // then it is a binary, octal, or hexadecimal.  Allow these constants
10945   // to fill all the bits, even if there is a sign change.
10946   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10947     const char FirstLiteralCharacter =
10948         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10949     if (FirstLiteralCharacter == '0')
10950       return false;
10951   }
10952 
10953   // If the CC location points to a '{', and the type is char, then assume
10954   // assume it is an array initialization.
10955   if (CC.isValid() && T->isCharType()) {
10956     const char FirstContextCharacter =
10957         S.getSourceManager().getCharacterData(CC)[0];
10958     if (FirstContextCharacter == '{')
10959       return false;
10960   }
10961 
10962   return true;
10963 }
10964 
10965 static void
10966 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10967                         bool *ICContext = nullptr) {
10968   if (E->isTypeDependent() || E->isValueDependent()) return;
10969 
10970   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10971   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10972   if (Source == Target) return;
10973   if (Target->isDependentType()) return;
10974 
10975   // If the conversion context location is invalid don't complain. We also
10976   // don't want to emit a warning if the issue occurs from the expansion of
10977   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10978   // delay this check as long as possible. Once we detect we are in that
10979   // scenario, we just return.
10980   if (CC.isInvalid())
10981     return;
10982 
10983   // Diagnose implicit casts to bool.
10984   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10985     if (isa<StringLiteral>(E))
10986       // Warn on string literal to bool.  Checks for string literals in logical
10987       // and expressions, for instance, assert(0 && "error here"), are
10988       // prevented by a check in AnalyzeImplicitConversions().
10989       return DiagnoseImpCast(S, E, T, CC,
10990                              diag::warn_impcast_string_literal_to_bool);
10991     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10992         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10993       // This covers the literal expressions that evaluate to Objective-C
10994       // objects.
10995       return DiagnoseImpCast(S, E, T, CC,
10996                              diag::warn_impcast_objective_c_literal_to_bool);
10997     }
10998     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10999       // Warn on pointer to bool conversion that is always true.
11000       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11001                                      SourceRange(CC));
11002     }
11003   }
11004 
11005   // Check implicit casts from Objective-C collection literals to specialized
11006   // collection types, e.g., NSArray<NSString *> *.
11007   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11008     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11009   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11010     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11011 
11012   // Strip vector types.
11013   if (isa<VectorType>(Source)) {
11014     if (!isa<VectorType>(Target)) {
11015       if (S.SourceMgr.isInSystemMacro(CC))
11016         return;
11017       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11018     }
11019 
11020     // If the vector cast is cast between two vectors of the same size, it is
11021     // a bitcast, not a conversion.
11022     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11023       return;
11024 
11025     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11026     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11027   }
11028   if (auto VecTy = dyn_cast<VectorType>(Target))
11029     Target = VecTy->getElementType().getTypePtr();
11030 
11031   // Strip complex types.
11032   if (isa<ComplexType>(Source)) {
11033     if (!isa<ComplexType>(Target)) {
11034       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11035         return;
11036 
11037       return DiagnoseImpCast(S, E, T, CC,
11038                              S.getLangOpts().CPlusPlus
11039                                  ? diag::err_impcast_complex_scalar
11040                                  : diag::warn_impcast_complex_scalar);
11041     }
11042 
11043     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11044     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11045   }
11046 
11047   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11048   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11049 
11050   // If the source is floating point...
11051   if (SourceBT && SourceBT->isFloatingPoint()) {
11052     // ...and the target is floating point...
11053     if (TargetBT && TargetBT->isFloatingPoint()) {
11054       // ...then warn if we're dropping FP rank.
11055 
11056       // Builtin FP kinds are ordered by increasing FP rank.
11057       if (SourceBT->getKind() > TargetBT->getKind()) {
11058         // Don't warn about float constants that are precisely
11059         // representable in the target type.
11060         Expr::EvalResult result;
11061         if (E->EvaluateAsRValue(result, S.Context)) {
11062           // Value might be a float, a float vector, or a float complex.
11063           if (IsSameFloatAfterCast(result.Val,
11064                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11065                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11066             return;
11067         }
11068 
11069         if (S.SourceMgr.isInSystemMacro(CC))
11070           return;
11071 
11072         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11073       }
11074       // ... or possibly if we're increasing rank, too
11075       else if (TargetBT->getKind() > SourceBT->getKind()) {
11076         if (S.SourceMgr.isInSystemMacro(CC))
11077           return;
11078 
11079         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11080       }
11081       return;
11082     }
11083 
11084     // If the target is integral, always warn.
11085     if (TargetBT && TargetBT->isInteger()) {
11086       if (S.SourceMgr.isInSystemMacro(CC))
11087         return;
11088 
11089       DiagnoseFloatingImpCast(S, E, T, CC);
11090     }
11091 
11092     // Detect the case where a call result is converted from floating-point to
11093     // to bool, and the final argument to the call is converted from bool, to
11094     // discover this typo:
11095     //
11096     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11097     //
11098     // FIXME: This is an incredibly special case; is there some more general
11099     // way to detect this class of misplaced-parentheses bug?
11100     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11101       // Check last argument of function call to see if it is an
11102       // implicit cast from a type matching the type the result
11103       // is being cast to.
11104       CallExpr *CEx = cast<CallExpr>(E);
11105       if (unsigned NumArgs = CEx->getNumArgs()) {
11106         Expr *LastA = CEx->getArg(NumArgs - 1);
11107         Expr *InnerE = LastA->IgnoreParenImpCasts();
11108         if (isa<ImplicitCastExpr>(LastA) &&
11109             InnerE->getType()->isBooleanType()) {
11110           // Warn on this floating-point to bool conversion
11111           DiagnoseImpCast(S, E, T, CC,
11112                           diag::warn_impcast_floating_point_to_bool);
11113         }
11114       }
11115     }
11116     return;
11117   }
11118 
11119   DiagnoseNullConversion(S, E, T, CC);
11120 
11121   S.DiscardMisalignedMemberAddress(Target, E);
11122 
11123   if (!Source->isIntegerType() || !Target->isIntegerType())
11124     return;
11125 
11126   // TODO: remove this early return once the false positives for constant->bool
11127   // in templates, macros, etc, are reduced or removed.
11128   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11129     return;
11130 
11131   IntRange SourceRange = GetExprRange(S.Context, E);
11132   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11133 
11134   if (SourceRange.Width > TargetRange.Width) {
11135     // If the source is a constant, use a default-on diagnostic.
11136     // TODO: this should happen for bitfield stores, too.
11137     llvm::APSInt Value(32);
11138     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
11139       if (S.SourceMgr.isInSystemMacro(CC))
11140         return;
11141 
11142       std::string PrettySourceValue = Value.toString(10);
11143       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11144 
11145       S.DiagRuntimeBehavior(E->getExprLoc(), E,
11146         S.PDiag(diag::warn_impcast_integer_precision_constant)
11147             << PrettySourceValue << PrettyTargetValue
11148             << E->getType() << T << E->getSourceRange()
11149             << clang::SourceRange(CC));
11150       return;
11151     }
11152 
11153     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11154     if (S.SourceMgr.isInSystemMacro(CC))
11155       return;
11156 
11157     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11158       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11159                              /* pruneControlFlow */ true);
11160     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11161   }
11162 
11163   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11164       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11165     // Warn when doing a signed to signed conversion, warn if the positive
11166     // source value is exactly the width of the target type, which will
11167     // cause a negative value to be stored.
11168 
11169     llvm::APSInt Value;
11170     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
11171         !S.SourceMgr.isInSystemMacro(CC)) {
11172       if (isSameWidthConstantConversion(S, E, T, CC)) {
11173         std::string PrettySourceValue = Value.toString(10);
11174         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11175 
11176         S.DiagRuntimeBehavior(
11177             E->getExprLoc(), E,
11178             S.PDiag(diag::warn_impcast_integer_precision_constant)
11179                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11180                 << E->getSourceRange() << clang::SourceRange(CC));
11181         return;
11182       }
11183     }
11184 
11185     // Fall through for non-constants to give a sign conversion warning.
11186   }
11187 
11188   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11189       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11190        SourceRange.Width == TargetRange.Width)) {
11191     if (S.SourceMgr.isInSystemMacro(CC))
11192       return;
11193 
11194     unsigned DiagID = diag::warn_impcast_integer_sign;
11195 
11196     // Traditionally, gcc has warned about this under -Wsign-compare.
11197     // We also want to warn about it in -Wconversion.
11198     // So if -Wconversion is off, use a completely identical diagnostic
11199     // in the sign-compare group.
11200     // The conditional-checking code will
11201     if (ICContext) {
11202       DiagID = diag::warn_impcast_integer_sign_conditional;
11203       *ICContext = true;
11204     }
11205 
11206     return DiagnoseImpCast(S, E, T, CC, DiagID);
11207   }
11208 
11209   // Diagnose conversions between different enumeration types.
11210   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11211   // type, to give us better diagnostics.
11212   QualType SourceType = E->getType();
11213   if (!S.getLangOpts().CPlusPlus) {
11214     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11215       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11216         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11217         SourceType = S.Context.getTypeDeclType(Enum);
11218         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11219       }
11220   }
11221 
11222   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11223     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11224       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11225           TargetEnum->getDecl()->hasNameForLinkage() &&
11226           SourceEnum != TargetEnum) {
11227         if (S.SourceMgr.isInSystemMacro(CC))
11228           return;
11229 
11230         return DiagnoseImpCast(S, E, SourceType, T, CC,
11231                                diag::warn_impcast_different_enum_types);
11232       }
11233 }
11234 
11235 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11236                                      SourceLocation CC, QualType T);
11237 
11238 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11239                                     SourceLocation CC, bool &ICContext) {
11240   E = E->IgnoreParenImpCasts();
11241 
11242   if (isa<ConditionalOperator>(E))
11243     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11244 
11245   AnalyzeImplicitConversions(S, E, CC);
11246   if (E->getType() != T)
11247     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11248 }
11249 
11250 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11251                                      SourceLocation CC, QualType T) {
11252   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11253 
11254   bool Suspicious = false;
11255   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11256   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11257 
11258   // If -Wconversion would have warned about either of the candidates
11259   // for a signedness conversion to the context type...
11260   if (!Suspicious) return;
11261 
11262   // ...but it's currently ignored...
11263   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11264     return;
11265 
11266   // ...then check whether it would have warned about either of the
11267   // candidates for a signedness conversion to the condition type.
11268   if (E->getType() == T) return;
11269 
11270   Suspicious = false;
11271   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11272                           E->getType(), CC, &Suspicious);
11273   if (!Suspicious)
11274     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11275                             E->getType(), CC, &Suspicious);
11276 }
11277 
11278 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11279 /// Input argument E is a logical expression.
11280 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11281   if (S.getLangOpts().Bool)
11282     return;
11283   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11284 }
11285 
11286 /// AnalyzeImplicitConversions - Find and report any interesting
11287 /// implicit conversions in the given expression.  There are a couple
11288 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11289 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11290                                        SourceLocation CC) {
11291   QualType T = OrigE->getType();
11292   Expr *E = OrigE->IgnoreParenImpCasts();
11293 
11294   if (E->isTypeDependent() || E->isValueDependent())
11295     return;
11296 
11297   // For conditional operators, we analyze the arguments as if they
11298   // were being fed directly into the output.
11299   if (isa<ConditionalOperator>(E)) {
11300     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11301     CheckConditionalOperator(S, CO, CC, T);
11302     return;
11303   }
11304 
11305   // Check implicit argument conversions for function calls.
11306   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11307     CheckImplicitArgumentConversions(S, Call, CC);
11308 
11309   // Go ahead and check any implicit conversions we might have skipped.
11310   // The non-canonical typecheck is just an optimization;
11311   // CheckImplicitConversion will filter out dead implicit conversions.
11312   if (E->getType() != T)
11313     CheckImplicitConversion(S, E, T, CC);
11314 
11315   // Now continue drilling into this expression.
11316 
11317   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11318     // The bound subexpressions in a PseudoObjectExpr are not reachable
11319     // as transitive children.
11320     // FIXME: Use a more uniform representation for this.
11321     for (auto *SE : POE->semantics())
11322       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11323         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11324   }
11325 
11326   // Skip past explicit casts.
11327   if (isa<ExplicitCastExpr>(E)) {
11328     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
11329     return AnalyzeImplicitConversions(S, E, CC);
11330   }
11331 
11332   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11333     // Do a somewhat different check with comparison operators.
11334     if (BO->isComparisonOp())
11335       return AnalyzeComparison(S, BO);
11336 
11337     // And with simple assignments.
11338     if (BO->getOpcode() == BO_Assign)
11339       return AnalyzeAssignment(S, BO);
11340     // And with compound assignments.
11341     if (BO->isAssignmentOp())
11342       return AnalyzeCompoundAssignment(S, BO);
11343   }
11344 
11345   // These break the otherwise-useful invariant below.  Fortunately,
11346   // we don't really need to recurse into them, because any internal
11347   // expressions should have been analyzed already when they were
11348   // built into statements.
11349   if (isa<StmtExpr>(E)) return;
11350 
11351   // Don't descend into unevaluated contexts.
11352   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11353 
11354   // Now just recurse over the expression's children.
11355   CC = E->getExprLoc();
11356   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11357   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11358   for (Stmt *SubStmt : E->children()) {
11359     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11360     if (!ChildExpr)
11361       continue;
11362 
11363     if (IsLogicalAndOperator &&
11364         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11365       // Ignore checking string literals that are in logical and operators.
11366       // This is a common pattern for asserts.
11367       continue;
11368     AnalyzeImplicitConversions(S, ChildExpr, CC);
11369   }
11370 
11371   if (BO && BO->isLogicalOp()) {
11372     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11373     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11374       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11375 
11376     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11377     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11378       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11379   }
11380 
11381   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
11382     if (U->getOpcode() == UO_LNot)
11383       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11384 }
11385 
11386 /// Diagnose integer type and any valid implicit conversion to it.
11387 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11388   // Taking into account implicit conversions,
11389   // allow any integer.
11390   if (!E->getType()->isIntegerType()) {
11391     S.Diag(E->getLocStart(),
11392            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11393     return true;
11394   }
11395   // Potentially emit standard warnings for implicit conversions if enabled
11396   // using -Wconversion.
11397   CheckImplicitConversion(S, E, IntT, E->getLocStart());
11398   return false;
11399 }
11400 
11401 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11402 // Returns true when emitting a warning about taking the address of a reference.
11403 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11404                               const PartialDiagnostic &PD) {
11405   E = E->IgnoreParenImpCasts();
11406 
11407   const FunctionDecl *FD = nullptr;
11408 
11409   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11410     if (!DRE->getDecl()->getType()->isReferenceType())
11411       return false;
11412   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11413     if (!M->getMemberDecl()->getType()->isReferenceType())
11414       return false;
11415   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11416     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11417       return false;
11418     FD = Call->getDirectCallee();
11419   } else {
11420     return false;
11421   }
11422 
11423   SemaRef.Diag(E->getExprLoc(), PD);
11424 
11425   // If possible, point to location of function.
11426   if (FD) {
11427     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11428   }
11429 
11430   return true;
11431 }
11432 
11433 // Returns true if the SourceLocation is expanded from any macro body.
11434 // Returns false if the SourceLocation is invalid, is from not in a macro
11435 // expansion, or is from expanded from a top-level macro argument.
11436 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11437   if (Loc.isInvalid())
11438     return false;
11439 
11440   while (Loc.isMacroID()) {
11441     if (SM.isMacroBodyExpansion(Loc))
11442       return true;
11443     Loc = SM.getImmediateMacroCallerLoc(Loc);
11444   }
11445 
11446   return false;
11447 }
11448 
11449 /// Diagnose pointers that are always non-null.
11450 /// \param E the expression containing the pointer
11451 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11452 /// compared to a null pointer
11453 /// \param IsEqual True when the comparison is equal to a null pointer
11454 /// \param Range Extra SourceRange to highlight in the diagnostic
11455 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11456                                         Expr::NullPointerConstantKind NullKind,
11457                                         bool IsEqual, SourceRange Range) {
11458   if (!E)
11459     return;
11460 
11461   // Don't warn inside macros.
11462   if (E->getExprLoc().isMacroID()) {
11463     const SourceManager &SM = getSourceManager();
11464     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11465         IsInAnyMacroBody(SM, Range.getBegin()))
11466       return;
11467   }
11468   E = E->IgnoreImpCasts();
11469 
11470   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11471 
11472   if (isa<CXXThisExpr>(E)) {
11473     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11474                                 : diag::warn_this_bool_conversion;
11475     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11476     return;
11477   }
11478 
11479   bool IsAddressOf = false;
11480 
11481   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11482     if (UO->getOpcode() != UO_AddrOf)
11483       return;
11484     IsAddressOf = true;
11485     E = UO->getSubExpr();
11486   }
11487 
11488   if (IsAddressOf) {
11489     unsigned DiagID = IsCompare
11490                           ? diag::warn_address_of_reference_null_compare
11491                           : diag::warn_address_of_reference_bool_conversion;
11492     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11493                                          << IsEqual;
11494     if (CheckForReference(*this, E, PD)) {
11495       return;
11496     }
11497   }
11498 
11499   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11500     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11501     std::string Str;
11502     llvm::raw_string_ostream S(Str);
11503     E->printPretty(S, nullptr, getPrintingPolicy());
11504     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11505                                 : diag::warn_cast_nonnull_to_bool;
11506     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11507       << E->getSourceRange() << Range << IsEqual;
11508     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11509   };
11510 
11511   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11512   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11513     if (auto *Callee = Call->getDirectCallee()) {
11514       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11515         ComplainAboutNonnullParamOrCall(A);
11516         return;
11517       }
11518     }
11519   }
11520 
11521   // Expect to find a single Decl.  Skip anything more complicated.
11522   ValueDecl *D = nullptr;
11523   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11524     D = R->getDecl();
11525   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11526     D = M->getMemberDecl();
11527   }
11528 
11529   // Weak Decls can be null.
11530   if (!D || D->isWeak())
11531     return;
11532 
11533   // Check for parameter decl with nonnull attribute
11534   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11535     if (getCurFunction() &&
11536         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11537       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11538         ComplainAboutNonnullParamOrCall(A);
11539         return;
11540       }
11541 
11542       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11543         auto ParamIter = llvm::find(FD->parameters(), PV);
11544         assert(ParamIter != FD->param_end());
11545         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11546 
11547         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11548           if (!NonNull->args_size()) {
11549               ComplainAboutNonnullParamOrCall(NonNull);
11550               return;
11551           }
11552 
11553           for (const ParamIdx &ArgNo : NonNull->args()) {
11554             if (ArgNo.getASTIndex() == ParamNo) {
11555               ComplainAboutNonnullParamOrCall(NonNull);
11556               return;
11557             }
11558           }
11559         }
11560       }
11561     }
11562   }
11563 
11564   QualType T = D->getType();
11565   const bool IsArray = T->isArrayType();
11566   const bool IsFunction = T->isFunctionType();
11567 
11568   // Address of function is used to silence the function warning.
11569   if (IsAddressOf && IsFunction) {
11570     return;
11571   }
11572 
11573   // Found nothing.
11574   if (!IsAddressOf && !IsFunction && !IsArray)
11575     return;
11576 
11577   // Pretty print the expression for the diagnostic.
11578   std::string Str;
11579   llvm::raw_string_ostream S(Str);
11580   E->printPretty(S, nullptr, getPrintingPolicy());
11581 
11582   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11583                               : diag::warn_impcast_pointer_to_bool;
11584   enum {
11585     AddressOf,
11586     FunctionPointer,
11587     ArrayPointer
11588   } DiagType;
11589   if (IsAddressOf)
11590     DiagType = AddressOf;
11591   else if (IsFunction)
11592     DiagType = FunctionPointer;
11593   else if (IsArray)
11594     DiagType = ArrayPointer;
11595   else
11596     llvm_unreachable("Could not determine diagnostic.");
11597   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11598                                 << Range << IsEqual;
11599 
11600   if (!IsFunction)
11601     return;
11602 
11603   // Suggest '&' to silence the function warning.
11604   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11605       << FixItHint::CreateInsertion(E->getLocStart(), "&");
11606 
11607   // Check to see if '()' fixit should be emitted.
11608   QualType ReturnType;
11609   UnresolvedSet<4> NonTemplateOverloads;
11610   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11611   if (ReturnType.isNull())
11612     return;
11613 
11614   if (IsCompare) {
11615     // There are two cases here.  If there is null constant, the only suggest
11616     // for a pointer return type.  If the null is 0, then suggest if the return
11617     // type is a pointer or an integer type.
11618     if (!ReturnType->isPointerType()) {
11619       if (NullKind == Expr::NPCK_ZeroExpression ||
11620           NullKind == Expr::NPCK_ZeroLiteral) {
11621         if (!ReturnType->isIntegerType())
11622           return;
11623       } else {
11624         return;
11625       }
11626     }
11627   } else { // !IsCompare
11628     // For function to bool, only suggest if the function pointer has bool
11629     // return type.
11630     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11631       return;
11632   }
11633   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11634       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
11635 }
11636 
11637 /// Diagnoses "dangerous" implicit conversions within the given
11638 /// expression (which is a full expression).  Implements -Wconversion
11639 /// and -Wsign-compare.
11640 ///
11641 /// \param CC the "context" location of the implicit conversion, i.e.
11642 ///   the most location of the syntactic entity requiring the implicit
11643 ///   conversion
11644 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11645   // Don't diagnose in unevaluated contexts.
11646   if (isUnevaluatedContext())
11647     return;
11648 
11649   // Don't diagnose for value- or type-dependent expressions.
11650   if (E->isTypeDependent() || E->isValueDependent())
11651     return;
11652 
11653   // Check for array bounds violations in cases where the check isn't triggered
11654   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11655   // ArraySubscriptExpr is on the RHS of a variable initialization.
11656   CheckArrayAccess(E);
11657 
11658   // This is not the right CC for (e.g.) a variable initialization.
11659   AnalyzeImplicitConversions(*this, E, CC);
11660 }
11661 
11662 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11663 /// Input argument E is a logical expression.
11664 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11665   ::CheckBoolLikeConversion(*this, E, CC);
11666 }
11667 
11668 /// Diagnose when expression is an integer constant expression and its evaluation
11669 /// results in integer overflow
11670 void Sema::CheckForIntOverflow (Expr *E) {
11671   // Use a work list to deal with nested struct initializers.
11672   SmallVector<Expr *, 2> Exprs(1, E);
11673 
11674   do {
11675     Expr *OriginalE = Exprs.pop_back_val();
11676     Expr *E = OriginalE->IgnoreParenCasts();
11677 
11678     if (isa<BinaryOperator>(E)) {
11679       E->EvaluateForOverflow(Context);
11680       continue;
11681     }
11682 
11683     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11684       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11685     else if (isa<ObjCBoxedExpr>(OriginalE))
11686       E->EvaluateForOverflow(Context);
11687     else if (auto Call = dyn_cast<CallExpr>(E))
11688       Exprs.append(Call->arg_begin(), Call->arg_end());
11689     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11690       Exprs.append(Message->arg_begin(), Message->arg_end());
11691   } while (!Exprs.empty());
11692 }
11693 
11694 namespace {
11695 
11696 /// Visitor for expressions which looks for unsequenced operations on the
11697 /// same object.
11698 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11699   using Base = EvaluatedExprVisitor<SequenceChecker>;
11700 
11701   /// A tree of sequenced regions within an expression. Two regions are
11702   /// unsequenced if one is an ancestor or a descendent of the other. When we
11703   /// finish processing an expression with sequencing, such as a comma
11704   /// expression, we fold its tree nodes into its parent, since they are
11705   /// unsequenced with respect to nodes we will visit later.
11706   class SequenceTree {
11707     struct Value {
11708       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11709       unsigned Parent : 31;
11710       unsigned Merged : 1;
11711     };
11712     SmallVector<Value, 8> Values;
11713 
11714   public:
11715     /// A region within an expression which may be sequenced with respect
11716     /// to some other region.
11717     class Seq {
11718       friend class SequenceTree;
11719 
11720       unsigned Index = 0;
11721 
11722       explicit Seq(unsigned N) : Index(N) {}
11723 
11724     public:
11725       Seq() = default;
11726     };
11727 
11728     SequenceTree() { Values.push_back(Value(0)); }
11729     Seq root() const { return Seq(0); }
11730 
11731     /// Create a new sequence of operations, which is an unsequenced
11732     /// subset of \p Parent. This sequence of operations is sequenced with
11733     /// respect to other children of \p Parent.
11734     Seq allocate(Seq Parent) {
11735       Values.push_back(Value(Parent.Index));
11736       return Seq(Values.size() - 1);
11737     }
11738 
11739     /// Merge a sequence of operations into its parent.
11740     void merge(Seq S) {
11741       Values[S.Index].Merged = true;
11742     }
11743 
11744     /// Determine whether two operations are unsequenced. This operation
11745     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11746     /// should have been merged into its parent as appropriate.
11747     bool isUnsequenced(Seq Cur, Seq Old) {
11748       unsigned C = representative(Cur.Index);
11749       unsigned Target = representative(Old.Index);
11750       while (C >= Target) {
11751         if (C == Target)
11752           return true;
11753         C = Values[C].Parent;
11754       }
11755       return false;
11756     }
11757 
11758   private:
11759     /// Pick a representative for a sequence.
11760     unsigned representative(unsigned K) {
11761       if (Values[K].Merged)
11762         // Perform path compression as we go.
11763         return Values[K].Parent = representative(Values[K].Parent);
11764       return K;
11765     }
11766   };
11767 
11768   /// An object for which we can track unsequenced uses.
11769   using Object = NamedDecl *;
11770 
11771   /// Different flavors of object usage which we track. We only track the
11772   /// least-sequenced usage of each kind.
11773   enum UsageKind {
11774     /// A read of an object. Multiple unsequenced reads are OK.
11775     UK_Use,
11776 
11777     /// A modification of an object which is sequenced before the value
11778     /// computation of the expression, such as ++n in C++.
11779     UK_ModAsValue,
11780 
11781     /// A modification of an object which is not sequenced before the value
11782     /// computation of the expression, such as n++.
11783     UK_ModAsSideEffect,
11784 
11785     UK_Count = UK_ModAsSideEffect + 1
11786   };
11787 
11788   struct Usage {
11789     Expr *Use = nullptr;
11790     SequenceTree::Seq Seq;
11791 
11792     Usage() = default;
11793   };
11794 
11795   struct UsageInfo {
11796     Usage Uses[UK_Count];
11797 
11798     /// Have we issued a diagnostic for this variable already?
11799     bool Diagnosed = false;
11800 
11801     UsageInfo() = default;
11802   };
11803   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11804 
11805   Sema &SemaRef;
11806 
11807   /// Sequenced regions within the expression.
11808   SequenceTree Tree;
11809 
11810   /// Declaration modifications and references which we have seen.
11811   UsageInfoMap UsageMap;
11812 
11813   /// The region we are currently within.
11814   SequenceTree::Seq Region;
11815 
11816   /// Filled in with declarations which were modified as a side-effect
11817   /// (that is, post-increment operations).
11818   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11819 
11820   /// Expressions to check later. We defer checking these to reduce
11821   /// stack usage.
11822   SmallVectorImpl<Expr *> &WorkList;
11823 
11824   /// RAII object wrapping the visitation of a sequenced subexpression of an
11825   /// expression. At the end of this process, the side-effects of the evaluation
11826   /// become sequenced with respect to the value computation of the result, so
11827   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11828   /// UK_ModAsValue.
11829   struct SequencedSubexpression {
11830     SequencedSubexpression(SequenceChecker &Self)
11831       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11832       Self.ModAsSideEffect = &ModAsSideEffect;
11833     }
11834 
11835     ~SequencedSubexpression() {
11836       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11837         UsageInfo &U = Self.UsageMap[M.first];
11838         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11839         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11840         SideEffectUsage = M.second;
11841       }
11842       Self.ModAsSideEffect = OldModAsSideEffect;
11843     }
11844 
11845     SequenceChecker &Self;
11846     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11847     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11848   };
11849 
11850   /// RAII object wrapping the visitation of a subexpression which we might
11851   /// choose to evaluate as a constant. If any subexpression is evaluated and
11852   /// found to be non-constant, this allows us to suppress the evaluation of
11853   /// the outer expression.
11854   class EvaluationTracker {
11855   public:
11856     EvaluationTracker(SequenceChecker &Self)
11857         : Self(Self), Prev(Self.EvalTracker) {
11858       Self.EvalTracker = this;
11859     }
11860 
11861     ~EvaluationTracker() {
11862       Self.EvalTracker = Prev;
11863       if (Prev)
11864         Prev->EvalOK &= EvalOK;
11865     }
11866 
11867     bool evaluate(const Expr *E, bool &Result) {
11868       if (!EvalOK || E->isValueDependent())
11869         return false;
11870       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11871       return EvalOK;
11872     }
11873 
11874   private:
11875     SequenceChecker &Self;
11876     EvaluationTracker *Prev;
11877     bool EvalOK = true;
11878   } *EvalTracker = nullptr;
11879 
11880   /// Find the object which is produced by the specified expression,
11881   /// if any.
11882   Object getObject(Expr *E, bool Mod) const {
11883     E = E->IgnoreParenCasts();
11884     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11885       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11886         return getObject(UO->getSubExpr(), Mod);
11887     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11888       if (BO->getOpcode() == BO_Comma)
11889         return getObject(BO->getRHS(), Mod);
11890       if (Mod && BO->isAssignmentOp())
11891         return getObject(BO->getLHS(), Mod);
11892     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11893       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11894       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11895         return ME->getMemberDecl();
11896     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11897       // FIXME: If this is a reference, map through to its value.
11898       return DRE->getDecl();
11899     return nullptr;
11900   }
11901 
11902   /// Note that an object was modified or used by an expression.
11903   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11904     Usage &U = UI.Uses[UK];
11905     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11906       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11907         ModAsSideEffect->push_back(std::make_pair(O, U));
11908       U.Use = Ref;
11909       U.Seq = Region;
11910     }
11911   }
11912 
11913   /// Check whether a modification or use conflicts with a prior usage.
11914   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11915                   bool IsModMod) {
11916     if (UI.Diagnosed)
11917       return;
11918 
11919     const Usage &U = UI.Uses[OtherKind];
11920     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11921       return;
11922 
11923     Expr *Mod = U.Use;
11924     Expr *ModOrUse = Ref;
11925     if (OtherKind == UK_Use)
11926       std::swap(Mod, ModOrUse);
11927 
11928     SemaRef.Diag(Mod->getExprLoc(),
11929                  IsModMod ? diag::warn_unsequenced_mod_mod
11930                           : diag::warn_unsequenced_mod_use)
11931       << O << SourceRange(ModOrUse->getExprLoc());
11932     UI.Diagnosed = true;
11933   }
11934 
11935   void notePreUse(Object O, Expr *Use) {
11936     UsageInfo &U = UsageMap[O];
11937     // Uses conflict with other modifications.
11938     checkUsage(O, U, Use, UK_ModAsValue, false);
11939   }
11940 
11941   void notePostUse(Object O, Expr *Use) {
11942     UsageInfo &U = UsageMap[O];
11943     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11944     addUsage(U, O, Use, UK_Use);
11945   }
11946 
11947   void notePreMod(Object O, Expr *Mod) {
11948     UsageInfo &U = UsageMap[O];
11949     // Modifications conflict with other modifications and with uses.
11950     checkUsage(O, U, Mod, UK_ModAsValue, true);
11951     checkUsage(O, U, Mod, UK_Use, false);
11952   }
11953 
11954   void notePostMod(Object O, Expr *Use, UsageKind UK) {
11955     UsageInfo &U = UsageMap[O];
11956     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11957     addUsage(U, O, Use, UK);
11958   }
11959 
11960 public:
11961   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
11962       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
11963     Visit(E);
11964   }
11965 
11966   void VisitStmt(Stmt *S) {
11967     // Skip all statements which aren't expressions for now.
11968   }
11969 
11970   void VisitExpr(Expr *E) {
11971     // By default, just recurse to evaluated subexpressions.
11972     Base::VisitStmt(E);
11973   }
11974 
11975   void VisitCastExpr(CastExpr *E) {
11976     Object O = Object();
11977     if (E->getCastKind() == CK_LValueToRValue)
11978       O = getObject(E->getSubExpr(), false);
11979 
11980     if (O)
11981       notePreUse(O, E);
11982     VisitExpr(E);
11983     if (O)
11984       notePostUse(O, E);
11985   }
11986 
11987   void VisitBinComma(BinaryOperator *BO) {
11988     // C++11 [expr.comma]p1:
11989     //   Every value computation and side effect associated with the left
11990     //   expression is sequenced before every value computation and side
11991     //   effect associated with the right expression.
11992     SequenceTree::Seq LHS = Tree.allocate(Region);
11993     SequenceTree::Seq RHS = Tree.allocate(Region);
11994     SequenceTree::Seq OldRegion = Region;
11995 
11996     {
11997       SequencedSubexpression SeqLHS(*this);
11998       Region = LHS;
11999       Visit(BO->getLHS());
12000     }
12001 
12002     Region = RHS;
12003     Visit(BO->getRHS());
12004 
12005     Region = OldRegion;
12006 
12007     // Forget that LHS and RHS are sequenced. They are both unsequenced
12008     // with respect to other stuff.
12009     Tree.merge(LHS);
12010     Tree.merge(RHS);
12011   }
12012 
12013   void VisitBinAssign(BinaryOperator *BO) {
12014     // The modification is sequenced after the value computation of the LHS
12015     // and RHS, so check it before inspecting the operands and update the
12016     // map afterwards.
12017     Object O = getObject(BO->getLHS(), true);
12018     if (!O)
12019       return VisitExpr(BO);
12020 
12021     notePreMod(O, BO);
12022 
12023     // C++11 [expr.ass]p7:
12024     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12025     //   only once.
12026     //
12027     // Therefore, for a compound assignment operator, O is considered used
12028     // everywhere except within the evaluation of E1 itself.
12029     if (isa<CompoundAssignOperator>(BO))
12030       notePreUse(O, BO);
12031 
12032     Visit(BO->getLHS());
12033 
12034     if (isa<CompoundAssignOperator>(BO))
12035       notePostUse(O, BO);
12036 
12037     Visit(BO->getRHS());
12038 
12039     // C++11 [expr.ass]p1:
12040     //   the assignment is sequenced [...] before the value computation of the
12041     //   assignment expression.
12042     // C11 6.5.16/3 has no such rule.
12043     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12044                                                        : UK_ModAsSideEffect);
12045   }
12046 
12047   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12048     VisitBinAssign(CAO);
12049   }
12050 
12051   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12052   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12053   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12054     Object O = getObject(UO->getSubExpr(), true);
12055     if (!O)
12056       return VisitExpr(UO);
12057 
12058     notePreMod(O, UO);
12059     Visit(UO->getSubExpr());
12060     // C++11 [expr.pre.incr]p1:
12061     //   the expression ++x is equivalent to x+=1
12062     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12063                                                        : UK_ModAsSideEffect);
12064   }
12065 
12066   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12067   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12068   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12069     Object O = getObject(UO->getSubExpr(), true);
12070     if (!O)
12071       return VisitExpr(UO);
12072 
12073     notePreMod(O, UO);
12074     Visit(UO->getSubExpr());
12075     notePostMod(O, UO, UK_ModAsSideEffect);
12076   }
12077 
12078   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12079   void VisitBinLOr(BinaryOperator *BO) {
12080     // The side-effects of the LHS of an '&&' are sequenced before the
12081     // value computation of the RHS, and hence before the value computation
12082     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12083     // as if they were unconditionally sequenced.
12084     EvaluationTracker Eval(*this);
12085     {
12086       SequencedSubexpression Sequenced(*this);
12087       Visit(BO->getLHS());
12088     }
12089 
12090     bool Result;
12091     if (Eval.evaluate(BO->getLHS(), Result)) {
12092       if (!Result)
12093         Visit(BO->getRHS());
12094     } else {
12095       // Check for unsequenced operations in the RHS, treating it as an
12096       // entirely separate evaluation.
12097       //
12098       // FIXME: If there are operations in the RHS which are unsequenced
12099       // with respect to operations outside the RHS, and those operations
12100       // are unconditionally evaluated, diagnose them.
12101       WorkList.push_back(BO->getRHS());
12102     }
12103   }
12104   void VisitBinLAnd(BinaryOperator *BO) {
12105     EvaluationTracker Eval(*this);
12106     {
12107       SequencedSubexpression Sequenced(*this);
12108       Visit(BO->getLHS());
12109     }
12110 
12111     bool Result;
12112     if (Eval.evaluate(BO->getLHS(), Result)) {
12113       if (Result)
12114         Visit(BO->getRHS());
12115     } else {
12116       WorkList.push_back(BO->getRHS());
12117     }
12118   }
12119 
12120   // Only visit the condition, unless we can be sure which subexpression will
12121   // be chosen.
12122   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12123     EvaluationTracker Eval(*this);
12124     {
12125       SequencedSubexpression Sequenced(*this);
12126       Visit(CO->getCond());
12127     }
12128 
12129     bool Result;
12130     if (Eval.evaluate(CO->getCond(), Result))
12131       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12132     else {
12133       WorkList.push_back(CO->getTrueExpr());
12134       WorkList.push_back(CO->getFalseExpr());
12135     }
12136   }
12137 
12138   void VisitCallExpr(CallExpr *CE) {
12139     // C++11 [intro.execution]p15:
12140     //   When calling a function [...], every value computation and side effect
12141     //   associated with any argument expression, or with the postfix expression
12142     //   designating the called function, is sequenced before execution of every
12143     //   expression or statement in the body of the function [and thus before
12144     //   the value computation of its result].
12145     SequencedSubexpression Sequenced(*this);
12146     Base::VisitCallExpr(CE);
12147 
12148     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12149   }
12150 
12151   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12152     // This is a call, so all subexpressions are sequenced before the result.
12153     SequencedSubexpression Sequenced(*this);
12154 
12155     if (!CCE->isListInitialization())
12156       return VisitExpr(CCE);
12157 
12158     // In C++11, list initializations are sequenced.
12159     SmallVector<SequenceTree::Seq, 32> Elts;
12160     SequenceTree::Seq Parent = Region;
12161     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12162                                         E = CCE->arg_end();
12163          I != E; ++I) {
12164       Region = Tree.allocate(Parent);
12165       Elts.push_back(Region);
12166       Visit(*I);
12167     }
12168 
12169     // Forget that the initializers are sequenced.
12170     Region = Parent;
12171     for (unsigned I = 0; I < Elts.size(); ++I)
12172       Tree.merge(Elts[I]);
12173   }
12174 
12175   void VisitInitListExpr(InitListExpr *ILE) {
12176     if (!SemaRef.getLangOpts().CPlusPlus11)
12177       return VisitExpr(ILE);
12178 
12179     // In C++11, list initializations are sequenced.
12180     SmallVector<SequenceTree::Seq, 32> Elts;
12181     SequenceTree::Seq Parent = Region;
12182     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12183       Expr *E = ILE->getInit(I);
12184       if (!E) continue;
12185       Region = Tree.allocate(Parent);
12186       Elts.push_back(Region);
12187       Visit(E);
12188     }
12189 
12190     // Forget that the initializers are sequenced.
12191     Region = Parent;
12192     for (unsigned I = 0; I < Elts.size(); ++I)
12193       Tree.merge(Elts[I]);
12194   }
12195 };
12196 
12197 } // namespace
12198 
12199 void Sema::CheckUnsequencedOperations(Expr *E) {
12200   SmallVector<Expr *, 8> WorkList;
12201   WorkList.push_back(E);
12202   while (!WorkList.empty()) {
12203     Expr *Item = WorkList.pop_back_val();
12204     SequenceChecker(*this, Item, WorkList);
12205   }
12206 }
12207 
12208 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12209                               bool IsConstexpr) {
12210   CheckImplicitConversions(E, CheckLoc);
12211   if (!E->isInstantiationDependent())
12212     CheckUnsequencedOperations(E);
12213   if (!IsConstexpr && !E->isValueDependent())
12214     CheckForIntOverflow(E);
12215   DiagnoseMisalignedMembers();
12216 }
12217 
12218 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12219                                        FieldDecl *BitField,
12220                                        Expr *Init) {
12221   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12222 }
12223 
12224 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12225                                          SourceLocation Loc) {
12226   if (!PType->isVariablyModifiedType())
12227     return;
12228   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12229     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12230     return;
12231   }
12232   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12233     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12234     return;
12235   }
12236   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12237     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12238     return;
12239   }
12240 
12241   const ArrayType *AT = S.Context.getAsArrayType(PType);
12242   if (!AT)
12243     return;
12244 
12245   if (AT->getSizeModifier() != ArrayType::Star) {
12246     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12247     return;
12248   }
12249 
12250   S.Diag(Loc, diag::err_array_star_in_function_definition);
12251 }
12252 
12253 /// CheckParmsForFunctionDef - Check that the parameters of the given
12254 /// function are appropriate for the definition of a function. This
12255 /// takes care of any checks that cannot be performed on the
12256 /// declaration itself, e.g., that the types of each of the function
12257 /// parameters are complete.
12258 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12259                                     bool CheckParameterNames) {
12260   bool HasInvalidParm = false;
12261   for (ParmVarDecl *Param : Parameters) {
12262     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12263     // function declarator that is part of a function definition of
12264     // that function shall not have incomplete type.
12265     //
12266     // This is also C++ [dcl.fct]p6.
12267     if (!Param->isInvalidDecl() &&
12268         RequireCompleteType(Param->getLocation(), Param->getType(),
12269                             diag::err_typecheck_decl_incomplete_type)) {
12270       Param->setInvalidDecl();
12271       HasInvalidParm = true;
12272     }
12273 
12274     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12275     // declaration of each parameter shall include an identifier.
12276     if (CheckParameterNames &&
12277         Param->getIdentifier() == nullptr &&
12278         !Param->isImplicit() &&
12279         !getLangOpts().CPlusPlus)
12280       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12281 
12282     // C99 6.7.5.3p12:
12283     //   If the function declarator is not part of a definition of that
12284     //   function, parameters may have incomplete type and may use the [*]
12285     //   notation in their sequences of declarator specifiers to specify
12286     //   variable length array types.
12287     QualType PType = Param->getOriginalType();
12288     // FIXME: This diagnostic should point the '[*]' if source-location
12289     // information is added for it.
12290     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12291 
12292     // If the parameter is a c++ class type and it has to be destructed in the
12293     // callee function, declare the destructor so that it can be called by the
12294     // callee function. Do not perform any direct access check on the dtor here.
12295     if (!Param->isInvalidDecl()) {
12296       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12297         if (!ClassDecl->isInvalidDecl() &&
12298             !ClassDecl->hasIrrelevantDestructor() &&
12299             !ClassDecl->isDependentContext() &&
12300             ClassDecl->isParamDestroyedInCallee()) {
12301           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12302           MarkFunctionReferenced(Param->getLocation(), Destructor);
12303           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12304         }
12305       }
12306     }
12307 
12308     // Parameters with the pass_object_size attribute only need to be marked
12309     // constant at function definitions. Because we lack information about
12310     // whether we're on a declaration or definition when we're instantiating the
12311     // attribute, we need to check for constness here.
12312     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12313       if (!Param->getType().isConstQualified())
12314         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12315             << Attr->getSpelling() << 1;
12316   }
12317 
12318   return HasInvalidParm;
12319 }
12320 
12321 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12322 /// or MemberExpr.
12323 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12324                               ASTContext &Context) {
12325   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12326     return Context.getDeclAlign(DRE->getDecl());
12327 
12328   if (const auto *ME = dyn_cast<MemberExpr>(E))
12329     return Context.getDeclAlign(ME->getMemberDecl());
12330 
12331   return TypeAlign;
12332 }
12333 
12334 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12335 /// pointer cast increases the alignment requirements.
12336 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12337   // This is actually a lot of work to potentially be doing on every
12338   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12339   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12340     return;
12341 
12342   // Ignore dependent types.
12343   if (T->isDependentType() || Op->getType()->isDependentType())
12344     return;
12345 
12346   // Require that the destination be a pointer type.
12347   const PointerType *DestPtr = T->getAs<PointerType>();
12348   if (!DestPtr) return;
12349 
12350   // If the destination has alignment 1, we're done.
12351   QualType DestPointee = DestPtr->getPointeeType();
12352   if (DestPointee->isIncompleteType()) return;
12353   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12354   if (DestAlign.isOne()) return;
12355 
12356   // Require that the source be a pointer type.
12357   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12358   if (!SrcPtr) return;
12359   QualType SrcPointee = SrcPtr->getPointeeType();
12360 
12361   // Whitelist casts from cv void*.  We already implicitly
12362   // whitelisted casts to cv void*, since they have alignment 1.
12363   // Also whitelist casts involving incomplete types, which implicitly
12364   // includes 'void'.
12365   if (SrcPointee->isIncompleteType()) return;
12366 
12367   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12368 
12369   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12370     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12371       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12372   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12373     if (UO->getOpcode() == UO_AddrOf)
12374       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12375   }
12376 
12377   if (SrcAlign >= DestAlign) return;
12378 
12379   Diag(TRange.getBegin(), diag::warn_cast_align)
12380     << Op->getType() << T
12381     << static_cast<unsigned>(SrcAlign.getQuantity())
12382     << static_cast<unsigned>(DestAlign.getQuantity())
12383     << TRange << Op->getSourceRange();
12384 }
12385 
12386 /// Check whether this array fits the idiom of a size-one tail padded
12387 /// array member of a struct.
12388 ///
12389 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12390 /// commonly used to emulate flexible arrays in C89 code.
12391 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12392                                     const NamedDecl *ND) {
12393   if (Size != 1 || !ND) return false;
12394 
12395   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12396   if (!FD) return false;
12397 
12398   // Don't consider sizes resulting from macro expansions or template argument
12399   // substitution to form C89 tail-padded arrays.
12400 
12401   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12402   while (TInfo) {
12403     TypeLoc TL = TInfo->getTypeLoc();
12404     // Look through typedefs.
12405     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12406       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12407       TInfo = TDL->getTypeSourceInfo();
12408       continue;
12409     }
12410     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12411       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12412       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12413         return false;
12414     }
12415     break;
12416   }
12417 
12418   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12419   if (!RD) return false;
12420   if (RD->isUnion()) return false;
12421   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12422     if (!CRD->isStandardLayout()) return false;
12423   }
12424 
12425   // See if this is the last field decl in the record.
12426   const Decl *D = FD;
12427   while ((D = D->getNextDeclInContext()))
12428     if (isa<FieldDecl>(D))
12429       return false;
12430   return true;
12431 }
12432 
12433 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12434                             const ArraySubscriptExpr *ASE,
12435                             bool AllowOnePastEnd, bool IndexNegated) {
12436   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12437   if (IndexExpr->isValueDependent())
12438     return;
12439 
12440   const Type *EffectiveType =
12441       BaseExpr->getType()->getPointeeOrArrayElementType();
12442   BaseExpr = BaseExpr->IgnoreParenCasts();
12443   const ConstantArrayType *ArrayTy =
12444     Context.getAsConstantArrayType(BaseExpr->getType());
12445   if (!ArrayTy)
12446     return;
12447 
12448   llvm::APSInt index;
12449   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
12450     return;
12451   if (IndexNegated)
12452     index = -index;
12453 
12454   const NamedDecl *ND = nullptr;
12455   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12456     ND = DRE->getDecl();
12457   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12458     ND = ME->getMemberDecl();
12459 
12460   if (index.isUnsigned() || !index.isNegative()) {
12461     llvm::APInt size = ArrayTy->getSize();
12462     if (!size.isStrictlyPositive())
12463       return;
12464 
12465     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
12466     if (BaseType != EffectiveType) {
12467       // Make sure we're comparing apples to apples when comparing index to size
12468       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12469       uint64_t array_typesize = Context.getTypeSize(BaseType);
12470       // Handle ptrarith_typesize being zero, such as when casting to void*
12471       if (!ptrarith_typesize) ptrarith_typesize = 1;
12472       if (ptrarith_typesize != array_typesize) {
12473         // There's a cast to a different size type involved
12474         uint64_t ratio = array_typesize / ptrarith_typesize;
12475         // TODO: Be smarter about handling cases where array_typesize is not a
12476         // multiple of ptrarith_typesize
12477         if (ptrarith_typesize * ratio == array_typesize)
12478           size *= llvm::APInt(size.getBitWidth(), ratio);
12479       }
12480     }
12481 
12482     if (size.getBitWidth() > index.getBitWidth())
12483       index = index.zext(size.getBitWidth());
12484     else if (size.getBitWidth() < index.getBitWidth())
12485       size = size.zext(index.getBitWidth());
12486 
12487     // For array subscripting the index must be less than size, but for pointer
12488     // arithmetic also allow the index (offset) to be equal to size since
12489     // computing the next address after the end of the array is legal and
12490     // commonly done e.g. in C++ iterators and range-based for loops.
12491     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12492       return;
12493 
12494     // Also don't warn for arrays of size 1 which are members of some
12495     // structure. These are often used to approximate flexible arrays in C89
12496     // code.
12497     if (IsTailPaddedMemberArray(*this, size, ND))
12498       return;
12499 
12500     // Suppress the warning if the subscript expression (as identified by the
12501     // ']' location) and the index expression are both from macro expansions
12502     // within a system header.
12503     if (ASE) {
12504       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12505           ASE->getRBracketLoc());
12506       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12507         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
12508             IndexExpr->getLocStart());
12509         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12510           return;
12511       }
12512     }
12513 
12514     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12515     if (ASE)
12516       DiagID = diag::warn_array_index_exceeds_bounds;
12517 
12518     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
12519                         PDiag(DiagID) << index.toString(10, true)
12520                           << size.toString(10, true)
12521                           << (unsigned)size.getLimitedValue(~0U)
12522                           << IndexExpr->getSourceRange());
12523   } else {
12524     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12525     if (!ASE) {
12526       DiagID = diag::warn_ptr_arith_precedes_bounds;
12527       if (index.isNegative()) index = -index;
12528     }
12529 
12530     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
12531                         PDiag(DiagID) << index.toString(10, true)
12532                           << IndexExpr->getSourceRange());
12533   }
12534 
12535   if (!ND) {
12536     // Try harder to find a NamedDecl to point at in the note.
12537     while (const ArraySubscriptExpr *ASE =
12538            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12539       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12540     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12541       ND = DRE->getDecl();
12542     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12543       ND = ME->getMemberDecl();
12544   }
12545 
12546   if (ND)
12547     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
12548                         PDiag(diag::note_array_index_out_of_bounds)
12549                           << ND->getDeclName());
12550 }
12551 
12552 void Sema::CheckArrayAccess(const Expr *expr) {
12553   int AllowOnePastEnd = 0;
12554   while (expr) {
12555     expr = expr->IgnoreParenImpCasts();
12556     switch (expr->getStmtClass()) {
12557       case Stmt::ArraySubscriptExprClass: {
12558         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12559         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12560                          AllowOnePastEnd > 0);
12561         expr = ASE->getBase();
12562         break;
12563       }
12564       case Stmt::MemberExprClass: {
12565         expr = cast<MemberExpr>(expr)->getBase();
12566         break;
12567       }
12568       case Stmt::OMPArraySectionExprClass: {
12569         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12570         if (ASE->getLowerBound())
12571           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12572                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12573         return;
12574       }
12575       case Stmt::UnaryOperatorClass: {
12576         // Only unwrap the * and & unary operators
12577         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12578         expr = UO->getSubExpr();
12579         switch (UO->getOpcode()) {
12580           case UO_AddrOf:
12581             AllowOnePastEnd++;
12582             break;
12583           case UO_Deref:
12584             AllowOnePastEnd--;
12585             break;
12586           default:
12587             return;
12588         }
12589         break;
12590       }
12591       case Stmt::ConditionalOperatorClass: {
12592         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12593         if (const Expr *lhs = cond->getLHS())
12594           CheckArrayAccess(lhs);
12595         if (const Expr *rhs = cond->getRHS())
12596           CheckArrayAccess(rhs);
12597         return;
12598       }
12599       case Stmt::CXXOperatorCallExprClass: {
12600         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12601         for (const auto *Arg : OCE->arguments())
12602           CheckArrayAccess(Arg);
12603         return;
12604       }
12605       default:
12606         return;
12607     }
12608   }
12609 }
12610 
12611 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12612 
12613 namespace {
12614 
12615 struct RetainCycleOwner {
12616   VarDecl *Variable = nullptr;
12617   SourceRange Range;
12618   SourceLocation Loc;
12619   bool Indirect = false;
12620 
12621   RetainCycleOwner() = default;
12622 
12623   void setLocsFrom(Expr *e) {
12624     Loc = e->getExprLoc();
12625     Range = e->getSourceRange();
12626   }
12627 };
12628 
12629 } // namespace
12630 
12631 /// Consider whether capturing the given variable can possibly lead to
12632 /// a retain cycle.
12633 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12634   // In ARC, it's captured strongly iff the variable has __strong
12635   // lifetime.  In MRR, it's captured strongly if the variable is
12636   // __block and has an appropriate type.
12637   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12638     return false;
12639 
12640   owner.Variable = var;
12641   if (ref)
12642     owner.setLocsFrom(ref);
12643   return true;
12644 }
12645 
12646 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12647   while (true) {
12648     e = e->IgnoreParens();
12649     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12650       switch (cast->getCastKind()) {
12651       case CK_BitCast:
12652       case CK_LValueBitCast:
12653       case CK_LValueToRValue:
12654       case CK_ARCReclaimReturnedObject:
12655         e = cast->getSubExpr();
12656         continue;
12657 
12658       default:
12659         return false;
12660       }
12661     }
12662 
12663     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12664       ObjCIvarDecl *ivar = ref->getDecl();
12665       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12666         return false;
12667 
12668       // Try to find a retain cycle in the base.
12669       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12670         return false;
12671 
12672       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12673       owner.Indirect = true;
12674       return true;
12675     }
12676 
12677     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12678       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12679       if (!var) return false;
12680       return considerVariable(var, ref, owner);
12681     }
12682 
12683     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12684       if (member->isArrow()) return false;
12685 
12686       // Don't count this as an indirect ownership.
12687       e = member->getBase();
12688       continue;
12689     }
12690 
12691     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12692       // Only pay attention to pseudo-objects on property references.
12693       ObjCPropertyRefExpr *pre
12694         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12695                                               ->IgnoreParens());
12696       if (!pre) return false;
12697       if (pre->isImplicitProperty()) return false;
12698       ObjCPropertyDecl *property = pre->getExplicitProperty();
12699       if (!property->isRetaining() &&
12700           !(property->getPropertyIvarDecl() &&
12701             property->getPropertyIvarDecl()->getType()
12702               .getObjCLifetime() == Qualifiers::OCL_Strong))
12703           return false;
12704 
12705       owner.Indirect = true;
12706       if (pre->isSuperReceiver()) {
12707         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12708         if (!owner.Variable)
12709           return false;
12710         owner.Loc = pre->getLocation();
12711         owner.Range = pre->getSourceRange();
12712         return true;
12713       }
12714       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12715                               ->getSourceExpr());
12716       continue;
12717     }
12718 
12719     // Array ivars?
12720 
12721     return false;
12722   }
12723 }
12724 
12725 namespace {
12726 
12727   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12728     ASTContext &Context;
12729     VarDecl *Variable;
12730     Expr *Capturer = nullptr;
12731     bool VarWillBeReased = false;
12732 
12733     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12734         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12735           Context(Context), Variable(variable) {}
12736 
12737     void VisitDeclRefExpr(DeclRefExpr *ref) {
12738       if (ref->getDecl() == Variable && !Capturer)
12739         Capturer = ref;
12740     }
12741 
12742     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12743       if (Capturer) return;
12744       Visit(ref->getBase());
12745       if (Capturer && ref->isFreeIvar())
12746         Capturer = ref;
12747     }
12748 
12749     void VisitBlockExpr(BlockExpr *block) {
12750       // Look inside nested blocks
12751       if (block->getBlockDecl()->capturesVariable(Variable))
12752         Visit(block->getBlockDecl()->getBody());
12753     }
12754 
12755     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12756       if (Capturer) return;
12757       if (OVE->getSourceExpr())
12758         Visit(OVE->getSourceExpr());
12759     }
12760 
12761     void VisitBinaryOperator(BinaryOperator *BinOp) {
12762       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12763         return;
12764       Expr *LHS = BinOp->getLHS();
12765       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12766         if (DRE->getDecl() != Variable)
12767           return;
12768         if (Expr *RHS = BinOp->getRHS()) {
12769           RHS = RHS->IgnoreParenCasts();
12770           llvm::APSInt Value;
12771           VarWillBeReased =
12772             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12773         }
12774       }
12775     }
12776   };
12777 
12778 } // namespace
12779 
12780 /// Check whether the given argument is a block which captures a
12781 /// variable.
12782 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12783   assert(owner.Variable && owner.Loc.isValid());
12784 
12785   e = e->IgnoreParenCasts();
12786 
12787   // Look through [^{...} copy] and Block_copy(^{...}).
12788   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12789     Selector Cmd = ME->getSelector();
12790     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12791       e = ME->getInstanceReceiver();
12792       if (!e)
12793         return nullptr;
12794       e = e->IgnoreParenCasts();
12795     }
12796   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12797     if (CE->getNumArgs() == 1) {
12798       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12799       if (Fn) {
12800         const IdentifierInfo *FnI = Fn->getIdentifier();
12801         if (FnI && FnI->isStr("_Block_copy")) {
12802           e = CE->getArg(0)->IgnoreParenCasts();
12803         }
12804       }
12805     }
12806   }
12807 
12808   BlockExpr *block = dyn_cast<BlockExpr>(e);
12809   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12810     return nullptr;
12811 
12812   FindCaptureVisitor visitor(S.Context, owner.Variable);
12813   visitor.Visit(block->getBlockDecl()->getBody());
12814   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12815 }
12816 
12817 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12818                                 RetainCycleOwner &owner) {
12819   assert(capturer);
12820   assert(owner.Variable && owner.Loc.isValid());
12821 
12822   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12823     << owner.Variable << capturer->getSourceRange();
12824   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12825     << owner.Indirect << owner.Range;
12826 }
12827 
12828 /// Check for a keyword selector that starts with the word 'add' or
12829 /// 'set'.
12830 static bool isSetterLikeSelector(Selector sel) {
12831   if (sel.isUnarySelector()) return false;
12832 
12833   StringRef str = sel.getNameForSlot(0);
12834   while (!str.empty() && str.front() == '_') str = str.substr(1);
12835   if (str.startswith("set"))
12836     str = str.substr(3);
12837   else if (str.startswith("add")) {
12838     // Specially whitelist 'addOperationWithBlock:'.
12839     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12840       return false;
12841     str = str.substr(3);
12842   }
12843   else
12844     return false;
12845 
12846   if (str.empty()) return true;
12847   return !isLowercase(str.front());
12848 }
12849 
12850 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12851                                                     ObjCMessageExpr *Message) {
12852   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12853                                                 Message->getReceiverInterface(),
12854                                                 NSAPI::ClassId_NSMutableArray);
12855   if (!IsMutableArray) {
12856     return None;
12857   }
12858 
12859   Selector Sel = Message->getSelector();
12860 
12861   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12862     S.NSAPIObj->getNSArrayMethodKind(Sel);
12863   if (!MKOpt) {
12864     return None;
12865   }
12866 
12867   NSAPI::NSArrayMethodKind MK = *MKOpt;
12868 
12869   switch (MK) {
12870     case NSAPI::NSMutableArr_addObject:
12871     case NSAPI::NSMutableArr_insertObjectAtIndex:
12872     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12873       return 0;
12874     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12875       return 1;
12876 
12877     default:
12878       return None;
12879   }
12880 
12881   return None;
12882 }
12883 
12884 static
12885 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12886                                                   ObjCMessageExpr *Message) {
12887   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12888                                             Message->getReceiverInterface(),
12889                                             NSAPI::ClassId_NSMutableDictionary);
12890   if (!IsMutableDictionary) {
12891     return None;
12892   }
12893 
12894   Selector Sel = Message->getSelector();
12895 
12896   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12897     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12898   if (!MKOpt) {
12899     return None;
12900   }
12901 
12902   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12903 
12904   switch (MK) {
12905     case NSAPI::NSMutableDict_setObjectForKey:
12906     case NSAPI::NSMutableDict_setValueForKey:
12907     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12908       return 0;
12909 
12910     default:
12911       return None;
12912   }
12913 
12914   return None;
12915 }
12916 
12917 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
12918   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12919                                                 Message->getReceiverInterface(),
12920                                                 NSAPI::ClassId_NSMutableSet);
12921 
12922   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12923                                             Message->getReceiverInterface(),
12924                                             NSAPI::ClassId_NSMutableOrderedSet);
12925   if (!IsMutableSet && !IsMutableOrderedSet) {
12926     return None;
12927   }
12928 
12929   Selector Sel = Message->getSelector();
12930 
12931   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12932   if (!MKOpt) {
12933     return None;
12934   }
12935 
12936   NSAPI::NSSetMethodKind MK = *MKOpt;
12937 
12938   switch (MK) {
12939     case NSAPI::NSMutableSet_addObject:
12940     case NSAPI::NSOrderedSet_setObjectAtIndex:
12941     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12942     case NSAPI::NSOrderedSet_insertObjectAtIndex:
12943       return 0;
12944     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12945       return 1;
12946   }
12947 
12948   return None;
12949 }
12950 
12951 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12952   if (!Message->isInstanceMessage()) {
12953     return;
12954   }
12955 
12956   Optional<int> ArgOpt;
12957 
12958   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12959       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12960       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12961     return;
12962   }
12963 
12964   int ArgIndex = *ArgOpt;
12965 
12966   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12967   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12968     Arg = OE->getSourceExpr()->IgnoreImpCasts();
12969   }
12970 
12971   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12972     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12973       if (ArgRE->isObjCSelfExpr()) {
12974         Diag(Message->getSourceRange().getBegin(),
12975              diag::warn_objc_circular_container)
12976           << ArgRE->getDecl() << StringRef("'super'");
12977       }
12978     }
12979   } else {
12980     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12981 
12982     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12983       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12984     }
12985 
12986     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12987       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12988         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12989           ValueDecl *Decl = ReceiverRE->getDecl();
12990           Diag(Message->getSourceRange().getBegin(),
12991                diag::warn_objc_circular_container)
12992             << Decl << Decl;
12993           if (!ArgRE->isObjCSelfExpr()) {
12994             Diag(Decl->getLocation(),
12995                  diag::note_objc_circular_container_declared_here)
12996               << Decl;
12997           }
12998         }
12999       }
13000     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13001       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13002         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13003           ObjCIvarDecl *Decl = IvarRE->getDecl();
13004           Diag(Message->getSourceRange().getBegin(),
13005                diag::warn_objc_circular_container)
13006             << Decl << Decl;
13007           Diag(Decl->getLocation(),
13008                diag::note_objc_circular_container_declared_here)
13009             << Decl;
13010         }
13011       }
13012     }
13013   }
13014 }
13015 
13016 /// Check a message send to see if it's likely to cause a retain cycle.
13017 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13018   // Only check instance methods whose selector looks like a setter.
13019   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13020     return;
13021 
13022   // Try to find a variable that the receiver is strongly owned by.
13023   RetainCycleOwner owner;
13024   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13025     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13026       return;
13027   } else {
13028     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13029     owner.Variable = getCurMethodDecl()->getSelfDecl();
13030     owner.Loc = msg->getSuperLoc();
13031     owner.Range = msg->getSuperLoc();
13032   }
13033 
13034   // Check whether the receiver is captured by any of the arguments.
13035   const ObjCMethodDecl *MD = msg->getMethodDecl();
13036   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13037     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13038       // noescape blocks should not be retained by the method.
13039       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13040         continue;
13041       return diagnoseRetainCycle(*this, capturer, owner);
13042     }
13043   }
13044 }
13045 
13046 /// Check a property assign to see if it's likely to cause a retain cycle.
13047 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13048   RetainCycleOwner owner;
13049   if (!findRetainCycleOwner(*this, receiver, owner))
13050     return;
13051 
13052   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13053     diagnoseRetainCycle(*this, capturer, owner);
13054 }
13055 
13056 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13057   RetainCycleOwner Owner;
13058   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13059     return;
13060 
13061   // Because we don't have an expression for the variable, we have to set the
13062   // location explicitly here.
13063   Owner.Loc = Var->getLocation();
13064   Owner.Range = Var->getSourceRange();
13065 
13066   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13067     diagnoseRetainCycle(*this, Capturer, Owner);
13068 }
13069 
13070 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13071                                      Expr *RHS, bool isProperty) {
13072   // Check if RHS is an Objective-C object literal, which also can get
13073   // immediately zapped in a weak reference.  Note that we explicitly
13074   // allow ObjCStringLiterals, since those are designed to never really die.
13075   RHS = RHS->IgnoreParenImpCasts();
13076 
13077   // This enum needs to match with the 'select' in
13078   // warn_objc_arc_literal_assign (off-by-1).
13079   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13080   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13081     return false;
13082 
13083   S.Diag(Loc, diag::warn_arc_literal_assign)
13084     << (unsigned) Kind
13085     << (isProperty ? 0 : 1)
13086     << RHS->getSourceRange();
13087 
13088   return true;
13089 }
13090 
13091 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13092                                     Qualifiers::ObjCLifetime LT,
13093                                     Expr *RHS, bool isProperty) {
13094   // Strip off any implicit cast added to get to the one ARC-specific.
13095   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13096     if (cast->getCastKind() == CK_ARCConsumeObject) {
13097       S.Diag(Loc, diag::warn_arc_retained_assign)
13098         << (LT == Qualifiers::OCL_ExplicitNone)
13099         << (isProperty ? 0 : 1)
13100         << RHS->getSourceRange();
13101       return true;
13102     }
13103     RHS = cast->getSubExpr();
13104   }
13105 
13106   if (LT == Qualifiers::OCL_Weak &&
13107       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13108     return true;
13109 
13110   return false;
13111 }
13112 
13113 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13114                               QualType LHS, Expr *RHS) {
13115   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13116 
13117   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13118     return false;
13119 
13120   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13121     return true;
13122 
13123   return false;
13124 }
13125 
13126 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13127                               Expr *LHS, Expr *RHS) {
13128   QualType LHSType;
13129   // PropertyRef on LHS type need be directly obtained from
13130   // its declaration as it has a PseudoType.
13131   ObjCPropertyRefExpr *PRE
13132     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13133   if (PRE && !PRE->isImplicitProperty()) {
13134     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13135     if (PD)
13136       LHSType = PD->getType();
13137   }
13138 
13139   if (LHSType.isNull())
13140     LHSType = LHS->getType();
13141 
13142   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13143 
13144   if (LT == Qualifiers::OCL_Weak) {
13145     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13146       getCurFunction()->markSafeWeakUse(LHS);
13147   }
13148 
13149   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13150     return;
13151 
13152   // FIXME. Check for other life times.
13153   if (LT != Qualifiers::OCL_None)
13154     return;
13155 
13156   if (PRE) {
13157     if (PRE->isImplicitProperty())
13158       return;
13159     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13160     if (!PD)
13161       return;
13162 
13163     unsigned Attributes = PD->getPropertyAttributes();
13164     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13165       // when 'assign' attribute was not explicitly specified
13166       // by user, ignore it and rely on property type itself
13167       // for lifetime info.
13168       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13169       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13170           LHSType->isObjCRetainableType())
13171         return;
13172 
13173       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13174         if (cast->getCastKind() == CK_ARCConsumeObject) {
13175           Diag(Loc, diag::warn_arc_retained_property_assign)
13176           << RHS->getSourceRange();
13177           return;
13178         }
13179         RHS = cast->getSubExpr();
13180       }
13181     }
13182     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13183       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13184         return;
13185     }
13186   }
13187 }
13188 
13189 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13190 
13191 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13192                                         SourceLocation StmtLoc,
13193                                         const NullStmt *Body) {
13194   // Do not warn if the body is a macro that expands to nothing, e.g:
13195   //
13196   // #define CALL(x)
13197   // if (condition)
13198   //   CALL(0);
13199   if (Body->hasLeadingEmptyMacro())
13200     return false;
13201 
13202   // Get line numbers of statement and body.
13203   bool StmtLineInvalid;
13204   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13205                                                       &StmtLineInvalid);
13206   if (StmtLineInvalid)
13207     return false;
13208 
13209   bool BodyLineInvalid;
13210   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13211                                                       &BodyLineInvalid);
13212   if (BodyLineInvalid)
13213     return false;
13214 
13215   // Warn if null statement and body are on the same line.
13216   if (StmtLine != BodyLine)
13217     return false;
13218 
13219   return true;
13220 }
13221 
13222 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13223                                  const Stmt *Body,
13224                                  unsigned DiagID) {
13225   // Since this is a syntactic check, don't emit diagnostic for template
13226   // instantiations, this just adds noise.
13227   if (CurrentInstantiationScope)
13228     return;
13229 
13230   // The body should be a null statement.
13231   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13232   if (!NBody)
13233     return;
13234 
13235   // Do the usual checks.
13236   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13237     return;
13238 
13239   Diag(NBody->getSemiLoc(), DiagID);
13240   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13241 }
13242 
13243 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13244                                  const Stmt *PossibleBody) {
13245   assert(!CurrentInstantiationScope); // Ensured by caller
13246 
13247   SourceLocation StmtLoc;
13248   const Stmt *Body;
13249   unsigned DiagID;
13250   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13251     StmtLoc = FS->getRParenLoc();
13252     Body = FS->getBody();
13253     DiagID = diag::warn_empty_for_body;
13254   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13255     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13256     Body = WS->getBody();
13257     DiagID = diag::warn_empty_while_body;
13258   } else
13259     return; // Neither `for' nor `while'.
13260 
13261   // The body should be a null statement.
13262   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13263   if (!NBody)
13264     return;
13265 
13266   // Skip expensive checks if diagnostic is disabled.
13267   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13268     return;
13269 
13270   // Do the usual checks.
13271   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13272     return;
13273 
13274   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13275   // noise level low, emit diagnostics only if for/while is followed by a
13276   // CompoundStmt, e.g.:
13277   //    for (int i = 0; i < n; i++);
13278   //    {
13279   //      a(i);
13280   //    }
13281   // or if for/while is followed by a statement with more indentation
13282   // than for/while itself:
13283   //    for (int i = 0; i < n; i++);
13284   //      a(i);
13285   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13286   if (!ProbableTypo) {
13287     bool BodyColInvalid;
13288     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13289                              PossibleBody->getLocStart(),
13290                              &BodyColInvalid);
13291     if (BodyColInvalid)
13292       return;
13293 
13294     bool StmtColInvalid;
13295     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
13296                              S->getLocStart(),
13297                              &StmtColInvalid);
13298     if (StmtColInvalid)
13299       return;
13300 
13301     if (BodyCol > StmtCol)
13302       ProbableTypo = true;
13303   }
13304 
13305   if (ProbableTypo) {
13306     Diag(NBody->getSemiLoc(), DiagID);
13307     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13308   }
13309 }
13310 
13311 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13312 
13313 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13314 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13315                              SourceLocation OpLoc) {
13316   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13317     return;
13318 
13319   if (inTemplateInstantiation())
13320     return;
13321 
13322   // Strip parens and casts away.
13323   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13324   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13325 
13326   // Check for a call expression
13327   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13328   if (!CE || CE->getNumArgs() != 1)
13329     return;
13330 
13331   // Check for a call to std::move
13332   if (!CE->isCallToStdMove())
13333     return;
13334 
13335   // Get argument from std::move
13336   RHSExpr = CE->getArg(0);
13337 
13338   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13339   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13340 
13341   // Two DeclRefExpr's, check that the decls are the same.
13342   if (LHSDeclRef && RHSDeclRef) {
13343     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13344       return;
13345     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13346         RHSDeclRef->getDecl()->getCanonicalDecl())
13347       return;
13348 
13349     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13350                                         << LHSExpr->getSourceRange()
13351                                         << RHSExpr->getSourceRange();
13352     return;
13353   }
13354 
13355   // Member variables require a different approach to check for self moves.
13356   // MemberExpr's are the same if every nested MemberExpr refers to the same
13357   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13358   // the base Expr's are CXXThisExpr's.
13359   const Expr *LHSBase = LHSExpr;
13360   const Expr *RHSBase = RHSExpr;
13361   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13362   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13363   if (!LHSME || !RHSME)
13364     return;
13365 
13366   while (LHSME && RHSME) {
13367     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13368         RHSME->getMemberDecl()->getCanonicalDecl())
13369       return;
13370 
13371     LHSBase = LHSME->getBase();
13372     RHSBase = RHSME->getBase();
13373     LHSME = dyn_cast<MemberExpr>(LHSBase);
13374     RHSME = dyn_cast<MemberExpr>(RHSBase);
13375   }
13376 
13377   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13378   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13379   if (LHSDeclRef && RHSDeclRef) {
13380     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13381       return;
13382     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13383         RHSDeclRef->getDecl()->getCanonicalDecl())
13384       return;
13385 
13386     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13387                                         << LHSExpr->getSourceRange()
13388                                         << RHSExpr->getSourceRange();
13389     return;
13390   }
13391 
13392   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13393     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13394                                         << LHSExpr->getSourceRange()
13395                                         << RHSExpr->getSourceRange();
13396 }
13397 
13398 //===--- Layout compatibility ----------------------------------------------//
13399 
13400 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13401 
13402 /// Check if two enumeration types are layout-compatible.
13403 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13404   // C++11 [dcl.enum] p8:
13405   // Two enumeration types are layout-compatible if they have the same
13406   // underlying type.
13407   return ED1->isComplete() && ED2->isComplete() &&
13408          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13409 }
13410 
13411 /// Check if two fields are layout-compatible.
13412 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13413                                FieldDecl *Field2) {
13414   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13415     return false;
13416 
13417   if (Field1->isBitField() != Field2->isBitField())
13418     return false;
13419 
13420   if (Field1->isBitField()) {
13421     // Make sure that the bit-fields are the same length.
13422     unsigned Bits1 = Field1->getBitWidthValue(C);
13423     unsigned Bits2 = Field2->getBitWidthValue(C);
13424 
13425     if (Bits1 != Bits2)
13426       return false;
13427   }
13428 
13429   return true;
13430 }
13431 
13432 /// Check if two standard-layout structs are layout-compatible.
13433 /// (C++11 [class.mem] p17)
13434 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13435                                      RecordDecl *RD2) {
13436   // If both records are C++ classes, check that base classes match.
13437   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13438     // If one of records is a CXXRecordDecl we are in C++ mode,
13439     // thus the other one is a CXXRecordDecl, too.
13440     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13441     // Check number of base classes.
13442     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13443       return false;
13444 
13445     // Check the base classes.
13446     for (CXXRecordDecl::base_class_const_iterator
13447                Base1 = D1CXX->bases_begin(),
13448            BaseEnd1 = D1CXX->bases_end(),
13449               Base2 = D2CXX->bases_begin();
13450          Base1 != BaseEnd1;
13451          ++Base1, ++Base2) {
13452       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13453         return false;
13454     }
13455   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13456     // If only RD2 is a C++ class, it should have zero base classes.
13457     if (D2CXX->getNumBases() > 0)
13458       return false;
13459   }
13460 
13461   // Check the fields.
13462   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13463                              Field2End = RD2->field_end(),
13464                              Field1 = RD1->field_begin(),
13465                              Field1End = RD1->field_end();
13466   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13467     if (!isLayoutCompatible(C, *Field1, *Field2))
13468       return false;
13469   }
13470   if (Field1 != Field1End || Field2 != Field2End)
13471     return false;
13472 
13473   return true;
13474 }
13475 
13476 /// Check if two standard-layout unions are layout-compatible.
13477 /// (C++11 [class.mem] p18)
13478 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13479                                     RecordDecl *RD2) {
13480   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13481   for (auto *Field2 : RD2->fields())
13482     UnmatchedFields.insert(Field2);
13483 
13484   for (auto *Field1 : RD1->fields()) {
13485     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13486         I = UnmatchedFields.begin(),
13487         E = UnmatchedFields.end();
13488 
13489     for ( ; I != E; ++I) {
13490       if (isLayoutCompatible(C, Field1, *I)) {
13491         bool Result = UnmatchedFields.erase(*I);
13492         (void) Result;
13493         assert(Result);
13494         break;
13495       }
13496     }
13497     if (I == E)
13498       return false;
13499   }
13500 
13501   return UnmatchedFields.empty();
13502 }
13503 
13504 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13505                                RecordDecl *RD2) {
13506   if (RD1->isUnion() != RD2->isUnion())
13507     return false;
13508 
13509   if (RD1->isUnion())
13510     return isLayoutCompatibleUnion(C, RD1, RD2);
13511   else
13512     return isLayoutCompatibleStruct(C, RD1, RD2);
13513 }
13514 
13515 /// Check if two types are layout-compatible in C++11 sense.
13516 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13517   if (T1.isNull() || T2.isNull())
13518     return false;
13519 
13520   // C++11 [basic.types] p11:
13521   // If two types T1 and T2 are the same type, then T1 and T2 are
13522   // layout-compatible types.
13523   if (C.hasSameType(T1, T2))
13524     return true;
13525 
13526   T1 = T1.getCanonicalType().getUnqualifiedType();
13527   T2 = T2.getCanonicalType().getUnqualifiedType();
13528 
13529   const Type::TypeClass TC1 = T1->getTypeClass();
13530   const Type::TypeClass TC2 = T2->getTypeClass();
13531 
13532   if (TC1 != TC2)
13533     return false;
13534 
13535   if (TC1 == Type::Enum) {
13536     return isLayoutCompatible(C,
13537                               cast<EnumType>(T1)->getDecl(),
13538                               cast<EnumType>(T2)->getDecl());
13539   } else if (TC1 == Type::Record) {
13540     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13541       return false;
13542 
13543     return isLayoutCompatible(C,
13544                               cast<RecordType>(T1)->getDecl(),
13545                               cast<RecordType>(T2)->getDecl());
13546   }
13547 
13548   return false;
13549 }
13550 
13551 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13552 
13553 /// Given a type tag expression find the type tag itself.
13554 ///
13555 /// \param TypeExpr Type tag expression, as it appears in user's code.
13556 ///
13557 /// \param VD Declaration of an identifier that appears in a type tag.
13558 ///
13559 /// \param MagicValue Type tag magic value.
13560 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13561                             const ValueDecl **VD, uint64_t *MagicValue) {
13562   while(true) {
13563     if (!TypeExpr)
13564       return false;
13565 
13566     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13567 
13568     switch (TypeExpr->getStmtClass()) {
13569     case Stmt::UnaryOperatorClass: {
13570       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13571       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13572         TypeExpr = UO->getSubExpr();
13573         continue;
13574       }
13575       return false;
13576     }
13577 
13578     case Stmt::DeclRefExprClass: {
13579       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13580       *VD = DRE->getDecl();
13581       return true;
13582     }
13583 
13584     case Stmt::IntegerLiteralClass: {
13585       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13586       llvm::APInt MagicValueAPInt = IL->getValue();
13587       if (MagicValueAPInt.getActiveBits() <= 64) {
13588         *MagicValue = MagicValueAPInt.getZExtValue();
13589         return true;
13590       } else
13591         return false;
13592     }
13593 
13594     case Stmt::BinaryConditionalOperatorClass:
13595     case Stmt::ConditionalOperatorClass: {
13596       const AbstractConditionalOperator *ACO =
13597           cast<AbstractConditionalOperator>(TypeExpr);
13598       bool Result;
13599       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13600         if (Result)
13601           TypeExpr = ACO->getTrueExpr();
13602         else
13603           TypeExpr = ACO->getFalseExpr();
13604         continue;
13605       }
13606       return false;
13607     }
13608 
13609     case Stmt::BinaryOperatorClass: {
13610       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13611       if (BO->getOpcode() == BO_Comma) {
13612         TypeExpr = BO->getRHS();
13613         continue;
13614       }
13615       return false;
13616     }
13617 
13618     default:
13619       return false;
13620     }
13621   }
13622 }
13623 
13624 /// Retrieve the C type corresponding to type tag TypeExpr.
13625 ///
13626 /// \param TypeExpr Expression that specifies a type tag.
13627 ///
13628 /// \param MagicValues Registered magic values.
13629 ///
13630 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13631 ///        kind.
13632 ///
13633 /// \param TypeInfo Information about the corresponding C type.
13634 ///
13635 /// \returns true if the corresponding C type was found.
13636 static bool GetMatchingCType(
13637         const IdentifierInfo *ArgumentKind,
13638         const Expr *TypeExpr, const ASTContext &Ctx,
13639         const llvm::DenseMap<Sema::TypeTagMagicValue,
13640                              Sema::TypeTagData> *MagicValues,
13641         bool &FoundWrongKind,
13642         Sema::TypeTagData &TypeInfo) {
13643   FoundWrongKind = false;
13644 
13645   // Variable declaration that has type_tag_for_datatype attribute.
13646   const ValueDecl *VD = nullptr;
13647 
13648   uint64_t MagicValue;
13649 
13650   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13651     return false;
13652 
13653   if (VD) {
13654     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13655       if (I->getArgumentKind() != ArgumentKind) {
13656         FoundWrongKind = true;
13657         return false;
13658       }
13659       TypeInfo.Type = I->getMatchingCType();
13660       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13661       TypeInfo.MustBeNull = I->getMustBeNull();
13662       return true;
13663     }
13664     return false;
13665   }
13666 
13667   if (!MagicValues)
13668     return false;
13669 
13670   llvm::DenseMap<Sema::TypeTagMagicValue,
13671                  Sema::TypeTagData>::const_iterator I =
13672       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13673   if (I == MagicValues->end())
13674     return false;
13675 
13676   TypeInfo = I->second;
13677   return true;
13678 }
13679 
13680 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13681                                       uint64_t MagicValue, QualType Type,
13682                                       bool LayoutCompatible,
13683                                       bool MustBeNull) {
13684   if (!TypeTagForDatatypeMagicValues)
13685     TypeTagForDatatypeMagicValues.reset(
13686         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13687 
13688   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13689   (*TypeTagForDatatypeMagicValues)[Magic] =
13690       TypeTagData(Type, LayoutCompatible, MustBeNull);
13691 }
13692 
13693 static bool IsSameCharType(QualType T1, QualType T2) {
13694   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13695   if (!BT1)
13696     return false;
13697 
13698   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13699   if (!BT2)
13700     return false;
13701 
13702   BuiltinType::Kind T1Kind = BT1->getKind();
13703   BuiltinType::Kind T2Kind = BT2->getKind();
13704 
13705   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13706          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13707          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13708          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13709 }
13710 
13711 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13712                                     const ArrayRef<const Expr *> ExprArgs,
13713                                     SourceLocation CallSiteLoc) {
13714   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13715   bool IsPointerAttr = Attr->getIsPointer();
13716 
13717   // Retrieve the argument representing the 'type_tag'.
13718   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13719   if (TypeTagIdxAST >= ExprArgs.size()) {
13720     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13721         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13722     return;
13723   }
13724   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13725   bool FoundWrongKind;
13726   TypeTagData TypeInfo;
13727   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13728                         TypeTagForDatatypeMagicValues.get(),
13729                         FoundWrongKind, TypeInfo)) {
13730     if (FoundWrongKind)
13731       Diag(TypeTagExpr->getExprLoc(),
13732            diag::warn_type_tag_for_datatype_wrong_kind)
13733         << TypeTagExpr->getSourceRange();
13734     return;
13735   }
13736 
13737   // Retrieve the argument representing the 'arg_idx'.
13738   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13739   if (ArgumentIdxAST >= ExprArgs.size()) {
13740     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13741         << 1 << Attr->getArgumentIdx().getSourceIndex();
13742     return;
13743   }
13744   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
13745   if (IsPointerAttr) {
13746     // Skip implicit cast of pointer to `void *' (as a function argument).
13747     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
13748       if (ICE->getType()->isVoidPointerType() &&
13749           ICE->getCastKind() == CK_BitCast)
13750         ArgumentExpr = ICE->getSubExpr();
13751   }
13752   QualType ArgumentType = ArgumentExpr->getType();
13753 
13754   // Passing a `void*' pointer shouldn't trigger a warning.
13755   if (IsPointerAttr && ArgumentType->isVoidPointerType())
13756     return;
13757 
13758   if (TypeInfo.MustBeNull) {
13759     // Type tag with matching void type requires a null pointer.
13760     if (!ArgumentExpr->isNullPointerConstant(Context,
13761                                              Expr::NPC_ValueDependentIsNotNull)) {
13762       Diag(ArgumentExpr->getExprLoc(),
13763            diag::warn_type_safety_null_pointer_required)
13764           << ArgumentKind->getName()
13765           << ArgumentExpr->getSourceRange()
13766           << TypeTagExpr->getSourceRange();
13767     }
13768     return;
13769   }
13770 
13771   QualType RequiredType = TypeInfo.Type;
13772   if (IsPointerAttr)
13773     RequiredType = Context.getPointerType(RequiredType);
13774 
13775   bool mismatch = false;
13776   if (!TypeInfo.LayoutCompatible) {
13777     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13778 
13779     // C++11 [basic.fundamental] p1:
13780     // Plain char, signed char, and unsigned char are three distinct types.
13781     //
13782     // But we treat plain `char' as equivalent to `signed char' or `unsigned
13783     // char' depending on the current char signedness mode.
13784     if (mismatch)
13785       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13786                                            RequiredType->getPointeeType())) ||
13787           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13788         mismatch = false;
13789   } else
13790     if (IsPointerAttr)
13791       mismatch = !isLayoutCompatible(Context,
13792                                      ArgumentType->getPointeeType(),
13793                                      RequiredType->getPointeeType());
13794     else
13795       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13796 
13797   if (mismatch)
13798     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13799         << ArgumentType << ArgumentKind
13800         << TypeInfo.LayoutCompatible << RequiredType
13801         << ArgumentExpr->getSourceRange()
13802         << TypeTagExpr->getSourceRange();
13803 }
13804 
13805 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13806                                          CharUnits Alignment) {
13807   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13808 }
13809 
13810 void Sema::DiagnoseMisalignedMembers() {
13811   for (MisalignedMember &m : MisalignedMembers) {
13812     const NamedDecl *ND = m.RD;
13813     if (ND->getName().empty()) {
13814       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13815         ND = TD;
13816     }
13817     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
13818         << m.MD << ND << m.E->getSourceRange();
13819   }
13820   MisalignedMembers.clear();
13821 }
13822 
13823 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13824   E = E->IgnoreParens();
13825   if (!T->isPointerType() && !T->isIntegerType())
13826     return;
13827   if (isa<UnaryOperator>(E) &&
13828       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13829     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13830     if (isa<MemberExpr>(Op)) {
13831       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13832                           MisalignedMember(Op));
13833       if (MA != MisalignedMembers.end() &&
13834           (T->isIntegerType() ||
13835            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13836                                    Context.getTypeAlignInChars(
13837                                        T->getPointeeType()) <= MA->Alignment))))
13838         MisalignedMembers.erase(MA);
13839     }
13840   }
13841 }
13842 
13843 void Sema::RefersToMemberWithReducedAlignment(
13844     Expr *E,
13845     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13846         Action) {
13847   const auto *ME = dyn_cast<MemberExpr>(E);
13848   if (!ME)
13849     return;
13850 
13851   // No need to check expressions with an __unaligned-qualified type.
13852   if (E->getType().getQualifiers().hasUnaligned())
13853     return;
13854 
13855   // For a chain of MemberExpr like "a.b.c.d" this list
13856   // will keep FieldDecl's like [d, c, b].
13857   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13858   const MemberExpr *TopME = nullptr;
13859   bool AnyIsPacked = false;
13860   do {
13861     QualType BaseType = ME->getBase()->getType();
13862     if (ME->isArrow())
13863       BaseType = BaseType->getPointeeType();
13864     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13865     if (RD->isInvalidDecl())
13866       return;
13867 
13868     ValueDecl *MD = ME->getMemberDecl();
13869     auto *FD = dyn_cast<FieldDecl>(MD);
13870     // We do not care about non-data members.
13871     if (!FD || FD->isInvalidDecl())
13872       return;
13873 
13874     AnyIsPacked =
13875         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13876     ReverseMemberChain.push_back(FD);
13877 
13878     TopME = ME;
13879     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13880   } while (ME);
13881   assert(TopME && "We did not compute a topmost MemberExpr!");
13882 
13883   // Not the scope of this diagnostic.
13884   if (!AnyIsPacked)
13885     return;
13886 
13887   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13888   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13889   // TODO: The innermost base of the member expression may be too complicated.
13890   // For now, just disregard these cases. This is left for future
13891   // improvement.
13892   if (!DRE && !isa<CXXThisExpr>(TopBase))
13893       return;
13894 
13895   // Alignment expected by the whole expression.
13896   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13897 
13898   // No need to do anything else with this case.
13899   if (ExpectedAlignment.isOne())
13900     return;
13901 
13902   // Synthesize offset of the whole access.
13903   CharUnits Offset;
13904   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13905        I++) {
13906     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13907   }
13908 
13909   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13910   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13911       ReverseMemberChain.back()->getParent()->getTypeForDecl());
13912 
13913   // The base expression of the innermost MemberExpr may give
13914   // stronger guarantees than the class containing the member.
13915   if (DRE && !TopME->isArrow()) {
13916     const ValueDecl *VD = DRE->getDecl();
13917     if (!VD->getType()->isReferenceType())
13918       CompleteObjectAlignment =
13919           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13920   }
13921 
13922   // Check if the synthesized offset fulfills the alignment.
13923   if (Offset % ExpectedAlignment != 0 ||
13924       // It may fulfill the offset it but the effective alignment may still be
13925       // lower than the expected expression alignment.
13926       CompleteObjectAlignment < ExpectedAlignment) {
13927     // If this happens, we want to determine a sensible culprit of this.
13928     // Intuitively, watching the chain of member expressions from right to
13929     // left, we start with the required alignment (as required by the field
13930     // type) but some packed attribute in that chain has reduced the alignment.
13931     // It may happen that another packed structure increases it again. But if
13932     // we are here such increase has not been enough. So pointing the first
13933     // FieldDecl that either is packed or else its RecordDecl is,
13934     // seems reasonable.
13935     FieldDecl *FD = nullptr;
13936     CharUnits Alignment;
13937     for (FieldDecl *FDI : ReverseMemberChain) {
13938       if (FDI->hasAttr<PackedAttr>() ||
13939           FDI->getParent()->hasAttr<PackedAttr>()) {
13940         FD = FDI;
13941         Alignment = std::min(
13942             Context.getTypeAlignInChars(FD->getType()),
13943             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13944         break;
13945       }
13946     }
13947     assert(FD && "We did not find a packed FieldDecl!");
13948     Action(E, FD->getParent(), FD, Alignment);
13949   }
13950 }
13951 
13952 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13953   using namespace std::placeholders;
13954 
13955   RefersToMemberWithReducedAlignment(
13956       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13957                      _2, _3, _4));
13958 }
13959