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/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
43 
44 using namespace clang;
45 using namespace sema;
46 
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48                                                     unsigned ByteNo) const {
49   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50                                Context.getTargetInfo());
51 }
52 
53 /// Checks that a call expression's argument count is the desired number.
54 /// This is useful when doing custom type-checking.  Returns true on error.
55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56   unsigned argCount = call->getNumArgs();
57   if (argCount == desiredArgCount) return false;
58 
59   if (argCount < desiredArgCount)
60     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61         << 0 /*function call*/ << desiredArgCount << argCount
62         << call->getSourceRange();
63 
64   // Highlight all the excess arguments.
65   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66                     call->getArg(argCount - 1)->getLocEnd());
67 
68   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69     << 0 /*function call*/ << desiredArgCount << argCount
70     << call->getArg(1)->getSourceRange();
71 }
72 
73 /// Check that the first argument to __builtin_annotation is an integer
74 /// and the second argument is a non-wide string literal.
75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76   if (checkArgCount(S, TheCall, 2))
77     return true;
78 
79   // First argument should be an integer.
80   Expr *ValArg = TheCall->getArg(0);
81   QualType Ty = ValArg->getType();
82   if (!Ty->isIntegerType()) {
83     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84       << ValArg->getSourceRange();
85     return true;
86   }
87 
88   // Second argument should be a constant string.
89   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91   if (!Literal || !Literal->isAscii()) {
92     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93       << StrArg->getSourceRange();
94     return true;
95   }
96 
97   TheCall->setType(Ty);
98   return false;
99 }
100 
101 /// Check that the argument to __builtin_addressof is a glvalue, and set the
102 /// result type to the corresponding pointer type.
103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104   if (checkArgCount(S, TheCall, 1))
105     return true;
106 
107   ExprResult Arg(TheCall->getArg(0));
108   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109   if (ResultType.isNull())
110     return true;
111 
112   TheCall->setArg(0, Arg.get());
113   TheCall->setType(ResultType);
114   return false;
115 }
116 
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118   if (checkArgCount(S, TheCall, 3))
119     return true;
120 
121   // First two arguments should be integers.
122   for (unsigned I = 0; I < 2; ++I) {
123     Expr *Arg = TheCall->getArg(I);
124     QualType Ty = Arg->getType();
125     if (!Ty->isIntegerType()) {
126       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127           << Ty << Arg->getSourceRange();
128       return true;
129     }
130   }
131 
132   // Third argument should be a pointer to a non-const integer.
133   // IRGen correctly handles volatile, restrict, and address spaces, and
134   // the other qualifiers aren't possible.
135   {
136     Expr *Arg = TheCall->getArg(2);
137     QualType Ty = Arg->getType();
138     const auto *PtrTy = Ty->getAs<PointerType>();
139     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140           !PtrTy->getPointeeType().isConstQualified())) {
141       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142           << Ty << Arg->getSourceRange();
143       return true;
144     }
145   }
146 
147   return false;
148 }
149 
150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 		                  CallExpr *TheCall, unsigned SizeIdx,
152                                   unsigned DstSizeIdx) {
153   if (TheCall->getNumArgs() <= SizeIdx ||
154       TheCall->getNumArgs() <= DstSizeIdx)
155     return;
156 
157   const Expr *SizeArg = TheCall->getArg(SizeIdx);
158   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159 
160   llvm::APSInt Size, DstSize;
161 
162   // find out if both sizes are known at compile time
163   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165     return;
166 
167   if (Size.ule(DstSize))
168     return;
169 
170   // confirmed overflow so generate the diagnostic.
171   IdentifierInfo *FnName = FDecl->getIdentifier();
172   SourceLocation SL = TheCall->getLocStart();
173   SourceRange SR = TheCall->getSourceRange();
174 
175   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176 }
177 
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179   if (checkArgCount(S, BuiltinCall, 2))
180     return true;
181 
182   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184   Expr *Call = BuiltinCall->getArg(0);
185   Expr *Chain = BuiltinCall->getArg(1);
186 
187   if (Call->getStmtClass() != Stmt::CallExprClass) {
188     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189         << Call->getSourceRange();
190     return true;
191   }
192 
193   auto CE = cast<CallExpr>(Call);
194   if (CE->getCallee()->getType()->isBlockPointerType()) {
195     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196         << Call->getSourceRange();
197     return true;
198   }
199 
200   const Decl *TargetDecl = CE->getCalleeDecl();
201   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202     if (FD->getBuiltinID()) {
203       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204           << Call->getSourceRange();
205       return true;
206     }
207 
208   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210         << Call->getSourceRange();
211     return true;
212   }
213 
214   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215   if (ChainResult.isInvalid())
216     return true;
217   if (!ChainResult.get()->getType()->isPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219         << Chain->getSourceRange();
220     return true;
221   }
222 
223   QualType ReturnTy = CE->getCallReturnType(S.Context);
224   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225   QualType BuiltinTy = S.Context.getFunctionType(
226       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228 
229   Builtin =
230       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231 
232   BuiltinCall->setType(CE->getType());
233   BuiltinCall->setValueKind(CE->getValueKind());
234   BuiltinCall->setObjectKind(CE->getObjectKind());
235   BuiltinCall->setCallee(Builtin);
236   BuiltinCall->setArg(1, ChainResult.get());
237 
238   return false;
239 }
240 
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242                                      Scope::ScopeFlags NeededScopeFlags,
243                                      unsigned DiagID) {
244   // Scopes aren't available during instantiation. Fortunately, builtin
245   // functions cannot be template args so they cannot be formed through template
246   // instantiation. Therefore checking once during the parse is sufficient.
247   if (!SemaRef.ActiveTemplateInstantiations.empty())
248     return false;
249 
250   Scope *S = SemaRef.getCurScope();
251   while (S && !S->isSEHExceptScope())
252     S = S->getParent();
253   if (!S || !(S->getFlags() & NeededScopeFlags)) {
254     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256         << DRE->getDecl()->getIdentifier();
257     return true;
258   }
259 
260   return false;
261 }
262 
263 static inline bool isBlockPointer(Expr *Arg) {
264   return Arg->getType()->isBlockPointerType();
265 }
266 
267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268 /// void*, which is a requirement of device side enqueue.
269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270   const BlockPointerType *BPT =
271       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272   ArrayRef<QualType> Params =
273       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274   unsigned ArgCounter = 0;
275   bool IllegalParams = false;
276   // Iterate through the block parameters until either one is found that is not
277   // a local void*, or the block is valid.
278   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279        I != E; ++I, ++ArgCounter) {
280     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282             LangAS::opencl_local) {
283       // Get the location of the error. If a block literal has been passed
284       // (BlockExpr) then we can point straight to the offending argument,
285       // else we just point to the variable reference.
286       SourceLocation ErrorLoc;
287       if (isa<BlockExpr>(BlockArg)) {
288         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290       } else if (isa<DeclRefExpr>(BlockArg)) {
291         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292       }
293       S.Diag(ErrorLoc,
294              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295       IllegalParams = true;
296     }
297   }
298 
299   return IllegalParams;
300 }
301 
302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303 /// get_kernel_work_group_size
304 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306   if (checkArgCount(S, TheCall, 1))
307     return true;
308 
309   Expr *BlockArg = TheCall->getArg(0);
310   if (!isBlockPointer(BlockArg)) {
311     S.Diag(BlockArg->getLocStart(),
312            diag::err_opencl_enqueue_kernel_expected_type) << "block";
313     return true;
314   }
315   return checkOpenCLBlockArgs(S, BlockArg);
316 }
317 
318 /// Diagnose integer type and any valid implicit convertion to it.
319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320                                       const QualType &IntType);
321 
322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
323                                             unsigned Start, unsigned End) {
324   bool IllegalParams = false;
325   for (unsigned I = Start; I <= End; ++I)
326     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327                                               S.Context.getSizeType());
328   return IllegalParams;
329 }
330 
331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332 /// 'local void*' parameter of passed block.
333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
334                                            Expr *BlockArg,
335                                            unsigned NumNonVarArgs) {
336   const BlockPointerType *BPT =
337       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338   unsigned NumBlockParams =
339       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340   unsigned TotalNumArgs = TheCall->getNumArgs();
341 
342   // For each argument passed to the block, a corresponding uint needs to
343   // be passed to describe the size of the local memory.
344   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345     S.Diag(TheCall->getLocStart(),
346            diag::err_opencl_enqueue_kernel_local_size_args);
347     return true;
348   }
349 
350   // Check that the sizes of the local memory are specified by integers.
351   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
352                                          TotalNumArgs - 1);
353 }
354 
355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356 /// overload formats specified in Table 6.13.17.1.
357 /// int enqueue_kernel(queue_t queue,
358 ///                    kernel_enqueue_flags_t flags,
359 ///                    const ndrange_t ndrange,
360 ///                    void (^block)(void))
361 /// int enqueue_kernel(queue_t queue,
362 ///                    kernel_enqueue_flags_t flags,
363 ///                    const ndrange_t ndrange,
364 ///                    uint num_events_in_wait_list,
365 ///                    clk_event_t *event_wait_list,
366 ///                    clk_event_t *event_ret,
367 ///                    void (^block)(void))
368 /// int enqueue_kernel(queue_t queue,
369 ///                    kernel_enqueue_flags_t flags,
370 ///                    const ndrange_t ndrange,
371 ///                    void (^block)(local void*, ...),
372 ///                    uint size0, ...)
373 /// int enqueue_kernel(queue_t queue,
374 ///                    kernel_enqueue_flags_t flags,
375 ///                    const ndrange_t ndrange,
376 ///                    uint num_events_in_wait_list,
377 ///                    clk_event_t *event_wait_list,
378 ///                    clk_event_t *event_ret,
379 ///                    void (^block)(local void*, ...),
380 ///                    uint size0, ...)
381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382   unsigned NumArgs = TheCall->getNumArgs();
383 
384   if (NumArgs < 4) {
385     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
386     return true;
387   }
388 
389   Expr *Arg0 = TheCall->getArg(0);
390   Expr *Arg1 = TheCall->getArg(1);
391   Expr *Arg2 = TheCall->getArg(2);
392   Expr *Arg3 = TheCall->getArg(3);
393 
394   // First argument always needs to be a queue_t type.
395   if (!Arg0->getType()->isQueueT()) {
396     S.Diag(TheCall->getArg(0)->getLocStart(),
397            diag::err_opencl_enqueue_kernel_expected_type)
398         << S.Context.OCLQueueTy;
399     return true;
400   }
401 
402   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403   if (!Arg1->getType()->isIntegerType()) {
404     S.Diag(TheCall->getArg(1)->getLocStart(),
405            diag::err_opencl_enqueue_kernel_expected_type)
406         << "'kernel_enqueue_flags_t' (i.e. uint)";
407     return true;
408   }
409 
410   // Third argument is always an ndrange_t type.
411   if (!Arg2->getType()->isNDRangeT()) {
412     S.Diag(TheCall->getArg(2)->getLocStart(),
413            diag::err_opencl_enqueue_kernel_expected_type)
414         << S.Context.OCLNDRangeTy;
415     return true;
416   }
417 
418   // With four arguments, there is only one form that the function could be
419   // called in: no events and no variable arguments.
420   if (NumArgs == 4) {
421     // check that the last argument is the right block type.
422     if (!isBlockPointer(Arg3)) {
423       S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
424           << "block";
425       return true;
426     }
427     // we have a block type, check the prototype
428     const BlockPointerType *BPT =
429         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431       S.Diag(Arg3->getLocStart(),
432              diag::err_opencl_enqueue_kernel_blocks_no_args);
433       return true;
434     }
435     return false;
436   }
437   // we can have block + varargs.
438   if (isBlockPointer(Arg3))
439     return (checkOpenCLBlockArgs(S, Arg3) ||
440             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441   // last two cases with either exactly 7 args or 7 args and varargs.
442   if (NumArgs >= 7) {
443     // check common block argument.
444     Expr *Arg6 = TheCall->getArg(6);
445     if (!isBlockPointer(Arg6)) {
446       S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
447           << "block";
448       return true;
449     }
450     if (checkOpenCLBlockArgs(S, Arg6))
451       return true;
452 
453     // Forth argument has to be any integer type.
454     if (!Arg3->getType()->isIntegerType()) {
455       S.Diag(TheCall->getArg(3)->getLocStart(),
456              diag::err_opencl_enqueue_kernel_expected_type)
457           << "integer";
458       return true;
459     }
460     // check remaining common arguments.
461     Expr *Arg4 = TheCall->getArg(4);
462     Expr *Arg5 = TheCall->getArg(5);
463 
464     // Fifth argument is always passed as a pointer to clk_event_t.
465     if (!Arg4->isNullPointerConstant(S.Context,
466                                      Expr::NPC_ValueDependentIsNotNull) &&
467         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
468       S.Diag(TheCall->getArg(4)->getLocStart(),
469              diag::err_opencl_enqueue_kernel_expected_type)
470           << S.Context.getPointerType(S.Context.OCLClkEventTy);
471       return true;
472     }
473 
474     // Sixth argument is always passed as a pointer to clk_event_t.
475     if (!Arg5->isNullPointerConstant(S.Context,
476                                      Expr::NPC_ValueDependentIsNotNull) &&
477         !(Arg5->getType()->isPointerType() &&
478           Arg5->getType()->getPointeeType()->isClkEventT())) {
479       S.Diag(TheCall->getArg(5)->getLocStart(),
480              diag::err_opencl_enqueue_kernel_expected_type)
481           << S.Context.getPointerType(S.Context.OCLClkEventTy);
482       return true;
483     }
484 
485     if (NumArgs == 7)
486       return false;
487 
488     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
489   }
490 
491   // None of the specific case has been detected, give generic error
492   S.Diag(TheCall->getLocStart(),
493          diag::err_opencl_enqueue_kernel_incorrect_args);
494   return true;
495 }
496 
497 /// Returns OpenCL access qual.
498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
499     return D->getAttr<OpenCLAccessAttr>();
500 }
501 
502 /// Returns true if pipe element type is different from the pointer.
503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504   const Expr *Arg0 = Call->getArg(0);
505   // First argument type should always be pipe.
506   if (!Arg0->getType()->isPipeType()) {
507     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
508         << Call->getDirectCallee() << Arg0->getSourceRange();
509     return true;
510   }
511   OpenCLAccessAttr *AccessQual =
512       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513   // Validates the access qualifier is compatible with the call.
514   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515   // read_only and write_only, and assumed to be read_only if no qualifier is
516   // specified.
517   switch (Call->getDirectCallee()->getBuiltinID()) {
518   case Builtin::BIread_pipe:
519   case Builtin::BIreserve_read_pipe:
520   case Builtin::BIcommit_read_pipe:
521   case Builtin::BIwork_group_reserve_read_pipe:
522   case Builtin::BIsub_group_reserve_read_pipe:
523   case Builtin::BIwork_group_commit_read_pipe:
524   case Builtin::BIsub_group_commit_read_pipe:
525     if (!(!AccessQual || AccessQual->isReadOnly())) {
526       S.Diag(Arg0->getLocStart(),
527              diag::err_opencl_builtin_pipe_invalid_access_modifier)
528           << "read_only" << Arg0->getSourceRange();
529       return true;
530     }
531     break;
532   case Builtin::BIwrite_pipe:
533   case Builtin::BIreserve_write_pipe:
534   case Builtin::BIcommit_write_pipe:
535   case Builtin::BIwork_group_reserve_write_pipe:
536   case Builtin::BIsub_group_reserve_write_pipe:
537   case Builtin::BIwork_group_commit_write_pipe:
538   case Builtin::BIsub_group_commit_write_pipe:
539     if (!(AccessQual && AccessQual->isWriteOnly())) {
540       S.Diag(Arg0->getLocStart(),
541              diag::err_opencl_builtin_pipe_invalid_access_modifier)
542           << "write_only" << Arg0->getSourceRange();
543       return true;
544     }
545     break;
546   default:
547     break;
548   }
549   return false;
550 }
551 
552 /// Returns true if pipe element type is different from the pointer.
553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554   const Expr *Arg0 = Call->getArg(0);
555   const Expr *ArgIdx = Call->getArg(Idx);
556   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
557   const QualType EltTy = PipeTy->getElementType();
558   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
559   // The Idx argument should be a pointer and the type of the pointer and
560   // the type of pipe element should also be the same.
561   if (!ArgTy ||
562       !S.Context.hasSameType(
563           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
564     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
565         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
566         << ArgIdx->getType() << ArgIdx->getSourceRange();
567     return true;
568   }
569   return false;
570 }
571 
572 // \brief Performs semantic analysis for the read/write_pipe call.
573 // \param S Reference to the semantic analyzer.
574 // \param Call A pointer to the builtin call.
575 // \return True if a semantic error has been found, false otherwise.
576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
577   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578   // functions have two forms.
579   switch (Call->getNumArgs()) {
580   case 2: {
581     if (checkOpenCLPipeArg(S, Call))
582       return true;
583     // The call with 2 arguments should be
584     // read/write_pipe(pipe T, T*).
585     // Check packet type T.
586     if (checkOpenCLPipePacketType(S, Call, 1))
587       return true;
588   } break;
589 
590   case 4: {
591     if (checkOpenCLPipeArg(S, Call))
592       return true;
593     // The call with 4 arguments should be
594     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595     // Check reserve_id_t.
596     if (!Call->getArg(1)->getType()->isReserveIDT()) {
597       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
598           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
599           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
600       return true;
601     }
602 
603     // Check the index.
604     const Expr *Arg2 = Call->getArg(2);
605     if (!Arg2->getType()->isIntegerType() &&
606         !Arg2->getType()->isUnsignedIntegerType()) {
607       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
608           << Call->getDirectCallee() << S.Context.UnsignedIntTy
609           << Arg2->getType() << Arg2->getSourceRange();
610       return true;
611     }
612 
613     // Check packet type T.
614     if (checkOpenCLPipePacketType(S, Call, 3))
615       return true;
616   } break;
617   default:
618     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
619         << Call->getDirectCallee() << Call->getSourceRange();
620     return true;
621   }
622 
623   return false;
624 }
625 
626 // \brief Performs a semantic analysis on the {work_group_/sub_group_
627 //        /_}reserve_{read/write}_pipe
628 // \param S Reference to the semantic analyzer.
629 // \param Call The call to the builtin function to be analyzed.
630 // \return True if a semantic error was found, false otherwise.
631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632   if (checkArgCount(S, Call, 2))
633     return true;
634 
635   if (checkOpenCLPipeArg(S, Call))
636     return true;
637 
638   // Check the reserve size.
639   if (!Call->getArg(1)->getType()->isIntegerType() &&
640       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
642         << Call->getDirectCallee() << S.Context.UnsignedIntTy
643         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
644     return true;
645   }
646 
647   return false;
648 }
649 
650 // \brief Performs a semantic analysis on {work_group_/sub_group_
651 //        /_}commit_{read/write}_pipe
652 // \param S Reference to the semantic analyzer.
653 // \param Call The call to the builtin function to be analyzed.
654 // \return True if a semantic error was found, false otherwise.
655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656   if (checkArgCount(S, Call, 2))
657     return true;
658 
659   if (checkOpenCLPipeArg(S, Call))
660     return true;
661 
662   // Check reserve_id_t.
663   if (!Call->getArg(1)->getType()->isReserveIDT()) {
664     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
665         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
666         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
667     return true;
668   }
669 
670   return false;
671 }
672 
673 // \brief Performs a semantic analysis on the call to built-in Pipe
674 //        Query Functions.
675 // \param S Reference to the semantic analyzer.
676 // \param Call The call to the builtin function to be analyzed.
677 // \return True if a semantic error was found, false otherwise.
678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679   if (checkArgCount(S, Call, 1))
680     return true;
681 
682   if (!Call->getArg(0)->getType()->isPipeType()) {
683     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
684         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
685     return true;
686   }
687 
688   return false;
689 }
690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
691 // \brief Performs semantic analysis for the to_global/local/private call.
692 // \param S Reference to the semantic analyzer.
693 // \param BuiltinID ID of the builtin function.
694 // \param Call A pointer to the builtin call.
695 // \return True if a semantic error has been found, false otherwise.
696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
697                                     CallExpr *Call) {
698   if (Call->getNumArgs() != 1) {
699     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700         << Call->getDirectCallee() << Call->getSourceRange();
701     return true;
702   }
703 
704   auto RT = Call->getArg(0)->getType();
705   if (!RT->isPointerType() || RT->getPointeeType()
706       .getAddressSpace() == LangAS::opencl_constant) {
707     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
709     return true;
710   }
711 
712   RT = RT->getPointeeType();
713   auto Qual = RT.getQualifiers();
714   switch (BuiltinID) {
715   case Builtin::BIto_global:
716     Qual.setAddressSpace(LangAS::opencl_global);
717     break;
718   case Builtin::BIto_local:
719     Qual.setAddressSpace(LangAS::opencl_local);
720     break;
721   default:
722     Qual.removeAddressSpace();
723   }
724   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725       RT.getUnqualifiedType(), Qual)));
726 
727   return false;
728 }
729 
730 ExprResult
731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
732                                CallExpr *TheCall) {
733   ExprResult TheCallResult(TheCall);
734 
735   // Find out if any arguments are required to be integer constant expressions.
736   unsigned ICEArguments = 0;
737   ASTContext::GetBuiltinTypeError Error;
738   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739   if (Error != ASTContext::GE_None)
740     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
741 
742   // If any arguments are required to be ICE's, check and diagnose.
743   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744     // Skip arguments not required to be ICE's.
745     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
746 
747     llvm::APSInt Result;
748     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
749       return true;
750     ICEArguments &= ~(1 << ArgNo);
751   }
752 
753   switch (BuiltinID) {
754   case Builtin::BI__builtin___CFStringMakeConstantString:
755     assert(TheCall->getNumArgs() == 1 &&
756            "Wrong # arguments to builtin CFStringMakeConstantString");
757     if (CheckObjCString(TheCall->getArg(0)))
758       return ExprError();
759     break;
760   case Builtin::BI__builtin_stdarg_start:
761   case Builtin::BI__builtin_va_start:
762     if (SemaBuiltinVAStart(TheCall))
763       return ExprError();
764     break;
765   case Builtin::BI__va_start: {
766     switch (Context.getTargetInfo().getTriple().getArch()) {
767     case llvm::Triple::arm:
768     case llvm::Triple::thumb:
769       if (SemaBuiltinVAStartARM(TheCall))
770         return ExprError();
771       break;
772     default:
773       if (SemaBuiltinVAStart(TheCall))
774         return ExprError();
775       break;
776     }
777     break;
778   }
779   case Builtin::BI__builtin_isgreater:
780   case Builtin::BI__builtin_isgreaterequal:
781   case Builtin::BI__builtin_isless:
782   case Builtin::BI__builtin_islessequal:
783   case Builtin::BI__builtin_islessgreater:
784   case Builtin::BI__builtin_isunordered:
785     if (SemaBuiltinUnorderedCompare(TheCall))
786       return ExprError();
787     break;
788   case Builtin::BI__builtin_fpclassify:
789     if (SemaBuiltinFPClassification(TheCall, 6))
790       return ExprError();
791     break;
792   case Builtin::BI__builtin_isfinite:
793   case Builtin::BI__builtin_isinf:
794   case Builtin::BI__builtin_isinf_sign:
795   case Builtin::BI__builtin_isnan:
796   case Builtin::BI__builtin_isnormal:
797     if (SemaBuiltinFPClassification(TheCall, 1))
798       return ExprError();
799     break;
800   case Builtin::BI__builtin_shufflevector:
801     return SemaBuiltinShuffleVector(TheCall);
802     // TheCall will be freed by the smart pointer here, but that's fine, since
803     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
804   case Builtin::BI__builtin_prefetch:
805     if (SemaBuiltinPrefetch(TheCall))
806       return ExprError();
807     break;
808   case Builtin::BI__builtin_alloca_with_align:
809     if (SemaBuiltinAllocaWithAlign(TheCall))
810       return ExprError();
811     break;
812   case Builtin::BI__assume:
813   case Builtin::BI__builtin_assume:
814     if (SemaBuiltinAssume(TheCall))
815       return ExprError();
816     break;
817   case Builtin::BI__builtin_assume_aligned:
818     if (SemaBuiltinAssumeAligned(TheCall))
819       return ExprError();
820     break;
821   case Builtin::BI__builtin_object_size:
822     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
823       return ExprError();
824     break;
825   case Builtin::BI__builtin_longjmp:
826     if (SemaBuiltinLongjmp(TheCall))
827       return ExprError();
828     break;
829   case Builtin::BI__builtin_setjmp:
830     if (SemaBuiltinSetjmp(TheCall))
831       return ExprError();
832     break;
833   case Builtin::BI_setjmp:
834   case Builtin::BI_setjmpex:
835     if (checkArgCount(*this, TheCall, 1))
836       return true;
837     break;
838 
839   case Builtin::BI__builtin_classify_type:
840     if (checkArgCount(*this, TheCall, 1)) return true;
841     TheCall->setType(Context.IntTy);
842     break;
843   case Builtin::BI__builtin_constant_p:
844     if (checkArgCount(*this, TheCall, 1)) return true;
845     TheCall->setType(Context.IntTy);
846     break;
847   case Builtin::BI__sync_fetch_and_add:
848   case Builtin::BI__sync_fetch_and_add_1:
849   case Builtin::BI__sync_fetch_and_add_2:
850   case Builtin::BI__sync_fetch_and_add_4:
851   case Builtin::BI__sync_fetch_and_add_8:
852   case Builtin::BI__sync_fetch_and_add_16:
853   case Builtin::BI__sync_fetch_and_sub:
854   case Builtin::BI__sync_fetch_and_sub_1:
855   case Builtin::BI__sync_fetch_and_sub_2:
856   case Builtin::BI__sync_fetch_and_sub_4:
857   case Builtin::BI__sync_fetch_and_sub_8:
858   case Builtin::BI__sync_fetch_and_sub_16:
859   case Builtin::BI__sync_fetch_and_or:
860   case Builtin::BI__sync_fetch_and_or_1:
861   case Builtin::BI__sync_fetch_and_or_2:
862   case Builtin::BI__sync_fetch_and_or_4:
863   case Builtin::BI__sync_fetch_and_or_8:
864   case Builtin::BI__sync_fetch_and_or_16:
865   case Builtin::BI__sync_fetch_and_and:
866   case Builtin::BI__sync_fetch_and_and_1:
867   case Builtin::BI__sync_fetch_and_and_2:
868   case Builtin::BI__sync_fetch_and_and_4:
869   case Builtin::BI__sync_fetch_and_and_8:
870   case Builtin::BI__sync_fetch_and_and_16:
871   case Builtin::BI__sync_fetch_and_xor:
872   case Builtin::BI__sync_fetch_and_xor_1:
873   case Builtin::BI__sync_fetch_and_xor_2:
874   case Builtin::BI__sync_fetch_and_xor_4:
875   case Builtin::BI__sync_fetch_and_xor_8:
876   case Builtin::BI__sync_fetch_and_xor_16:
877   case Builtin::BI__sync_fetch_and_nand:
878   case Builtin::BI__sync_fetch_and_nand_1:
879   case Builtin::BI__sync_fetch_and_nand_2:
880   case Builtin::BI__sync_fetch_and_nand_4:
881   case Builtin::BI__sync_fetch_and_nand_8:
882   case Builtin::BI__sync_fetch_and_nand_16:
883   case Builtin::BI__sync_add_and_fetch:
884   case Builtin::BI__sync_add_and_fetch_1:
885   case Builtin::BI__sync_add_and_fetch_2:
886   case Builtin::BI__sync_add_and_fetch_4:
887   case Builtin::BI__sync_add_and_fetch_8:
888   case Builtin::BI__sync_add_and_fetch_16:
889   case Builtin::BI__sync_sub_and_fetch:
890   case Builtin::BI__sync_sub_and_fetch_1:
891   case Builtin::BI__sync_sub_and_fetch_2:
892   case Builtin::BI__sync_sub_and_fetch_4:
893   case Builtin::BI__sync_sub_and_fetch_8:
894   case Builtin::BI__sync_sub_and_fetch_16:
895   case Builtin::BI__sync_and_and_fetch:
896   case Builtin::BI__sync_and_and_fetch_1:
897   case Builtin::BI__sync_and_and_fetch_2:
898   case Builtin::BI__sync_and_and_fetch_4:
899   case Builtin::BI__sync_and_and_fetch_8:
900   case Builtin::BI__sync_and_and_fetch_16:
901   case Builtin::BI__sync_or_and_fetch:
902   case Builtin::BI__sync_or_and_fetch_1:
903   case Builtin::BI__sync_or_and_fetch_2:
904   case Builtin::BI__sync_or_and_fetch_4:
905   case Builtin::BI__sync_or_and_fetch_8:
906   case Builtin::BI__sync_or_and_fetch_16:
907   case Builtin::BI__sync_xor_and_fetch:
908   case Builtin::BI__sync_xor_and_fetch_1:
909   case Builtin::BI__sync_xor_and_fetch_2:
910   case Builtin::BI__sync_xor_and_fetch_4:
911   case Builtin::BI__sync_xor_and_fetch_8:
912   case Builtin::BI__sync_xor_and_fetch_16:
913   case Builtin::BI__sync_nand_and_fetch:
914   case Builtin::BI__sync_nand_and_fetch_1:
915   case Builtin::BI__sync_nand_and_fetch_2:
916   case Builtin::BI__sync_nand_and_fetch_4:
917   case Builtin::BI__sync_nand_and_fetch_8:
918   case Builtin::BI__sync_nand_and_fetch_16:
919   case Builtin::BI__sync_val_compare_and_swap:
920   case Builtin::BI__sync_val_compare_and_swap_1:
921   case Builtin::BI__sync_val_compare_and_swap_2:
922   case Builtin::BI__sync_val_compare_and_swap_4:
923   case Builtin::BI__sync_val_compare_and_swap_8:
924   case Builtin::BI__sync_val_compare_and_swap_16:
925   case Builtin::BI__sync_bool_compare_and_swap:
926   case Builtin::BI__sync_bool_compare_and_swap_1:
927   case Builtin::BI__sync_bool_compare_and_swap_2:
928   case Builtin::BI__sync_bool_compare_and_swap_4:
929   case Builtin::BI__sync_bool_compare_and_swap_8:
930   case Builtin::BI__sync_bool_compare_and_swap_16:
931   case Builtin::BI__sync_lock_test_and_set:
932   case Builtin::BI__sync_lock_test_and_set_1:
933   case Builtin::BI__sync_lock_test_and_set_2:
934   case Builtin::BI__sync_lock_test_and_set_4:
935   case Builtin::BI__sync_lock_test_and_set_8:
936   case Builtin::BI__sync_lock_test_and_set_16:
937   case Builtin::BI__sync_lock_release:
938   case Builtin::BI__sync_lock_release_1:
939   case Builtin::BI__sync_lock_release_2:
940   case Builtin::BI__sync_lock_release_4:
941   case Builtin::BI__sync_lock_release_8:
942   case Builtin::BI__sync_lock_release_16:
943   case Builtin::BI__sync_swap:
944   case Builtin::BI__sync_swap_1:
945   case Builtin::BI__sync_swap_2:
946   case Builtin::BI__sync_swap_4:
947   case Builtin::BI__sync_swap_8:
948   case Builtin::BI__sync_swap_16:
949     return SemaBuiltinAtomicOverloaded(TheCallResult);
950   case Builtin::BI__builtin_nontemporal_load:
951   case Builtin::BI__builtin_nontemporal_store:
952     return SemaBuiltinNontemporalOverloaded(TheCallResult);
953 #define BUILTIN(ID, TYPE, ATTRS)
954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955   case Builtin::BI##ID: \
956     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
957 #include "clang/Basic/Builtins.def"
958   case Builtin::BI__builtin_annotation:
959     if (SemaBuiltinAnnotation(*this, TheCall))
960       return ExprError();
961     break;
962   case Builtin::BI__builtin_addressof:
963     if (SemaBuiltinAddressof(*this, TheCall))
964       return ExprError();
965     break;
966   case Builtin::BI__builtin_add_overflow:
967   case Builtin::BI__builtin_sub_overflow:
968   case Builtin::BI__builtin_mul_overflow:
969     if (SemaBuiltinOverflow(*this, TheCall))
970       return ExprError();
971     break;
972   case Builtin::BI__builtin_operator_new:
973   case Builtin::BI__builtin_operator_delete:
974     if (!getLangOpts().CPlusPlus) {
975       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976         << (BuiltinID == Builtin::BI__builtin_operator_new
977                 ? "__builtin_operator_new"
978                 : "__builtin_operator_delete")
979         << "C++";
980       return ExprError();
981     }
982     // CodeGen assumes it can find the global new and delete to call,
983     // so ensure that they are declared.
984     DeclareGlobalNewDelete();
985     break;
986 
987   // check secure string manipulation functions where overflows
988   // are detectable at compile time
989   case Builtin::BI__builtin___memcpy_chk:
990   case Builtin::BI__builtin___memmove_chk:
991   case Builtin::BI__builtin___memset_chk:
992   case Builtin::BI__builtin___strlcat_chk:
993   case Builtin::BI__builtin___strlcpy_chk:
994   case Builtin::BI__builtin___strncat_chk:
995   case Builtin::BI__builtin___strncpy_chk:
996   case Builtin::BI__builtin___stpncpy_chk:
997     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
998     break;
999   case Builtin::BI__builtin___memccpy_chk:
1000     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1001     break;
1002   case Builtin::BI__builtin___snprintf_chk:
1003   case Builtin::BI__builtin___vsnprintf_chk:
1004     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1005     break;
1006   case Builtin::BI__builtin_call_with_static_chain:
1007     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1008       return ExprError();
1009     break;
1010   case Builtin::BI__exception_code:
1011   case Builtin::BI_exception_code:
1012     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013                                  diag::err_seh___except_block))
1014       return ExprError();
1015     break;
1016   case Builtin::BI__exception_info:
1017   case Builtin::BI_exception_info:
1018     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019                                  diag::err_seh___except_filter))
1020       return ExprError();
1021     break;
1022   case Builtin::BI__GetExceptionInfo:
1023     if (checkArgCount(*this, TheCall, 1))
1024       return ExprError();
1025 
1026     if (CheckCXXThrowOperand(
1027             TheCall->getLocStart(),
1028             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1029             TheCall))
1030       return ExprError();
1031 
1032     TheCall->setType(Context.VoidPtrTy);
1033     break;
1034   // OpenCL v2.0, s6.13.16 - Pipe functions
1035   case Builtin::BIread_pipe:
1036   case Builtin::BIwrite_pipe:
1037     // Since those two functions are declared with var args, we need a semantic
1038     // check for the argument.
1039     if (SemaBuiltinRWPipe(*this, TheCall))
1040       return ExprError();
1041     TheCall->setType(Context.IntTy);
1042     break;
1043   case Builtin::BIreserve_read_pipe:
1044   case Builtin::BIreserve_write_pipe:
1045   case Builtin::BIwork_group_reserve_read_pipe:
1046   case Builtin::BIwork_group_reserve_write_pipe:
1047   case Builtin::BIsub_group_reserve_read_pipe:
1048   case Builtin::BIsub_group_reserve_write_pipe:
1049     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1050       return ExprError();
1051     // Since return type of reserve_read/write_pipe built-in function is
1052     // reserve_id_t, which is not defined in the builtin def file , we used int
1053     // as return type and need to override the return type of these functions.
1054     TheCall->setType(Context.OCLReserveIDTy);
1055     break;
1056   case Builtin::BIcommit_read_pipe:
1057   case Builtin::BIcommit_write_pipe:
1058   case Builtin::BIwork_group_commit_read_pipe:
1059   case Builtin::BIwork_group_commit_write_pipe:
1060   case Builtin::BIsub_group_commit_read_pipe:
1061   case Builtin::BIsub_group_commit_write_pipe:
1062     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1063       return ExprError();
1064     break;
1065   case Builtin::BIget_pipe_num_packets:
1066   case Builtin::BIget_pipe_max_packets:
1067     if (SemaBuiltinPipePackets(*this, TheCall))
1068       return ExprError();
1069     TheCall->setType(Context.UnsignedIntTy);
1070     break;
1071   case Builtin::BIto_global:
1072   case Builtin::BIto_local:
1073   case Builtin::BIto_private:
1074     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1075       return ExprError();
1076     break;
1077   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078   case Builtin::BIenqueue_kernel:
1079     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1080       return ExprError();
1081     break;
1082   case Builtin::BIget_kernel_work_group_size:
1083   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1085       return ExprError();
1086     break;
1087   case Builtin::BI__builtin_os_log_format:
1088   case Builtin::BI__builtin_os_log_format_buffer_size:
1089     if (SemaBuiltinOSLogFormat(TheCall)) {
1090       return ExprError();
1091     }
1092     break;
1093   }
1094 
1095   // Since the target specific builtins for each arch overlap, only check those
1096   // of the arch we are compiling for.
1097   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1098     switch (Context.getTargetInfo().getTriple().getArch()) {
1099       case llvm::Triple::arm:
1100       case llvm::Triple::armeb:
1101       case llvm::Triple::thumb:
1102       case llvm::Triple::thumbeb:
1103         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1104           return ExprError();
1105         break;
1106       case llvm::Triple::aarch64:
1107       case llvm::Triple::aarch64_be:
1108         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1109           return ExprError();
1110         break;
1111       case llvm::Triple::mips:
1112       case llvm::Triple::mipsel:
1113       case llvm::Triple::mips64:
1114       case llvm::Triple::mips64el:
1115         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1116           return ExprError();
1117         break;
1118       case llvm::Triple::systemz:
1119         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1120           return ExprError();
1121         break;
1122       case llvm::Triple::x86:
1123       case llvm::Triple::x86_64:
1124         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1125           return ExprError();
1126         break;
1127       case llvm::Triple::ppc:
1128       case llvm::Triple::ppc64:
1129       case llvm::Triple::ppc64le:
1130         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1131           return ExprError();
1132         break;
1133       default:
1134         break;
1135     }
1136   }
1137 
1138   return TheCallResult;
1139 }
1140 
1141 // Get the valid immediate range for the specified NEON type code.
1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1143   NeonTypeFlags Type(t);
1144   int IsQuad = ForceQuad ? true : Type.isQuad();
1145   switch (Type.getEltType()) {
1146   case NeonTypeFlags::Int8:
1147   case NeonTypeFlags::Poly8:
1148     return shift ? 7 : (8 << IsQuad) - 1;
1149   case NeonTypeFlags::Int16:
1150   case NeonTypeFlags::Poly16:
1151     return shift ? 15 : (4 << IsQuad) - 1;
1152   case NeonTypeFlags::Int32:
1153     return shift ? 31 : (2 << IsQuad) - 1;
1154   case NeonTypeFlags::Int64:
1155   case NeonTypeFlags::Poly64:
1156     return shift ? 63 : (1 << IsQuad) - 1;
1157   case NeonTypeFlags::Poly128:
1158     return shift ? 127 : (1 << IsQuad) - 1;
1159   case NeonTypeFlags::Float16:
1160     assert(!shift && "cannot shift float types!");
1161     return (4 << IsQuad) - 1;
1162   case NeonTypeFlags::Float32:
1163     assert(!shift && "cannot shift float types!");
1164     return (2 << IsQuad) - 1;
1165   case NeonTypeFlags::Float64:
1166     assert(!shift && "cannot shift float types!");
1167     return (1 << IsQuad) - 1;
1168   }
1169   llvm_unreachable("Invalid NeonTypeFlag!");
1170 }
1171 
1172 /// getNeonEltType - Return the QualType corresponding to the elements of
1173 /// the vector type specified by the NeonTypeFlags.  This is used to check
1174 /// the pointer arguments for Neon load/store intrinsics.
1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1176                                bool IsPolyUnsigned, bool IsInt64Long) {
1177   switch (Flags.getEltType()) {
1178   case NeonTypeFlags::Int8:
1179     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180   case NeonTypeFlags::Int16:
1181     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182   case NeonTypeFlags::Int32:
1183     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184   case NeonTypeFlags::Int64:
1185     if (IsInt64Long)
1186       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1187     else
1188       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189                                 : Context.LongLongTy;
1190   case NeonTypeFlags::Poly8:
1191     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1192   case NeonTypeFlags::Poly16:
1193     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1194   case NeonTypeFlags::Poly64:
1195     if (IsInt64Long)
1196       return Context.UnsignedLongTy;
1197     else
1198       return Context.UnsignedLongLongTy;
1199   case NeonTypeFlags::Poly128:
1200     break;
1201   case NeonTypeFlags::Float16:
1202     return Context.HalfTy;
1203   case NeonTypeFlags::Float32:
1204     return Context.FloatTy;
1205   case NeonTypeFlags::Float64:
1206     return Context.DoubleTy;
1207   }
1208   llvm_unreachable("Invalid NeonTypeFlag!");
1209 }
1210 
1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1212   llvm::APSInt Result;
1213   uint64_t mask = 0;
1214   unsigned TV = 0;
1215   int PtrArgNum = -1;
1216   bool HasConstPtr = false;
1217   switch (BuiltinID) {
1218 #define GET_NEON_OVERLOAD_CHECK
1219 #include "clang/Basic/arm_neon.inc"
1220 #undef GET_NEON_OVERLOAD_CHECK
1221   }
1222 
1223   // For NEON intrinsics which are overloaded on vector element type, validate
1224   // the immediate which specifies which variant to emit.
1225   unsigned ImmArg = TheCall->getNumArgs()-1;
1226   if (mask) {
1227     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1228       return true;
1229 
1230     TV = Result.getLimitedValue(64);
1231     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1233         << TheCall->getArg(ImmArg)->getSourceRange();
1234   }
1235 
1236   if (PtrArgNum >= 0) {
1237     // Check that pointer arguments have the specified type.
1238     Expr *Arg = TheCall->getArg(PtrArgNum);
1239     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240       Arg = ICE->getSubExpr();
1241     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242     QualType RHSTy = RHS.get()->getType();
1243 
1244     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1245     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1246     bool IsInt64Long =
1247         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1248     QualType EltTy =
1249         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1250     if (HasConstPtr)
1251       EltTy = EltTy.withConst();
1252     QualType LHSTy = Context.getPointerType(EltTy);
1253     AssignConvertType ConvTy;
1254     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1255     if (RHS.isInvalid())
1256       return true;
1257     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1258                                  RHS.get(), AA_Assigning))
1259       return true;
1260   }
1261 
1262   // For NEON intrinsics which take an immediate value as part of the
1263   // instruction, range check them here.
1264   unsigned i = 0, l = 0, u = 0;
1265   switch (BuiltinID) {
1266   default:
1267     return false;
1268 #define GET_NEON_IMMEDIATE_CHECK
1269 #include "clang/Basic/arm_neon.inc"
1270 #undef GET_NEON_IMMEDIATE_CHECK
1271   }
1272 
1273   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1274 }
1275 
1276 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1277                                         unsigned MaxWidth) {
1278   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1279           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1280           BuiltinID == ARM::BI__builtin_arm_strex ||
1281           BuiltinID == ARM::BI__builtin_arm_stlex ||
1282           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1283           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1284           BuiltinID == AArch64::BI__builtin_arm_strex ||
1285           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1286          "unexpected ARM builtin");
1287   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1288                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1289                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1290                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1291 
1292   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1293 
1294   // Ensure that we have the proper number of arguments.
1295   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1296     return true;
1297 
1298   // Inspect the pointer argument of the atomic builtin.  This should always be
1299   // a pointer type, whose element is an integral scalar or pointer type.
1300   // Because it is a pointer type, we don't have to worry about any implicit
1301   // casts here.
1302   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1303   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1304   if (PointerArgRes.isInvalid())
1305     return true;
1306   PointerArg = PointerArgRes.get();
1307 
1308   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1309   if (!pointerType) {
1310     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1311       << PointerArg->getType() << PointerArg->getSourceRange();
1312     return true;
1313   }
1314 
1315   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1316   // task is to insert the appropriate casts into the AST. First work out just
1317   // what the appropriate type is.
1318   QualType ValType = pointerType->getPointeeType();
1319   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1320   if (IsLdrex)
1321     AddrType.addConst();
1322 
1323   // Issue a warning if the cast is dodgy.
1324   CastKind CastNeeded = CK_NoOp;
1325   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1326     CastNeeded = CK_BitCast;
1327     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1328       << PointerArg->getType()
1329       << Context.getPointerType(AddrType)
1330       << AA_Passing << PointerArg->getSourceRange();
1331   }
1332 
1333   // Finally, do the cast and replace the argument with the corrected version.
1334   AddrType = Context.getPointerType(AddrType);
1335   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1336   if (PointerArgRes.isInvalid())
1337     return true;
1338   PointerArg = PointerArgRes.get();
1339 
1340   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1341 
1342   // In general, we allow ints, floats and pointers to be loaded and stored.
1343   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1344       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1345     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1346       << PointerArg->getType() << PointerArg->getSourceRange();
1347     return true;
1348   }
1349 
1350   // But ARM doesn't have instructions to deal with 128-bit versions.
1351   if (Context.getTypeSize(ValType) > MaxWidth) {
1352     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1353     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1354       << PointerArg->getType() << PointerArg->getSourceRange();
1355     return true;
1356   }
1357 
1358   switch (ValType.getObjCLifetime()) {
1359   case Qualifiers::OCL_None:
1360   case Qualifiers::OCL_ExplicitNone:
1361     // okay
1362     break;
1363 
1364   case Qualifiers::OCL_Weak:
1365   case Qualifiers::OCL_Strong:
1366   case Qualifiers::OCL_Autoreleasing:
1367     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1368       << ValType << PointerArg->getSourceRange();
1369     return true;
1370   }
1371 
1372   if (IsLdrex) {
1373     TheCall->setType(ValType);
1374     return false;
1375   }
1376 
1377   // Initialize the argument to be stored.
1378   ExprResult ValArg = TheCall->getArg(0);
1379   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1380       Context, ValType, /*consume*/ false);
1381   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1382   if (ValArg.isInvalid())
1383     return true;
1384   TheCall->setArg(0, ValArg.get());
1385 
1386   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1387   // but the custom checker bypasses all default analysis.
1388   TheCall->setType(Context.IntTy);
1389   return false;
1390 }
1391 
1392 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1393   llvm::APSInt Result;
1394 
1395   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1396       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1397       BuiltinID == ARM::BI__builtin_arm_strex ||
1398       BuiltinID == ARM::BI__builtin_arm_stlex) {
1399     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1400   }
1401 
1402   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1403     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1404       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1405   }
1406 
1407   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1408       BuiltinID == ARM::BI__builtin_arm_wsr64)
1409     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1410 
1411   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1412       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1413       BuiltinID == ARM::BI__builtin_arm_wsr ||
1414       BuiltinID == ARM::BI__builtin_arm_wsrp)
1415     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1416 
1417   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1418     return true;
1419 
1420   // For intrinsics which take an immediate value as part of the instruction,
1421   // range check them here.
1422   unsigned i = 0, l = 0, u = 0;
1423   switch (BuiltinID) {
1424   default: return false;
1425   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1426   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1427   case ARM::BI__builtin_arm_vcvtr_f:
1428   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1429   case ARM::BI__builtin_arm_dmb:
1430   case ARM::BI__builtin_arm_dsb:
1431   case ARM::BI__builtin_arm_isb:
1432   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1433   }
1434 
1435   // FIXME: VFP Intrinsics should error if VFP not present.
1436   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1437 }
1438 
1439 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1440                                          CallExpr *TheCall) {
1441   llvm::APSInt Result;
1442 
1443   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1444       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445       BuiltinID == AArch64::BI__builtin_arm_strex ||
1446       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1447     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448   }
1449 
1450   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455   }
1456 
1457   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1459     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1460 
1461   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466 
1467   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468     return true;
1469 
1470   // For intrinsics which take an immediate value as part of the instruction,
1471   // range check them here.
1472   unsigned i = 0, l = 0, u = 0;
1473   switch (BuiltinID) {
1474   default: return false;
1475   case AArch64::BI__builtin_arm_dmb:
1476   case AArch64::BI__builtin_arm_dsb:
1477   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478   }
1479 
1480   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1481 }
1482 
1483 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485 // ordering for DSP is unspecified. MSA is ordered by the data format used
1486 // by the underlying instruction i.e., df/m, df/n and then by size.
1487 //
1488 // FIXME: The size tests here should instead be tablegen'd along with the
1489 //        definitions from include/clang/Basic/BuiltinsMips.def.
1490 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491 //        be too.
1492 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1493   unsigned i = 0, l = 0, u = 0, m = 0;
1494   switch (BuiltinID) {
1495   default: return false;
1496   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1498   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1503   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504   // df/m field.
1505   // These intrinsics take an unsigned 3 bit immediate.
1506   case Mips::BI__builtin_msa_bclri_b:
1507   case Mips::BI__builtin_msa_bnegi_b:
1508   case Mips::BI__builtin_msa_bseti_b:
1509   case Mips::BI__builtin_msa_sat_s_b:
1510   case Mips::BI__builtin_msa_sat_u_b:
1511   case Mips::BI__builtin_msa_slli_b:
1512   case Mips::BI__builtin_msa_srai_b:
1513   case Mips::BI__builtin_msa_srari_b:
1514   case Mips::BI__builtin_msa_srli_b:
1515   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516   case Mips::BI__builtin_msa_binsli_b:
1517   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518   // These intrinsics take an unsigned 4 bit immediate.
1519   case Mips::BI__builtin_msa_bclri_h:
1520   case Mips::BI__builtin_msa_bnegi_h:
1521   case Mips::BI__builtin_msa_bseti_h:
1522   case Mips::BI__builtin_msa_sat_s_h:
1523   case Mips::BI__builtin_msa_sat_u_h:
1524   case Mips::BI__builtin_msa_slli_h:
1525   case Mips::BI__builtin_msa_srai_h:
1526   case Mips::BI__builtin_msa_srari_h:
1527   case Mips::BI__builtin_msa_srli_h:
1528   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529   case Mips::BI__builtin_msa_binsli_h:
1530   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531   // These intrinsics take an unsigned 5 bit immedate.
1532   // The first block of intrinsics actually have an unsigned 5 bit field,
1533   // not a df/n field.
1534   case Mips::BI__builtin_msa_clei_u_b:
1535   case Mips::BI__builtin_msa_clei_u_h:
1536   case Mips::BI__builtin_msa_clei_u_w:
1537   case Mips::BI__builtin_msa_clei_u_d:
1538   case Mips::BI__builtin_msa_clti_u_b:
1539   case Mips::BI__builtin_msa_clti_u_h:
1540   case Mips::BI__builtin_msa_clti_u_w:
1541   case Mips::BI__builtin_msa_clti_u_d:
1542   case Mips::BI__builtin_msa_maxi_u_b:
1543   case Mips::BI__builtin_msa_maxi_u_h:
1544   case Mips::BI__builtin_msa_maxi_u_w:
1545   case Mips::BI__builtin_msa_maxi_u_d:
1546   case Mips::BI__builtin_msa_mini_u_b:
1547   case Mips::BI__builtin_msa_mini_u_h:
1548   case Mips::BI__builtin_msa_mini_u_w:
1549   case Mips::BI__builtin_msa_mini_u_d:
1550   case Mips::BI__builtin_msa_addvi_b:
1551   case Mips::BI__builtin_msa_addvi_h:
1552   case Mips::BI__builtin_msa_addvi_w:
1553   case Mips::BI__builtin_msa_addvi_d:
1554   case Mips::BI__builtin_msa_bclri_w:
1555   case Mips::BI__builtin_msa_bnegi_w:
1556   case Mips::BI__builtin_msa_bseti_w:
1557   case Mips::BI__builtin_msa_sat_s_w:
1558   case Mips::BI__builtin_msa_sat_u_w:
1559   case Mips::BI__builtin_msa_slli_w:
1560   case Mips::BI__builtin_msa_srai_w:
1561   case Mips::BI__builtin_msa_srari_w:
1562   case Mips::BI__builtin_msa_srli_w:
1563   case Mips::BI__builtin_msa_srlri_w:
1564   case Mips::BI__builtin_msa_subvi_b:
1565   case Mips::BI__builtin_msa_subvi_h:
1566   case Mips::BI__builtin_msa_subvi_w:
1567   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568   case Mips::BI__builtin_msa_binsli_w:
1569   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570   // These intrinsics take an unsigned 6 bit immediate.
1571   case Mips::BI__builtin_msa_bclri_d:
1572   case Mips::BI__builtin_msa_bnegi_d:
1573   case Mips::BI__builtin_msa_bseti_d:
1574   case Mips::BI__builtin_msa_sat_s_d:
1575   case Mips::BI__builtin_msa_sat_u_d:
1576   case Mips::BI__builtin_msa_slli_d:
1577   case Mips::BI__builtin_msa_srai_d:
1578   case Mips::BI__builtin_msa_srari_d:
1579   case Mips::BI__builtin_msa_srli_d:
1580   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581   case Mips::BI__builtin_msa_binsli_d:
1582   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583   // These intrinsics take a signed 5 bit immediate.
1584   case Mips::BI__builtin_msa_ceqi_b:
1585   case Mips::BI__builtin_msa_ceqi_h:
1586   case Mips::BI__builtin_msa_ceqi_w:
1587   case Mips::BI__builtin_msa_ceqi_d:
1588   case Mips::BI__builtin_msa_clti_s_b:
1589   case Mips::BI__builtin_msa_clti_s_h:
1590   case Mips::BI__builtin_msa_clti_s_w:
1591   case Mips::BI__builtin_msa_clti_s_d:
1592   case Mips::BI__builtin_msa_clei_s_b:
1593   case Mips::BI__builtin_msa_clei_s_h:
1594   case Mips::BI__builtin_msa_clei_s_w:
1595   case Mips::BI__builtin_msa_clei_s_d:
1596   case Mips::BI__builtin_msa_maxi_s_b:
1597   case Mips::BI__builtin_msa_maxi_s_h:
1598   case Mips::BI__builtin_msa_maxi_s_w:
1599   case Mips::BI__builtin_msa_maxi_s_d:
1600   case Mips::BI__builtin_msa_mini_s_b:
1601   case Mips::BI__builtin_msa_mini_s_h:
1602   case Mips::BI__builtin_msa_mini_s_w:
1603   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604   // These intrinsics take an unsigned 8 bit immediate.
1605   case Mips::BI__builtin_msa_andi_b:
1606   case Mips::BI__builtin_msa_nori_b:
1607   case Mips::BI__builtin_msa_ori_b:
1608   case Mips::BI__builtin_msa_shf_b:
1609   case Mips::BI__builtin_msa_shf_h:
1610   case Mips::BI__builtin_msa_shf_w:
1611   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612   case Mips::BI__builtin_msa_bseli_b:
1613   case Mips::BI__builtin_msa_bmnzi_b:
1614   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615   // df/n format
1616   // These intrinsics take an unsigned 4 bit immediate.
1617   case Mips::BI__builtin_msa_copy_s_b:
1618   case Mips::BI__builtin_msa_copy_u_b:
1619   case Mips::BI__builtin_msa_insve_b:
1620   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1621   case Mips::BI__builtin_msa_sld_b:
1622   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623   // These intrinsics take an unsigned 3 bit immediate.
1624   case Mips::BI__builtin_msa_copy_s_h:
1625   case Mips::BI__builtin_msa_copy_u_h:
1626   case Mips::BI__builtin_msa_insve_h:
1627   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1628   case Mips::BI__builtin_msa_sld_h:
1629   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1630   // These intrinsics take an unsigned 2 bit immediate.
1631   case Mips::BI__builtin_msa_copy_s_w:
1632   case Mips::BI__builtin_msa_copy_u_w:
1633   case Mips::BI__builtin_msa_insve_w:
1634   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1635   case Mips::BI__builtin_msa_sld_w:
1636   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1637   // These intrinsics take an unsigned 1 bit immediate.
1638   case Mips::BI__builtin_msa_copy_s_d:
1639   case Mips::BI__builtin_msa_copy_u_d:
1640   case Mips::BI__builtin_msa_insve_d:
1641   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1642   case Mips::BI__builtin_msa_sld_d:
1643   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1644   // Memory offsets and immediate loads.
1645   // These intrinsics take a signed 10 bit immediate.
1646   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1647   case Mips::BI__builtin_msa_ldi_h:
1648   case Mips::BI__builtin_msa_ldi_w:
1649   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1650   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1651   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1652   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1653   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1654   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1655   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1656   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1657   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1658   }
1659 
1660   if (!m)
1661     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1662 
1663   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1664          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1665 }
1666 
1667 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1668   unsigned i = 0, l = 0, u = 0;
1669   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1670                       BuiltinID == PPC::BI__builtin_divdeu ||
1671                       BuiltinID == PPC::BI__builtin_bpermd;
1672   bool IsTarget64Bit = Context.getTargetInfo()
1673                               .getTypeWidth(Context
1674                                             .getTargetInfo()
1675                                             .getIntPtrType()) == 64;
1676   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1677                        BuiltinID == PPC::BI__builtin_divweu ||
1678                        BuiltinID == PPC::BI__builtin_divde ||
1679                        BuiltinID == PPC::BI__builtin_divdeu;
1680 
1681   if (Is64BitBltin && !IsTarget64Bit)
1682       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1683              << TheCall->getSourceRange();
1684 
1685   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1686       (BuiltinID == PPC::BI__builtin_bpermd &&
1687        !Context.getTargetInfo().hasFeature("bpermd")))
1688     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1689            << TheCall->getSourceRange();
1690 
1691   switch (BuiltinID) {
1692   default: return false;
1693   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1694   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1695     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1696            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1697   case PPC::BI__builtin_tbegin:
1698   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1699   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1700   case PPC::BI__builtin_tabortwc:
1701   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1702   case PPC::BI__builtin_tabortwci:
1703   case PPC::BI__builtin_tabortdci:
1704     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1705            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1706   }
1707   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1708 }
1709 
1710 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711                                            CallExpr *TheCall) {
1712   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713     Expr *Arg = TheCall->getArg(0);
1714     llvm::APSInt AbortCode(32);
1715     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718              << Arg->getSourceRange();
1719   }
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 SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727   case SystemZ::BI__builtin_s390_verimb:
1728   case SystemZ::BI__builtin_s390_verimh:
1729   case SystemZ::BI__builtin_s390_verimf:
1730   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731   case SystemZ::BI__builtin_s390_vfaeb:
1732   case SystemZ::BI__builtin_s390_vfaeh:
1733   case SystemZ::BI__builtin_s390_vfaef:
1734   case SystemZ::BI__builtin_s390_vfaebs:
1735   case SystemZ::BI__builtin_s390_vfaehs:
1736   case SystemZ::BI__builtin_s390_vfaefs:
1737   case SystemZ::BI__builtin_s390_vfaezb:
1738   case SystemZ::BI__builtin_s390_vfaezh:
1739   case SystemZ::BI__builtin_s390_vfaezf:
1740   case SystemZ::BI__builtin_s390_vfaezbs:
1741   case SystemZ::BI__builtin_s390_vfaezhs:
1742   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1743   case SystemZ::BI__builtin_s390_vfidb:
1744     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1745            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1746   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1747   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1748   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1749   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1750   case SystemZ::BI__builtin_s390_vstrcb:
1751   case SystemZ::BI__builtin_s390_vstrch:
1752   case SystemZ::BI__builtin_s390_vstrcf:
1753   case SystemZ::BI__builtin_s390_vstrczb:
1754   case SystemZ::BI__builtin_s390_vstrczh:
1755   case SystemZ::BI__builtin_s390_vstrczf:
1756   case SystemZ::BI__builtin_s390_vstrcbs:
1757   case SystemZ::BI__builtin_s390_vstrchs:
1758   case SystemZ::BI__builtin_s390_vstrcfs:
1759   case SystemZ::BI__builtin_s390_vstrczbs:
1760   case SystemZ::BI__builtin_s390_vstrczhs:
1761   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1762   }
1763   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1764 }
1765 
1766 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1767 /// This checks that the target supports __builtin_cpu_supports and
1768 /// that the string argument is constant and valid.
1769 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1770   Expr *Arg = TheCall->getArg(0);
1771 
1772   // Check if the argument is a string literal.
1773   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1774     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1775            << Arg->getSourceRange();
1776 
1777   // Check the contents of the string.
1778   StringRef Feature =
1779       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1780   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1781     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1782            << Arg->getSourceRange();
1783   return false;
1784 }
1785 
1786 // Check if the rounding mode is legal.
1787 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1788   // Indicates if this instruction has rounding control or just SAE.
1789   bool HasRC = false;
1790 
1791   unsigned ArgNum = 0;
1792   switch (BuiltinID) {
1793   default:
1794     return false;
1795   case X86::BI__builtin_ia32_vcvttsd2si32:
1796   case X86::BI__builtin_ia32_vcvttsd2si64:
1797   case X86::BI__builtin_ia32_vcvttsd2usi32:
1798   case X86::BI__builtin_ia32_vcvttsd2usi64:
1799   case X86::BI__builtin_ia32_vcvttss2si32:
1800   case X86::BI__builtin_ia32_vcvttss2si64:
1801   case X86::BI__builtin_ia32_vcvttss2usi32:
1802   case X86::BI__builtin_ia32_vcvttss2usi64:
1803     ArgNum = 1;
1804     break;
1805   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1806   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1807   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1808   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1809   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1810   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1811   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1812   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1813   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1814   case X86::BI__builtin_ia32_exp2pd_mask:
1815   case X86::BI__builtin_ia32_exp2ps_mask:
1816   case X86::BI__builtin_ia32_getexppd512_mask:
1817   case X86::BI__builtin_ia32_getexpps512_mask:
1818   case X86::BI__builtin_ia32_rcp28pd_mask:
1819   case X86::BI__builtin_ia32_rcp28ps_mask:
1820   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1821   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1822   case X86::BI__builtin_ia32_vcomisd:
1823   case X86::BI__builtin_ia32_vcomiss:
1824   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1825     ArgNum = 3;
1826     break;
1827   case X86::BI__builtin_ia32_cmppd512_mask:
1828   case X86::BI__builtin_ia32_cmpps512_mask:
1829   case X86::BI__builtin_ia32_cmpsd_mask:
1830   case X86::BI__builtin_ia32_cmpss_mask:
1831   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1832   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1833   case X86::BI__builtin_ia32_getexpss128_round_mask:
1834   case X86::BI__builtin_ia32_maxpd512_mask:
1835   case X86::BI__builtin_ia32_maxps512_mask:
1836   case X86::BI__builtin_ia32_maxsd_round_mask:
1837   case X86::BI__builtin_ia32_maxss_round_mask:
1838   case X86::BI__builtin_ia32_minpd512_mask:
1839   case X86::BI__builtin_ia32_minps512_mask:
1840   case X86::BI__builtin_ia32_minsd_round_mask:
1841   case X86::BI__builtin_ia32_minss_round_mask:
1842   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1843   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1844   case X86::BI__builtin_ia32_reducepd512_mask:
1845   case X86::BI__builtin_ia32_reduceps512_mask:
1846   case X86::BI__builtin_ia32_rndscalepd_mask:
1847   case X86::BI__builtin_ia32_rndscaleps_mask:
1848   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1849   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1850     ArgNum = 4;
1851     break;
1852   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1853   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1854   case X86::BI__builtin_ia32_fixupimmps512_mask:
1855   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1856   case X86::BI__builtin_ia32_fixupimmsd_mask:
1857   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1858   case X86::BI__builtin_ia32_fixupimmss_mask:
1859   case X86::BI__builtin_ia32_fixupimmss_maskz:
1860   case X86::BI__builtin_ia32_rangepd512_mask:
1861   case X86::BI__builtin_ia32_rangeps512_mask:
1862   case X86::BI__builtin_ia32_rangesd128_round_mask:
1863   case X86::BI__builtin_ia32_rangess128_round_mask:
1864   case X86::BI__builtin_ia32_reducesd_mask:
1865   case X86::BI__builtin_ia32_reducess_mask:
1866   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1867   case X86::BI__builtin_ia32_rndscaless_round_mask:
1868     ArgNum = 5;
1869     break;
1870   case X86::BI__builtin_ia32_vcvtsd2si64:
1871   case X86::BI__builtin_ia32_vcvtsd2si32:
1872   case X86::BI__builtin_ia32_vcvtsd2usi32:
1873   case X86::BI__builtin_ia32_vcvtsd2usi64:
1874   case X86::BI__builtin_ia32_vcvtss2si32:
1875   case X86::BI__builtin_ia32_vcvtss2si64:
1876   case X86::BI__builtin_ia32_vcvtss2usi32:
1877   case X86::BI__builtin_ia32_vcvtss2usi64:
1878     ArgNum = 1;
1879     HasRC = true;
1880     break;
1881   case X86::BI__builtin_ia32_cvtsi2sd64:
1882   case X86::BI__builtin_ia32_cvtsi2ss32:
1883   case X86::BI__builtin_ia32_cvtsi2ss64:
1884   case X86::BI__builtin_ia32_cvtusi2sd64:
1885   case X86::BI__builtin_ia32_cvtusi2ss32:
1886   case X86::BI__builtin_ia32_cvtusi2ss64:
1887     ArgNum = 2;
1888     HasRC = true;
1889     break;
1890   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1891   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1892   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1893   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1894   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1895   case X86::BI__builtin_ia32_cvtps2qq512_mask:
1896   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1897   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1898   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1899   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1900   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1901   case X86::BI__builtin_ia32_sqrtpd512_mask:
1902   case X86::BI__builtin_ia32_sqrtps512_mask:
1903     ArgNum = 3;
1904     HasRC = true;
1905     break;
1906   case X86::BI__builtin_ia32_addpd512_mask:
1907   case X86::BI__builtin_ia32_addps512_mask:
1908   case X86::BI__builtin_ia32_divpd512_mask:
1909   case X86::BI__builtin_ia32_divps512_mask:
1910   case X86::BI__builtin_ia32_mulpd512_mask:
1911   case X86::BI__builtin_ia32_mulps512_mask:
1912   case X86::BI__builtin_ia32_subpd512_mask:
1913   case X86::BI__builtin_ia32_subps512_mask:
1914   case X86::BI__builtin_ia32_addss_round_mask:
1915   case X86::BI__builtin_ia32_addsd_round_mask:
1916   case X86::BI__builtin_ia32_divss_round_mask:
1917   case X86::BI__builtin_ia32_divsd_round_mask:
1918   case X86::BI__builtin_ia32_mulss_round_mask:
1919   case X86::BI__builtin_ia32_mulsd_round_mask:
1920   case X86::BI__builtin_ia32_subss_round_mask:
1921   case X86::BI__builtin_ia32_subsd_round_mask:
1922   case X86::BI__builtin_ia32_scalefpd512_mask:
1923   case X86::BI__builtin_ia32_scalefps512_mask:
1924   case X86::BI__builtin_ia32_scalefsd_round_mask:
1925   case X86::BI__builtin_ia32_scalefss_round_mask:
1926   case X86::BI__builtin_ia32_getmantpd512_mask:
1927   case X86::BI__builtin_ia32_getmantps512_mask:
1928   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1929   case X86::BI__builtin_ia32_sqrtsd_round_mask:
1930   case X86::BI__builtin_ia32_sqrtss_round_mask:
1931   case X86::BI__builtin_ia32_vfmaddpd512_mask:
1932   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1933   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1934   case X86::BI__builtin_ia32_vfmaddps512_mask:
1935   case X86::BI__builtin_ia32_vfmaddps512_mask3:
1936   case X86::BI__builtin_ia32_vfmaddps512_maskz:
1937   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1938   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1939   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1940   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1941   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1942   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1943   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1944   case X86::BI__builtin_ia32_vfmsubps512_mask3:
1945   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1946   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1947   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1948   case X86::BI__builtin_ia32_vfnmaddps512_mask:
1949   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1950   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1951   case X86::BI__builtin_ia32_vfnmsubps512_mask:
1952   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1953   case X86::BI__builtin_ia32_vfmaddsd3_mask:
1954   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1955   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1956   case X86::BI__builtin_ia32_vfmaddss3_mask:
1957   case X86::BI__builtin_ia32_vfmaddss3_maskz:
1958   case X86::BI__builtin_ia32_vfmaddss3_mask3:
1959     ArgNum = 4;
1960     HasRC = true;
1961     break;
1962   case X86::BI__builtin_ia32_getmantsd_round_mask:
1963   case X86::BI__builtin_ia32_getmantss_round_mask:
1964     ArgNum = 5;
1965     HasRC = true;
1966     break;
1967   }
1968 
1969   llvm::APSInt Result;
1970 
1971   // We can't check the value of a dependent argument.
1972   Expr *Arg = TheCall->getArg(ArgNum);
1973   if (Arg->isTypeDependent() || Arg->isValueDependent())
1974     return false;
1975 
1976   // Check constant-ness first.
1977   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1978     return true;
1979 
1980   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1981   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1982   // combined with ROUND_NO_EXC.
1983   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1984       Result == 8/*ROUND_NO_EXC*/ ||
1985       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1986     return false;
1987 
1988   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1989     << Arg->getSourceRange();
1990 }
1991 
1992 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1993   if (BuiltinID == X86::BI__builtin_cpu_supports)
1994     return SemaBuiltinCpuSupports(*this, TheCall);
1995 
1996   if (BuiltinID == X86::BI__builtin_ms_va_start)
1997     return SemaBuiltinMSVAStart(TheCall);
1998 
1999   // If the intrinsic has rounding or SAE make sure its valid.
2000   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2001     return true;
2002 
2003   // For intrinsics which take an immediate value as part of the instruction,
2004   // range check them here.
2005   int i = 0, l = 0, u = 0;
2006   switch (BuiltinID) {
2007   default:
2008     return false;
2009   case X86::BI_mm_prefetch:
2010     i = 1; l = 0; u = 3;
2011     break;
2012   case X86::BI__builtin_ia32_sha1rnds4:
2013   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2014   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2015   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2016   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2017     i = 2; l = 0; u = 3;
2018     break;
2019   case X86::BI__builtin_ia32_vpermil2pd:
2020   case X86::BI__builtin_ia32_vpermil2pd256:
2021   case X86::BI__builtin_ia32_vpermil2ps:
2022   case X86::BI__builtin_ia32_vpermil2ps256:
2023     i = 3; l = 0; u = 3;
2024     break;
2025   case X86::BI__builtin_ia32_cmpb128_mask:
2026   case X86::BI__builtin_ia32_cmpw128_mask:
2027   case X86::BI__builtin_ia32_cmpd128_mask:
2028   case X86::BI__builtin_ia32_cmpq128_mask:
2029   case X86::BI__builtin_ia32_cmpb256_mask:
2030   case X86::BI__builtin_ia32_cmpw256_mask:
2031   case X86::BI__builtin_ia32_cmpd256_mask:
2032   case X86::BI__builtin_ia32_cmpq256_mask:
2033   case X86::BI__builtin_ia32_cmpb512_mask:
2034   case X86::BI__builtin_ia32_cmpw512_mask:
2035   case X86::BI__builtin_ia32_cmpd512_mask:
2036   case X86::BI__builtin_ia32_cmpq512_mask:
2037   case X86::BI__builtin_ia32_ucmpb128_mask:
2038   case X86::BI__builtin_ia32_ucmpw128_mask:
2039   case X86::BI__builtin_ia32_ucmpd128_mask:
2040   case X86::BI__builtin_ia32_ucmpq128_mask:
2041   case X86::BI__builtin_ia32_ucmpb256_mask:
2042   case X86::BI__builtin_ia32_ucmpw256_mask:
2043   case X86::BI__builtin_ia32_ucmpd256_mask:
2044   case X86::BI__builtin_ia32_ucmpq256_mask:
2045   case X86::BI__builtin_ia32_ucmpb512_mask:
2046   case X86::BI__builtin_ia32_ucmpw512_mask:
2047   case X86::BI__builtin_ia32_ucmpd512_mask:
2048   case X86::BI__builtin_ia32_ucmpq512_mask:
2049   case X86::BI__builtin_ia32_vpcomub:
2050   case X86::BI__builtin_ia32_vpcomuw:
2051   case X86::BI__builtin_ia32_vpcomud:
2052   case X86::BI__builtin_ia32_vpcomuq:
2053   case X86::BI__builtin_ia32_vpcomb:
2054   case X86::BI__builtin_ia32_vpcomw:
2055   case X86::BI__builtin_ia32_vpcomd:
2056   case X86::BI__builtin_ia32_vpcomq:
2057     i = 2; l = 0; u = 7;
2058     break;
2059   case X86::BI__builtin_ia32_roundps:
2060   case X86::BI__builtin_ia32_roundpd:
2061   case X86::BI__builtin_ia32_roundps256:
2062   case X86::BI__builtin_ia32_roundpd256:
2063     i = 1; l = 0; u = 15;
2064     break;
2065   case X86::BI__builtin_ia32_roundss:
2066   case X86::BI__builtin_ia32_roundsd:
2067   case X86::BI__builtin_ia32_rangepd128_mask:
2068   case X86::BI__builtin_ia32_rangepd256_mask:
2069   case X86::BI__builtin_ia32_rangepd512_mask:
2070   case X86::BI__builtin_ia32_rangeps128_mask:
2071   case X86::BI__builtin_ia32_rangeps256_mask:
2072   case X86::BI__builtin_ia32_rangeps512_mask:
2073   case X86::BI__builtin_ia32_getmantsd_round_mask:
2074   case X86::BI__builtin_ia32_getmantss_round_mask:
2075     i = 2; l = 0; u = 15;
2076     break;
2077   case X86::BI__builtin_ia32_cmpps:
2078   case X86::BI__builtin_ia32_cmpss:
2079   case X86::BI__builtin_ia32_cmppd:
2080   case X86::BI__builtin_ia32_cmpsd:
2081   case X86::BI__builtin_ia32_cmpps256:
2082   case X86::BI__builtin_ia32_cmppd256:
2083   case X86::BI__builtin_ia32_cmpps128_mask:
2084   case X86::BI__builtin_ia32_cmppd128_mask:
2085   case X86::BI__builtin_ia32_cmpps256_mask:
2086   case X86::BI__builtin_ia32_cmppd256_mask:
2087   case X86::BI__builtin_ia32_cmpps512_mask:
2088   case X86::BI__builtin_ia32_cmppd512_mask:
2089   case X86::BI__builtin_ia32_cmpsd_mask:
2090   case X86::BI__builtin_ia32_cmpss_mask:
2091     i = 2; l = 0; u = 31;
2092     break;
2093   case X86::BI__builtin_ia32_xabort:
2094     i = 0; l = -128; u = 255;
2095     break;
2096   case X86::BI__builtin_ia32_pshufw:
2097   case X86::BI__builtin_ia32_aeskeygenassist128:
2098     i = 1; l = -128; u = 255;
2099     break;
2100   case X86::BI__builtin_ia32_vcvtps2ph:
2101   case X86::BI__builtin_ia32_vcvtps2ph256:
2102   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2103   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2104   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2105   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2106   case X86::BI__builtin_ia32_rndscaleps_mask:
2107   case X86::BI__builtin_ia32_rndscalepd_mask:
2108   case X86::BI__builtin_ia32_reducepd128_mask:
2109   case X86::BI__builtin_ia32_reducepd256_mask:
2110   case X86::BI__builtin_ia32_reducepd512_mask:
2111   case X86::BI__builtin_ia32_reduceps128_mask:
2112   case X86::BI__builtin_ia32_reduceps256_mask:
2113   case X86::BI__builtin_ia32_reduceps512_mask:
2114   case X86::BI__builtin_ia32_prold512_mask:
2115   case X86::BI__builtin_ia32_prolq512_mask:
2116   case X86::BI__builtin_ia32_prold128_mask:
2117   case X86::BI__builtin_ia32_prold256_mask:
2118   case X86::BI__builtin_ia32_prolq128_mask:
2119   case X86::BI__builtin_ia32_prolq256_mask:
2120   case X86::BI__builtin_ia32_prord128_mask:
2121   case X86::BI__builtin_ia32_prord256_mask:
2122   case X86::BI__builtin_ia32_prorq128_mask:
2123   case X86::BI__builtin_ia32_prorq256_mask:
2124   case X86::BI__builtin_ia32_fpclasspd128_mask:
2125   case X86::BI__builtin_ia32_fpclasspd256_mask:
2126   case X86::BI__builtin_ia32_fpclassps128_mask:
2127   case X86::BI__builtin_ia32_fpclassps256_mask:
2128   case X86::BI__builtin_ia32_fpclassps512_mask:
2129   case X86::BI__builtin_ia32_fpclasspd512_mask:
2130   case X86::BI__builtin_ia32_fpclasssd_mask:
2131   case X86::BI__builtin_ia32_fpclassss_mask:
2132     i = 1; l = 0; u = 255;
2133     break;
2134   case X86::BI__builtin_ia32_palignr:
2135   case X86::BI__builtin_ia32_insertps128:
2136   case X86::BI__builtin_ia32_dpps:
2137   case X86::BI__builtin_ia32_dppd:
2138   case X86::BI__builtin_ia32_dpps256:
2139   case X86::BI__builtin_ia32_mpsadbw128:
2140   case X86::BI__builtin_ia32_mpsadbw256:
2141   case X86::BI__builtin_ia32_pcmpistrm128:
2142   case X86::BI__builtin_ia32_pcmpistri128:
2143   case X86::BI__builtin_ia32_pcmpistria128:
2144   case X86::BI__builtin_ia32_pcmpistric128:
2145   case X86::BI__builtin_ia32_pcmpistrio128:
2146   case X86::BI__builtin_ia32_pcmpistris128:
2147   case X86::BI__builtin_ia32_pcmpistriz128:
2148   case X86::BI__builtin_ia32_pclmulqdq128:
2149   case X86::BI__builtin_ia32_vperm2f128_pd256:
2150   case X86::BI__builtin_ia32_vperm2f128_ps256:
2151   case X86::BI__builtin_ia32_vperm2f128_si256:
2152   case X86::BI__builtin_ia32_permti256:
2153     i = 2; l = -128; u = 255;
2154     break;
2155   case X86::BI__builtin_ia32_palignr128:
2156   case X86::BI__builtin_ia32_palignr256:
2157   case X86::BI__builtin_ia32_palignr512_mask:
2158   case X86::BI__builtin_ia32_alignq512_mask:
2159   case X86::BI__builtin_ia32_alignd512_mask:
2160   case X86::BI__builtin_ia32_alignd128_mask:
2161   case X86::BI__builtin_ia32_alignd256_mask:
2162   case X86::BI__builtin_ia32_alignq128_mask:
2163   case X86::BI__builtin_ia32_alignq256_mask:
2164   case X86::BI__builtin_ia32_vcomisd:
2165   case X86::BI__builtin_ia32_vcomiss:
2166   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2167   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2168   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2169   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2170   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2171   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2172   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2173     i = 2; l = 0; u = 255;
2174     break;
2175   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2176   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2177   case X86::BI__builtin_ia32_fixupimmps512_mask:
2178   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2179   case X86::BI__builtin_ia32_fixupimmsd_mask:
2180   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2181   case X86::BI__builtin_ia32_fixupimmss_mask:
2182   case X86::BI__builtin_ia32_fixupimmss_maskz:
2183   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2184   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2185   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2186   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2187   case X86::BI__builtin_ia32_fixupimmps128_mask:
2188   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2189   case X86::BI__builtin_ia32_fixupimmps256_mask:
2190   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2191   case X86::BI__builtin_ia32_pternlogd512_mask:
2192   case X86::BI__builtin_ia32_pternlogd512_maskz:
2193   case X86::BI__builtin_ia32_pternlogq512_mask:
2194   case X86::BI__builtin_ia32_pternlogq512_maskz:
2195   case X86::BI__builtin_ia32_pternlogd128_mask:
2196   case X86::BI__builtin_ia32_pternlogd128_maskz:
2197   case X86::BI__builtin_ia32_pternlogd256_mask:
2198   case X86::BI__builtin_ia32_pternlogd256_maskz:
2199   case X86::BI__builtin_ia32_pternlogq128_mask:
2200   case X86::BI__builtin_ia32_pternlogq128_maskz:
2201   case X86::BI__builtin_ia32_pternlogq256_mask:
2202   case X86::BI__builtin_ia32_pternlogq256_maskz:
2203     i = 3; l = 0; u = 255;
2204     break;
2205   case X86::BI__builtin_ia32_pcmpestrm128:
2206   case X86::BI__builtin_ia32_pcmpestri128:
2207   case X86::BI__builtin_ia32_pcmpestria128:
2208   case X86::BI__builtin_ia32_pcmpestric128:
2209   case X86::BI__builtin_ia32_pcmpestrio128:
2210   case X86::BI__builtin_ia32_pcmpestris128:
2211   case X86::BI__builtin_ia32_pcmpestriz128:
2212     i = 4; l = -128; u = 255;
2213     break;
2214   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2215   case X86::BI__builtin_ia32_rndscaless_round_mask:
2216     i = 4; l = 0; u = 255;
2217     break;
2218   }
2219   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2220 }
2221 
2222 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2223 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2224 /// Returns true when the format fits the function and the FormatStringInfo has
2225 /// been populated.
2226 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2227                                FormatStringInfo *FSI) {
2228   FSI->HasVAListArg = Format->getFirstArg() == 0;
2229   FSI->FormatIdx = Format->getFormatIdx() - 1;
2230   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2231 
2232   // The way the format attribute works in GCC, the implicit this argument
2233   // of member functions is counted. However, it doesn't appear in our own
2234   // lists, so decrement format_idx in that case.
2235   if (IsCXXMember) {
2236     if(FSI->FormatIdx == 0)
2237       return false;
2238     --FSI->FormatIdx;
2239     if (FSI->FirstDataArg != 0)
2240       --FSI->FirstDataArg;
2241   }
2242   return true;
2243 }
2244 
2245 /// Checks if a the given expression evaluates to null.
2246 ///
2247 /// \brief Returns true if the value evaluates to null.
2248 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2249   // If the expression has non-null type, it doesn't evaluate to null.
2250   if (auto nullability
2251         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2252     if (*nullability == NullabilityKind::NonNull)
2253       return false;
2254   }
2255 
2256   // As a special case, transparent unions initialized with zero are
2257   // considered null for the purposes of the nonnull attribute.
2258   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2259     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2260       if (const CompoundLiteralExpr *CLE =
2261           dyn_cast<CompoundLiteralExpr>(Expr))
2262         if (const InitListExpr *ILE =
2263             dyn_cast<InitListExpr>(CLE->getInitializer()))
2264           Expr = ILE->getInit(0);
2265   }
2266 
2267   bool Result;
2268   return (!Expr->isValueDependent() &&
2269           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2270           !Result);
2271 }
2272 
2273 static void CheckNonNullArgument(Sema &S,
2274                                  const Expr *ArgExpr,
2275                                  SourceLocation CallSiteLoc) {
2276   if (CheckNonNullExpr(S, ArgExpr))
2277     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2278            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2279 }
2280 
2281 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2282   FormatStringInfo FSI;
2283   if ((GetFormatStringType(Format) == FST_NSString) &&
2284       getFormatStringInfo(Format, false, &FSI)) {
2285     Idx = FSI.FormatIdx;
2286     return true;
2287   }
2288   return false;
2289 }
2290 /// \brief Diagnose use of %s directive in an NSString which is being passed
2291 /// as formatting string to formatting method.
2292 static void
2293 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2294                                         const NamedDecl *FDecl,
2295                                         Expr **Args,
2296                                         unsigned NumArgs) {
2297   unsigned Idx = 0;
2298   bool Format = false;
2299   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2300   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2301     Idx = 2;
2302     Format = true;
2303   }
2304   else
2305     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2306       if (S.GetFormatNSStringIdx(I, Idx)) {
2307         Format = true;
2308         break;
2309       }
2310     }
2311   if (!Format || NumArgs <= Idx)
2312     return;
2313   const Expr *FormatExpr = Args[Idx];
2314   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2315     FormatExpr = CSCE->getSubExpr();
2316   const StringLiteral *FormatString;
2317   if (const ObjCStringLiteral *OSL =
2318       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2319     FormatString = OSL->getString();
2320   else
2321     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2322   if (!FormatString)
2323     return;
2324   if (S.FormatStringHasSArg(FormatString)) {
2325     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2326       << "%s" << 1 << 1;
2327     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2328       << FDecl->getDeclName();
2329   }
2330 }
2331 
2332 /// Determine whether the given type has a non-null nullability annotation.
2333 static bool isNonNullType(ASTContext &ctx, QualType type) {
2334   if (auto nullability = type->getNullability(ctx))
2335     return *nullability == NullabilityKind::NonNull;
2336 
2337   return false;
2338 }
2339 
2340 static void CheckNonNullArguments(Sema &S,
2341                                   const NamedDecl *FDecl,
2342                                   const FunctionProtoType *Proto,
2343                                   ArrayRef<const Expr *> Args,
2344                                   SourceLocation CallSiteLoc) {
2345   assert((FDecl || Proto) && "Need a function declaration or prototype");
2346 
2347   // Check the attributes attached to the method/function itself.
2348   llvm::SmallBitVector NonNullArgs;
2349   if (FDecl) {
2350     // Handle the nonnull attribute on the function/method declaration itself.
2351     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2352       if (!NonNull->args_size()) {
2353         // Easy case: all pointer arguments are nonnull.
2354         for (const auto *Arg : Args)
2355           if (S.isValidPointerAttrType(Arg->getType()))
2356             CheckNonNullArgument(S, Arg, CallSiteLoc);
2357         return;
2358       }
2359 
2360       for (unsigned Val : NonNull->args()) {
2361         if (Val >= Args.size())
2362           continue;
2363         if (NonNullArgs.empty())
2364           NonNullArgs.resize(Args.size());
2365         NonNullArgs.set(Val);
2366       }
2367     }
2368   }
2369 
2370   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2371     // Handle the nonnull attribute on the parameters of the
2372     // function/method.
2373     ArrayRef<ParmVarDecl*> parms;
2374     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2375       parms = FD->parameters();
2376     else
2377       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2378 
2379     unsigned ParamIndex = 0;
2380     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2381          I != E; ++I, ++ParamIndex) {
2382       const ParmVarDecl *PVD = *I;
2383       if (PVD->hasAttr<NonNullAttr>() ||
2384           isNonNullType(S.Context, PVD->getType())) {
2385         if (NonNullArgs.empty())
2386           NonNullArgs.resize(Args.size());
2387 
2388         NonNullArgs.set(ParamIndex);
2389       }
2390     }
2391   } else {
2392     // If we have a non-function, non-method declaration but no
2393     // function prototype, try to dig out the function prototype.
2394     if (!Proto) {
2395       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2396         QualType type = VD->getType().getNonReferenceType();
2397         if (auto pointerType = type->getAs<PointerType>())
2398           type = pointerType->getPointeeType();
2399         else if (auto blockType = type->getAs<BlockPointerType>())
2400           type = blockType->getPointeeType();
2401         // FIXME: data member pointers?
2402 
2403         // Dig out the function prototype, if there is one.
2404         Proto = type->getAs<FunctionProtoType>();
2405       }
2406     }
2407 
2408     // Fill in non-null argument information from the nullability
2409     // information on the parameter types (if we have them).
2410     if (Proto) {
2411       unsigned Index = 0;
2412       for (auto paramType : Proto->getParamTypes()) {
2413         if (isNonNullType(S.Context, paramType)) {
2414           if (NonNullArgs.empty())
2415             NonNullArgs.resize(Args.size());
2416 
2417           NonNullArgs.set(Index);
2418         }
2419 
2420         ++Index;
2421       }
2422     }
2423   }
2424 
2425   // Check for non-null arguments.
2426   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2427        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2428     if (NonNullArgs[ArgIndex])
2429       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2430   }
2431 }
2432 
2433 /// Handles the checks for format strings, non-POD arguments to vararg
2434 /// functions, and NULL arguments passed to non-NULL parameters.
2435 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2436                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
2437                      SourceLocation Loc, SourceRange Range,
2438                      VariadicCallType CallType) {
2439   // FIXME: We should check as much as we can in the template definition.
2440   if (CurContext->isDependentContext())
2441     return;
2442 
2443   // Printf and scanf checking.
2444   llvm::SmallBitVector CheckedVarArgs;
2445   if (FDecl) {
2446     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2447       // Only create vector if there are format attributes.
2448       CheckedVarArgs.resize(Args.size());
2449 
2450       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2451                            CheckedVarArgs);
2452     }
2453   }
2454 
2455   // Refuse POD arguments that weren't caught by the format string
2456   // checks above.
2457   if (CallType != VariadicDoesNotApply) {
2458     unsigned NumParams = Proto ? Proto->getNumParams()
2459                        : FDecl && isa<FunctionDecl>(FDecl)
2460                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2461                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2462                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2463                        : 0;
2464 
2465     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2466       // Args[ArgIdx] can be null in malformed code.
2467       if (const Expr *Arg = Args[ArgIdx]) {
2468         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2469           checkVariadicArgument(Arg, CallType);
2470       }
2471     }
2472   }
2473 
2474   if (FDecl || Proto) {
2475     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2476 
2477     // Type safety checking.
2478     if (FDecl) {
2479       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2480         CheckArgumentWithTypeTag(I, Args.data());
2481     }
2482   }
2483 }
2484 
2485 /// CheckConstructorCall - Check a constructor call for correctness and safety
2486 /// properties not enforced by the C type system.
2487 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2488                                 ArrayRef<const Expr *> Args,
2489                                 const FunctionProtoType *Proto,
2490                                 SourceLocation Loc) {
2491   VariadicCallType CallType =
2492     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2493   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2494             CallType);
2495 }
2496 
2497 /// CheckFunctionCall - Check a direct function call for various correctness
2498 /// and safety properties not strictly enforced by the C type system.
2499 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2500                              const FunctionProtoType *Proto) {
2501   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2502                               isa<CXXMethodDecl>(FDecl);
2503   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2504                           IsMemberOperatorCall;
2505   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2506                                                   TheCall->getCallee());
2507   Expr** Args = TheCall->getArgs();
2508   unsigned NumArgs = TheCall->getNumArgs();
2509   if (IsMemberOperatorCall) {
2510     // If this is a call to a member operator, hide the first argument
2511     // from checkCall.
2512     // FIXME: Our choice of AST representation here is less than ideal.
2513     ++Args;
2514     --NumArgs;
2515   }
2516   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2517             IsMemberFunction, TheCall->getRParenLoc(),
2518             TheCall->getCallee()->getSourceRange(), CallType);
2519 
2520   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2521   // None of the checks below are needed for functions that don't have
2522   // simple names (e.g., C++ conversion functions).
2523   if (!FnInfo)
2524     return false;
2525 
2526   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
2527   if (getLangOpts().ObjC1)
2528     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2529 
2530   unsigned CMId = FDecl->getMemoryFunctionKind();
2531   if (CMId == 0)
2532     return false;
2533 
2534   // Handle memory setting and copying functions.
2535   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2536     CheckStrlcpycatArguments(TheCall, FnInfo);
2537   else if (CMId == Builtin::BIstrncat)
2538     CheckStrncatArguments(TheCall, FnInfo);
2539   else
2540     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2541 
2542   return false;
2543 }
2544 
2545 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2546                                ArrayRef<const Expr *> Args) {
2547   VariadicCallType CallType =
2548       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2549 
2550   checkCall(Method, nullptr, Args,
2551             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2552             CallType);
2553 
2554   return false;
2555 }
2556 
2557 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2558                             const FunctionProtoType *Proto) {
2559   QualType Ty;
2560   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2561     Ty = V->getType().getNonReferenceType();
2562   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2563     Ty = F->getType().getNonReferenceType();
2564   else
2565     return false;
2566 
2567   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2568       !Ty->isFunctionProtoType())
2569     return false;
2570 
2571   VariadicCallType CallType;
2572   if (!Proto || !Proto->isVariadic()) {
2573     CallType = VariadicDoesNotApply;
2574   } else if (Ty->isBlockPointerType()) {
2575     CallType = VariadicBlock;
2576   } else { // Ty->isFunctionPointerType()
2577     CallType = VariadicFunction;
2578   }
2579 
2580   checkCall(NDecl, Proto,
2581             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2582             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2583             TheCall->getCallee()->getSourceRange(), CallType);
2584 
2585   return false;
2586 }
2587 
2588 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2589 /// such as function pointers returned from functions.
2590 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2591   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2592                                                   TheCall->getCallee());
2593   checkCall(/*FDecl=*/nullptr, Proto,
2594             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2595             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2596             TheCall->getCallee()->getSourceRange(), CallType);
2597 
2598   return false;
2599 }
2600 
2601 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2602   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2603     return false;
2604 
2605   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2606   switch (Op) {
2607   case AtomicExpr::AO__c11_atomic_init:
2608     llvm_unreachable("There is no ordering argument for an init");
2609 
2610   case AtomicExpr::AO__c11_atomic_load:
2611   case AtomicExpr::AO__atomic_load_n:
2612   case AtomicExpr::AO__atomic_load:
2613     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2614            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2615 
2616   case AtomicExpr::AO__c11_atomic_store:
2617   case AtomicExpr::AO__atomic_store:
2618   case AtomicExpr::AO__atomic_store_n:
2619     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2620            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2621            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2622 
2623   default:
2624     return true;
2625   }
2626 }
2627 
2628 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2629                                          AtomicExpr::AtomicOp Op) {
2630   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2631   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2632 
2633   // All these operations take one of the following forms:
2634   enum {
2635     // C    __c11_atomic_init(A *, C)
2636     Init,
2637     // C    __c11_atomic_load(A *, int)
2638     Load,
2639     // void __atomic_load(A *, CP, int)
2640     LoadCopy,
2641     // void __atomic_store(A *, CP, int)
2642     Copy,
2643     // C    __c11_atomic_add(A *, M, int)
2644     Arithmetic,
2645     // C    __atomic_exchange_n(A *, CP, int)
2646     Xchg,
2647     // void __atomic_exchange(A *, C *, CP, int)
2648     GNUXchg,
2649     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2650     C11CmpXchg,
2651     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2652     GNUCmpXchg
2653   } Form = Init;
2654   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2655   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2656   // where:
2657   //   C is an appropriate type,
2658   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2659   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2660   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2661   //   the int parameters are for orderings.
2662 
2663   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2664                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2665                         AtomicExpr::AO__atomic_load,
2666                 "need to update code for modified C11 atomics");
2667   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2668                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2669   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2670              Op == AtomicExpr::AO__atomic_store_n ||
2671              Op == AtomicExpr::AO__atomic_exchange_n ||
2672              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2673   bool IsAddSub = false;
2674 
2675   switch (Op) {
2676   case AtomicExpr::AO__c11_atomic_init:
2677     Form = Init;
2678     break;
2679 
2680   case AtomicExpr::AO__c11_atomic_load:
2681   case AtomicExpr::AO__atomic_load_n:
2682     Form = Load;
2683     break;
2684 
2685   case AtomicExpr::AO__atomic_load:
2686     Form = LoadCopy;
2687     break;
2688 
2689   case AtomicExpr::AO__c11_atomic_store:
2690   case AtomicExpr::AO__atomic_store:
2691   case AtomicExpr::AO__atomic_store_n:
2692     Form = Copy;
2693     break;
2694 
2695   case AtomicExpr::AO__c11_atomic_fetch_add:
2696   case AtomicExpr::AO__c11_atomic_fetch_sub:
2697   case AtomicExpr::AO__atomic_fetch_add:
2698   case AtomicExpr::AO__atomic_fetch_sub:
2699   case AtomicExpr::AO__atomic_add_fetch:
2700   case AtomicExpr::AO__atomic_sub_fetch:
2701     IsAddSub = true;
2702     // Fall through.
2703   case AtomicExpr::AO__c11_atomic_fetch_and:
2704   case AtomicExpr::AO__c11_atomic_fetch_or:
2705   case AtomicExpr::AO__c11_atomic_fetch_xor:
2706   case AtomicExpr::AO__atomic_fetch_and:
2707   case AtomicExpr::AO__atomic_fetch_or:
2708   case AtomicExpr::AO__atomic_fetch_xor:
2709   case AtomicExpr::AO__atomic_fetch_nand:
2710   case AtomicExpr::AO__atomic_and_fetch:
2711   case AtomicExpr::AO__atomic_or_fetch:
2712   case AtomicExpr::AO__atomic_xor_fetch:
2713   case AtomicExpr::AO__atomic_nand_fetch:
2714     Form = Arithmetic;
2715     break;
2716 
2717   case AtomicExpr::AO__c11_atomic_exchange:
2718   case AtomicExpr::AO__atomic_exchange_n:
2719     Form = Xchg;
2720     break;
2721 
2722   case AtomicExpr::AO__atomic_exchange:
2723     Form = GNUXchg;
2724     break;
2725 
2726   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2727   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2728     Form = C11CmpXchg;
2729     break;
2730 
2731   case AtomicExpr::AO__atomic_compare_exchange:
2732   case AtomicExpr::AO__atomic_compare_exchange_n:
2733     Form = GNUCmpXchg;
2734     break;
2735   }
2736 
2737   // Check we have the right number of arguments.
2738   if (TheCall->getNumArgs() < NumArgs[Form]) {
2739     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2740       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2741       << TheCall->getCallee()->getSourceRange();
2742     return ExprError();
2743   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2744     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2745          diag::err_typecheck_call_too_many_args)
2746       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2747       << TheCall->getCallee()->getSourceRange();
2748     return ExprError();
2749   }
2750 
2751   // Inspect the first argument of the atomic operation.
2752   Expr *Ptr = TheCall->getArg(0);
2753   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2754   if (ConvertedPtr.isInvalid())
2755     return ExprError();
2756 
2757   Ptr = ConvertedPtr.get();
2758   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2759   if (!pointerType) {
2760     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2761       << Ptr->getType() << Ptr->getSourceRange();
2762     return ExprError();
2763   }
2764 
2765   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2766   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2767   QualType ValType = AtomTy; // 'C'
2768   if (IsC11) {
2769     if (!AtomTy->isAtomicType()) {
2770       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2771         << Ptr->getType() << Ptr->getSourceRange();
2772       return ExprError();
2773     }
2774     if (AtomTy.isConstQualified()) {
2775       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2776         << Ptr->getType() << Ptr->getSourceRange();
2777       return ExprError();
2778     }
2779     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2780   } else if (Form != Load && Form != LoadCopy) {
2781     if (ValType.isConstQualified()) {
2782       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2783         << Ptr->getType() << Ptr->getSourceRange();
2784       return ExprError();
2785     }
2786   }
2787 
2788   // For an arithmetic operation, the implied arithmetic must be well-formed.
2789   if (Form == Arithmetic) {
2790     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2791     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2792       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2793         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2794       return ExprError();
2795     }
2796     if (!IsAddSub && !ValType->isIntegerType()) {
2797       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2798         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2799       return ExprError();
2800     }
2801     if (IsC11 && ValType->isPointerType() &&
2802         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2803                             diag::err_incomplete_type)) {
2804       return ExprError();
2805     }
2806   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2807     // For __atomic_*_n operations, the value type must be a scalar integral or
2808     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2809     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2810       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2811     return ExprError();
2812   }
2813 
2814   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2815       !AtomTy->isScalarType()) {
2816     // For GNU atomics, require a trivially-copyable type. This is not part of
2817     // the GNU atomics specification, but we enforce it for sanity.
2818     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2819       << Ptr->getType() << Ptr->getSourceRange();
2820     return ExprError();
2821   }
2822 
2823   switch (ValType.getObjCLifetime()) {
2824   case Qualifiers::OCL_None:
2825   case Qualifiers::OCL_ExplicitNone:
2826     // okay
2827     break;
2828 
2829   case Qualifiers::OCL_Weak:
2830   case Qualifiers::OCL_Strong:
2831   case Qualifiers::OCL_Autoreleasing:
2832     // FIXME: Can this happen? By this point, ValType should be known
2833     // to be trivially copyable.
2834     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2835       << ValType << Ptr->getSourceRange();
2836     return ExprError();
2837   }
2838 
2839   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2840   // volatile-ness of the pointee-type inject itself into the result or the
2841   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2842   ValType.removeLocalVolatile();
2843   ValType.removeLocalConst();
2844   QualType ResultType = ValType;
2845   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2846     ResultType = Context.VoidTy;
2847   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2848     ResultType = Context.BoolTy;
2849 
2850   // The type of a parameter passed 'by value'. In the GNU atomics, such
2851   // arguments are actually passed as pointers.
2852   QualType ByValType = ValType; // 'CP'
2853   if (!IsC11 && !IsN)
2854     ByValType = Ptr->getType();
2855 
2856   // The first argument --- the pointer --- has a fixed type; we
2857   // deduce the types of the rest of the arguments accordingly.  Walk
2858   // the remaining arguments, converting them to the deduced value type.
2859   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2860     QualType Ty;
2861     if (i < NumVals[Form] + 1) {
2862       switch (i) {
2863       case 1:
2864         // The second argument is the non-atomic operand. For arithmetic, this
2865         // is always passed by value, and for a compare_exchange it is always
2866         // passed by address. For the rest, GNU uses by-address and C11 uses
2867         // by-value.
2868         assert(Form != Load);
2869         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2870           Ty = ValType;
2871         else if (Form == Copy || Form == Xchg)
2872           Ty = ByValType;
2873         else if (Form == Arithmetic)
2874           Ty = Context.getPointerDiffType();
2875         else {
2876           Expr *ValArg = TheCall->getArg(i);
2877           unsigned AS = 0;
2878           // Keep address space of non-atomic pointer type.
2879           if (const PointerType *PtrTy =
2880                   ValArg->getType()->getAs<PointerType>()) {
2881             AS = PtrTy->getPointeeType().getAddressSpace();
2882           }
2883           Ty = Context.getPointerType(
2884               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2885         }
2886         break;
2887       case 2:
2888         // The third argument to compare_exchange / GNU exchange is a
2889         // (pointer to a) desired value.
2890         Ty = ByValType;
2891         break;
2892       case 3:
2893         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2894         Ty = Context.BoolTy;
2895         break;
2896       }
2897     } else {
2898       // The order(s) are always converted to int.
2899       Ty = Context.IntTy;
2900     }
2901 
2902     InitializedEntity Entity =
2903         InitializedEntity::InitializeParameter(Context, Ty, false);
2904     ExprResult Arg = TheCall->getArg(i);
2905     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2906     if (Arg.isInvalid())
2907       return true;
2908     TheCall->setArg(i, Arg.get());
2909   }
2910 
2911   // Permute the arguments into a 'consistent' order.
2912   SmallVector<Expr*, 5> SubExprs;
2913   SubExprs.push_back(Ptr);
2914   switch (Form) {
2915   case Init:
2916     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2917     SubExprs.push_back(TheCall->getArg(1)); // Val1
2918     break;
2919   case Load:
2920     SubExprs.push_back(TheCall->getArg(1)); // Order
2921     break;
2922   case LoadCopy:
2923   case Copy:
2924   case Arithmetic:
2925   case Xchg:
2926     SubExprs.push_back(TheCall->getArg(2)); // Order
2927     SubExprs.push_back(TheCall->getArg(1)); // Val1
2928     break;
2929   case GNUXchg:
2930     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2931     SubExprs.push_back(TheCall->getArg(3)); // Order
2932     SubExprs.push_back(TheCall->getArg(1)); // Val1
2933     SubExprs.push_back(TheCall->getArg(2)); // Val2
2934     break;
2935   case C11CmpXchg:
2936     SubExprs.push_back(TheCall->getArg(3)); // Order
2937     SubExprs.push_back(TheCall->getArg(1)); // Val1
2938     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2939     SubExprs.push_back(TheCall->getArg(2)); // Val2
2940     break;
2941   case GNUCmpXchg:
2942     SubExprs.push_back(TheCall->getArg(4)); // Order
2943     SubExprs.push_back(TheCall->getArg(1)); // Val1
2944     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2945     SubExprs.push_back(TheCall->getArg(2)); // Val2
2946     SubExprs.push_back(TheCall->getArg(3)); // Weak
2947     break;
2948   }
2949 
2950   if (SubExprs.size() >= 2 && Form != Init) {
2951     llvm::APSInt Result(32);
2952     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2953         !isValidOrderingForOp(Result.getSExtValue(), Op))
2954       Diag(SubExprs[1]->getLocStart(),
2955            diag::warn_atomic_op_has_invalid_memory_order)
2956           << SubExprs[1]->getSourceRange();
2957   }
2958 
2959   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2960                                             SubExprs, ResultType, Op,
2961                                             TheCall->getRParenLoc());
2962 
2963   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2964        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2965       Context.AtomicUsesUnsupportedLibcall(AE))
2966     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2967     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2968 
2969   return AE;
2970 }
2971 
2972 /// checkBuiltinArgument - Given a call to a builtin function, perform
2973 /// normal type-checking on the given argument, updating the call in
2974 /// place.  This is useful when a builtin function requires custom
2975 /// type-checking for some of its arguments but not necessarily all of
2976 /// them.
2977 ///
2978 /// Returns true on error.
2979 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2980   FunctionDecl *Fn = E->getDirectCallee();
2981   assert(Fn && "builtin call without direct callee!");
2982 
2983   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2984   InitializedEntity Entity =
2985     InitializedEntity::InitializeParameter(S.Context, Param);
2986 
2987   ExprResult Arg = E->getArg(0);
2988   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2989   if (Arg.isInvalid())
2990     return true;
2991 
2992   E->setArg(ArgIndex, Arg.get());
2993   return false;
2994 }
2995 
2996 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2997 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2998 /// type of its first argument.  The main ActOnCallExpr routines have already
2999 /// promoted the types of arguments because all of these calls are prototyped as
3000 /// void(...).
3001 ///
3002 /// This function goes through and does final semantic checking for these
3003 /// builtins,
3004 ExprResult
3005 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3006   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3007   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3008   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3009 
3010   // Ensure that we have at least one argument to do type inference from.
3011   if (TheCall->getNumArgs() < 1) {
3012     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3013       << 0 << 1 << TheCall->getNumArgs()
3014       << TheCall->getCallee()->getSourceRange();
3015     return ExprError();
3016   }
3017 
3018   // Inspect the first argument of the atomic builtin.  This should always be
3019   // a pointer type, whose element is an integral scalar or pointer type.
3020   // Because it is a pointer type, we don't have to worry about any implicit
3021   // casts here.
3022   // FIXME: We don't allow floating point scalars as input.
3023   Expr *FirstArg = TheCall->getArg(0);
3024   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3025   if (FirstArgResult.isInvalid())
3026     return ExprError();
3027   FirstArg = FirstArgResult.get();
3028   TheCall->setArg(0, FirstArg);
3029 
3030   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3031   if (!pointerType) {
3032     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3033       << FirstArg->getType() << FirstArg->getSourceRange();
3034     return ExprError();
3035   }
3036 
3037   QualType ValType = pointerType->getPointeeType();
3038   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3039       !ValType->isBlockPointerType()) {
3040     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3041       << FirstArg->getType() << FirstArg->getSourceRange();
3042     return ExprError();
3043   }
3044 
3045   switch (ValType.getObjCLifetime()) {
3046   case Qualifiers::OCL_None:
3047   case Qualifiers::OCL_ExplicitNone:
3048     // okay
3049     break;
3050 
3051   case Qualifiers::OCL_Weak:
3052   case Qualifiers::OCL_Strong:
3053   case Qualifiers::OCL_Autoreleasing:
3054     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3055       << ValType << FirstArg->getSourceRange();
3056     return ExprError();
3057   }
3058 
3059   // Strip any qualifiers off ValType.
3060   ValType = ValType.getUnqualifiedType();
3061 
3062   // The majority of builtins return a value, but a few have special return
3063   // types, so allow them to override appropriately below.
3064   QualType ResultType = ValType;
3065 
3066   // We need to figure out which concrete builtin this maps onto.  For example,
3067   // __sync_fetch_and_add with a 2 byte object turns into
3068   // __sync_fetch_and_add_2.
3069 #define BUILTIN_ROW(x) \
3070   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3071     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3072 
3073   static const unsigned BuiltinIndices[][5] = {
3074     BUILTIN_ROW(__sync_fetch_and_add),
3075     BUILTIN_ROW(__sync_fetch_and_sub),
3076     BUILTIN_ROW(__sync_fetch_and_or),
3077     BUILTIN_ROW(__sync_fetch_and_and),
3078     BUILTIN_ROW(__sync_fetch_and_xor),
3079     BUILTIN_ROW(__sync_fetch_and_nand),
3080 
3081     BUILTIN_ROW(__sync_add_and_fetch),
3082     BUILTIN_ROW(__sync_sub_and_fetch),
3083     BUILTIN_ROW(__sync_and_and_fetch),
3084     BUILTIN_ROW(__sync_or_and_fetch),
3085     BUILTIN_ROW(__sync_xor_and_fetch),
3086     BUILTIN_ROW(__sync_nand_and_fetch),
3087 
3088     BUILTIN_ROW(__sync_val_compare_and_swap),
3089     BUILTIN_ROW(__sync_bool_compare_and_swap),
3090     BUILTIN_ROW(__sync_lock_test_and_set),
3091     BUILTIN_ROW(__sync_lock_release),
3092     BUILTIN_ROW(__sync_swap)
3093   };
3094 #undef BUILTIN_ROW
3095 
3096   // Determine the index of the size.
3097   unsigned SizeIndex;
3098   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3099   case 1: SizeIndex = 0; break;
3100   case 2: SizeIndex = 1; break;
3101   case 4: SizeIndex = 2; break;
3102   case 8: SizeIndex = 3; break;
3103   case 16: SizeIndex = 4; break;
3104   default:
3105     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3106       << FirstArg->getType() << FirstArg->getSourceRange();
3107     return ExprError();
3108   }
3109 
3110   // Each of these builtins has one pointer argument, followed by some number of
3111   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3112   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3113   // as the number of fixed args.
3114   unsigned BuiltinID = FDecl->getBuiltinID();
3115   unsigned BuiltinIndex, NumFixed = 1;
3116   bool WarnAboutSemanticsChange = false;
3117   switch (BuiltinID) {
3118   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3119   case Builtin::BI__sync_fetch_and_add:
3120   case Builtin::BI__sync_fetch_and_add_1:
3121   case Builtin::BI__sync_fetch_and_add_2:
3122   case Builtin::BI__sync_fetch_and_add_4:
3123   case Builtin::BI__sync_fetch_and_add_8:
3124   case Builtin::BI__sync_fetch_and_add_16:
3125     BuiltinIndex = 0;
3126     break;
3127 
3128   case Builtin::BI__sync_fetch_and_sub:
3129   case Builtin::BI__sync_fetch_and_sub_1:
3130   case Builtin::BI__sync_fetch_and_sub_2:
3131   case Builtin::BI__sync_fetch_and_sub_4:
3132   case Builtin::BI__sync_fetch_and_sub_8:
3133   case Builtin::BI__sync_fetch_and_sub_16:
3134     BuiltinIndex = 1;
3135     break;
3136 
3137   case Builtin::BI__sync_fetch_and_or:
3138   case Builtin::BI__sync_fetch_and_or_1:
3139   case Builtin::BI__sync_fetch_and_or_2:
3140   case Builtin::BI__sync_fetch_and_or_4:
3141   case Builtin::BI__sync_fetch_and_or_8:
3142   case Builtin::BI__sync_fetch_and_or_16:
3143     BuiltinIndex = 2;
3144     break;
3145 
3146   case Builtin::BI__sync_fetch_and_and:
3147   case Builtin::BI__sync_fetch_and_and_1:
3148   case Builtin::BI__sync_fetch_and_and_2:
3149   case Builtin::BI__sync_fetch_and_and_4:
3150   case Builtin::BI__sync_fetch_and_and_8:
3151   case Builtin::BI__sync_fetch_and_and_16:
3152     BuiltinIndex = 3;
3153     break;
3154 
3155   case Builtin::BI__sync_fetch_and_xor:
3156   case Builtin::BI__sync_fetch_and_xor_1:
3157   case Builtin::BI__sync_fetch_and_xor_2:
3158   case Builtin::BI__sync_fetch_and_xor_4:
3159   case Builtin::BI__sync_fetch_and_xor_8:
3160   case Builtin::BI__sync_fetch_and_xor_16:
3161     BuiltinIndex = 4;
3162     break;
3163 
3164   case Builtin::BI__sync_fetch_and_nand:
3165   case Builtin::BI__sync_fetch_and_nand_1:
3166   case Builtin::BI__sync_fetch_and_nand_2:
3167   case Builtin::BI__sync_fetch_and_nand_4:
3168   case Builtin::BI__sync_fetch_and_nand_8:
3169   case Builtin::BI__sync_fetch_and_nand_16:
3170     BuiltinIndex = 5;
3171     WarnAboutSemanticsChange = true;
3172     break;
3173 
3174   case Builtin::BI__sync_add_and_fetch:
3175   case Builtin::BI__sync_add_and_fetch_1:
3176   case Builtin::BI__sync_add_and_fetch_2:
3177   case Builtin::BI__sync_add_and_fetch_4:
3178   case Builtin::BI__sync_add_and_fetch_8:
3179   case Builtin::BI__sync_add_and_fetch_16:
3180     BuiltinIndex = 6;
3181     break;
3182 
3183   case Builtin::BI__sync_sub_and_fetch:
3184   case Builtin::BI__sync_sub_and_fetch_1:
3185   case Builtin::BI__sync_sub_and_fetch_2:
3186   case Builtin::BI__sync_sub_and_fetch_4:
3187   case Builtin::BI__sync_sub_and_fetch_8:
3188   case Builtin::BI__sync_sub_and_fetch_16:
3189     BuiltinIndex = 7;
3190     break;
3191 
3192   case Builtin::BI__sync_and_and_fetch:
3193   case Builtin::BI__sync_and_and_fetch_1:
3194   case Builtin::BI__sync_and_and_fetch_2:
3195   case Builtin::BI__sync_and_and_fetch_4:
3196   case Builtin::BI__sync_and_and_fetch_8:
3197   case Builtin::BI__sync_and_and_fetch_16:
3198     BuiltinIndex = 8;
3199     break;
3200 
3201   case Builtin::BI__sync_or_and_fetch:
3202   case Builtin::BI__sync_or_and_fetch_1:
3203   case Builtin::BI__sync_or_and_fetch_2:
3204   case Builtin::BI__sync_or_and_fetch_4:
3205   case Builtin::BI__sync_or_and_fetch_8:
3206   case Builtin::BI__sync_or_and_fetch_16:
3207     BuiltinIndex = 9;
3208     break;
3209 
3210   case Builtin::BI__sync_xor_and_fetch:
3211   case Builtin::BI__sync_xor_and_fetch_1:
3212   case Builtin::BI__sync_xor_and_fetch_2:
3213   case Builtin::BI__sync_xor_and_fetch_4:
3214   case Builtin::BI__sync_xor_and_fetch_8:
3215   case Builtin::BI__sync_xor_and_fetch_16:
3216     BuiltinIndex = 10;
3217     break;
3218 
3219   case Builtin::BI__sync_nand_and_fetch:
3220   case Builtin::BI__sync_nand_and_fetch_1:
3221   case Builtin::BI__sync_nand_and_fetch_2:
3222   case Builtin::BI__sync_nand_and_fetch_4:
3223   case Builtin::BI__sync_nand_and_fetch_8:
3224   case Builtin::BI__sync_nand_and_fetch_16:
3225     BuiltinIndex = 11;
3226     WarnAboutSemanticsChange = true;
3227     break;
3228 
3229   case Builtin::BI__sync_val_compare_and_swap:
3230   case Builtin::BI__sync_val_compare_and_swap_1:
3231   case Builtin::BI__sync_val_compare_and_swap_2:
3232   case Builtin::BI__sync_val_compare_and_swap_4:
3233   case Builtin::BI__sync_val_compare_and_swap_8:
3234   case Builtin::BI__sync_val_compare_and_swap_16:
3235     BuiltinIndex = 12;
3236     NumFixed = 2;
3237     break;
3238 
3239   case Builtin::BI__sync_bool_compare_and_swap:
3240   case Builtin::BI__sync_bool_compare_and_swap_1:
3241   case Builtin::BI__sync_bool_compare_and_swap_2:
3242   case Builtin::BI__sync_bool_compare_and_swap_4:
3243   case Builtin::BI__sync_bool_compare_and_swap_8:
3244   case Builtin::BI__sync_bool_compare_and_swap_16:
3245     BuiltinIndex = 13;
3246     NumFixed = 2;
3247     ResultType = Context.BoolTy;
3248     break;
3249 
3250   case Builtin::BI__sync_lock_test_and_set:
3251   case Builtin::BI__sync_lock_test_and_set_1:
3252   case Builtin::BI__sync_lock_test_and_set_2:
3253   case Builtin::BI__sync_lock_test_and_set_4:
3254   case Builtin::BI__sync_lock_test_and_set_8:
3255   case Builtin::BI__sync_lock_test_and_set_16:
3256     BuiltinIndex = 14;
3257     break;
3258 
3259   case Builtin::BI__sync_lock_release:
3260   case Builtin::BI__sync_lock_release_1:
3261   case Builtin::BI__sync_lock_release_2:
3262   case Builtin::BI__sync_lock_release_4:
3263   case Builtin::BI__sync_lock_release_8:
3264   case Builtin::BI__sync_lock_release_16:
3265     BuiltinIndex = 15;
3266     NumFixed = 0;
3267     ResultType = Context.VoidTy;
3268     break;
3269 
3270   case Builtin::BI__sync_swap:
3271   case Builtin::BI__sync_swap_1:
3272   case Builtin::BI__sync_swap_2:
3273   case Builtin::BI__sync_swap_4:
3274   case Builtin::BI__sync_swap_8:
3275   case Builtin::BI__sync_swap_16:
3276     BuiltinIndex = 16;
3277     break;
3278   }
3279 
3280   // Now that we know how many fixed arguments we expect, first check that we
3281   // have at least that many.
3282   if (TheCall->getNumArgs() < 1+NumFixed) {
3283     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3284       << 0 << 1+NumFixed << TheCall->getNumArgs()
3285       << TheCall->getCallee()->getSourceRange();
3286     return ExprError();
3287   }
3288 
3289   if (WarnAboutSemanticsChange) {
3290     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3291       << TheCall->getCallee()->getSourceRange();
3292   }
3293 
3294   // Get the decl for the concrete builtin from this, we can tell what the
3295   // concrete integer type we should convert to is.
3296   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3297   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3298   FunctionDecl *NewBuiltinDecl;
3299   if (NewBuiltinID == BuiltinID)
3300     NewBuiltinDecl = FDecl;
3301   else {
3302     // Perform builtin lookup to avoid redeclaring it.
3303     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3304     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3305     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3306     assert(Res.getFoundDecl());
3307     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3308     if (!NewBuiltinDecl)
3309       return ExprError();
3310   }
3311 
3312   // The first argument --- the pointer --- has a fixed type; we
3313   // deduce the types of the rest of the arguments accordingly.  Walk
3314   // the remaining arguments, converting them to the deduced value type.
3315   for (unsigned i = 0; i != NumFixed; ++i) {
3316     ExprResult Arg = TheCall->getArg(i+1);
3317 
3318     // GCC does an implicit conversion to the pointer or integer ValType.  This
3319     // can fail in some cases (1i -> int**), check for this error case now.
3320     // Initialize the argument.
3321     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3322                                                    ValType, /*consume*/ false);
3323     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3324     if (Arg.isInvalid())
3325       return ExprError();
3326 
3327     // Okay, we have something that *can* be converted to the right type.  Check
3328     // to see if there is a potentially weird extension going on here.  This can
3329     // happen when you do an atomic operation on something like an char* and
3330     // pass in 42.  The 42 gets converted to char.  This is even more strange
3331     // for things like 45.123 -> char, etc.
3332     // FIXME: Do this check.
3333     TheCall->setArg(i+1, Arg.get());
3334   }
3335 
3336   ASTContext& Context = this->getASTContext();
3337 
3338   // Create a new DeclRefExpr to refer to the new decl.
3339   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3340       Context,
3341       DRE->getQualifierLoc(),
3342       SourceLocation(),
3343       NewBuiltinDecl,
3344       /*enclosing*/ false,
3345       DRE->getLocation(),
3346       Context.BuiltinFnTy,
3347       DRE->getValueKind());
3348 
3349   // Set the callee in the CallExpr.
3350   // FIXME: This loses syntactic information.
3351   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3352   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3353                                               CK_BuiltinFnToFnPtr);
3354   TheCall->setCallee(PromotedCall.get());
3355 
3356   // Change the result type of the call to match the original value type. This
3357   // is arbitrary, but the codegen for these builtins ins design to handle it
3358   // gracefully.
3359   TheCall->setType(ResultType);
3360 
3361   return TheCallResult;
3362 }
3363 
3364 /// SemaBuiltinNontemporalOverloaded - We have a call to
3365 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3366 /// overloaded function based on the pointer type of its last argument.
3367 ///
3368 /// This function goes through and does final semantic checking for these
3369 /// builtins.
3370 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3371   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3372   DeclRefExpr *DRE =
3373       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3374   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3375   unsigned BuiltinID = FDecl->getBuiltinID();
3376   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3377           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3378          "Unexpected nontemporal load/store builtin!");
3379   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3380   unsigned numArgs = isStore ? 2 : 1;
3381 
3382   // Ensure that we have the proper number of arguments.
3383   if (checkArgCount(*this, TheCall, numArgs))
3384     return ExprError();
3385 
3386   // Inspect the last argument of the nontemporal builtin.  This should always
3387   // be a pointer type, from which we imply the type of the memory access.
3388   // Because it is a pointer type, we don't have to worry about any implicit
3389   // casts here.
3390   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3391   ExprResult PointerArgResult =
3392       DefaultFunctionArrayLvalueConversion(PointerArg);
3393 
3394   if (PointerArgResult.isInvalid())
3395     return ExprError();
3396   PointerArg = PointerArgResult.get();
3397   TheCall->setArg(numArgs - 1, PointerArg);
3398 
3399   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3400   if (!pointerType) {
3401     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3402         << PointerArg->getType() << PointerArg->getSourceRange();
3403     return ExprError();
3404   }
3405 
3406   QualType ValType = pointerType->getPointeeType();
3407 
3408   // Strip any qualifiers off ValType.
3409   ValType = ValType.getUnqualifiedType();
3410   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3411       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3412       !ValType->isVectorType()) {
3413     Diag(DRE->getLocStart(),
3414          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3415         << PointerArg->getType() << PointerArg->getSourceRange();
3416     return ExprError();
3417   }
3418 
3419   if (!isStore) {
3420     TheCall->setType(ValType);
3421     return TheCallResult;
3422   }
3423 
3424   ExprResult ValArg = TheCall->getArg(0);
3425   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3426       Context, ValType, /*consume*/ false);
3427   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3428   if (ValArg.isInvalid())
3429     return ExprError();
3430 
3431   TheCall->setArg(0, ValArg.get());
3432   TheCall->setType(Context.VoidTy);
3433   return TheCallResult;
3434 }
3435 
3436 /// CheckObjCString - Checks that the argument to the builtin
3437 /// CFString constructor is correct
3438 /// Note: It might also make sense to do the UTF-16 conversion here (would
3439 /// simplify the backend).
3440 bool Sema::CheckObjCString(Expr *Arg) {
3441   Arg = Arg->IgnoreParenCasts();
3442   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3443 
3444   if (!Literal || !Literal->isAscii()) {
3445     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3446       << Arg->getSourceRange();
3447     return true;
3448   }
3449 
3450   if (Literal->containsNonAsciiOrNull()) {
3451     StringRef String = Literal->getString();
3452     unsigned NumBytes = String.size();
3453     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3454     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3455     llvm::UTF16 *ToPtr = &ToBuf[0];
3456 
3457     llvm::ConversionResult Result =
3458         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3459                                  ToPtr + NumBytes, llvm::strictConversion);
3460     // Check for conversion failure.
3461     if (Result != llvm::conversionOK)
3462       Diag(Arg->getLocStart(),
3463            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3464   }
3465   return false;
3466 }
3467 
3468 /// CheckObjCString - Checks that the format string argument to the os_log()
3469 /// and os_trace() functions is correct, and converts it to const char *.
3470 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3471   Arg = Arg->IgnoreParenCasts();
3472   auto *Literal = dyn_cast<StringLiteral>(Arg);
3473   if (!Literal) {
3474     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3475       Literal = ObjcLiteral->getString();
3476     }
3477   }
3478 
3479   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3480     return ExprError(
3481         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3482         << Arg->getSourceRange());
3483   }
3484 
3485   ExprResult Result(Literal);
3486   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3487   InitializedEntity Entity =
3488       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3489   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3490   return Result;
3491 }
3492 
3493 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3494 /// for validity.  Emit an error and return true on failure; return false
3495 /// on success.
3496 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3497   Expr *Fn = TheCall->getCallee();
3498   if (TheCall->getNumArgs() > 2) {
3499     Diag(TheCall->getArg(2)->getLocStart(),
3500          diag::err_typecheck_call_too_many_args)
3501       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3502       << Fn->getSourceRange()
3503       << SourceRange(TheCall->getArg(2)->getLocStart(),
3504                      (*(TheCall->arg_end()-1))->getLocEnd());
3505     return true;
3506   }
3507 
3508   if (TheCall->getNumArgs() < 2) {
3509     return Diag(TheCall->getLocEnd(),
3510       diag::err_typecheck_call_too_few_args_at_least)
3511       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3512   }
3513 
3514   // Type-check the first argument normally.
3515   if (checkBuiltinArgument(*this, TheCall, 0))
3516     return true;
3517 
3518   // Determine whether the current function is variadic or not.
3519   BlockScopeInfo *CurBlock = getCurBlock();
3520   bool isVariadic;
3521   if (CurBlock)
3522     isVariadic = CurBlock->TheDecl->isVariadic();
3523   else if (FunctionDecl *FD = getCurFunctionDecl())
3524     isVariadic = FD->isVariadic();
3525   else
3526     isVariadic = getCurMethodDecl()->isVariadic();
3527 
3528   if (!isVariadic) {
3529     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3530     return true;
3531   }
3532 
3533   // Verify that the second argument to the builtin is the last argument of the
3534   // current function or method.
3535   bool SecondArgIsLastNamedArgument = false;
3536   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3537 
3538   // These are valid if SecondArgIsLastNamedArgument is false after the next
3539   // block.
3540   QualType Type;
3541   SourceLocation ParamLoc;
3542   bool IsCRegister = false;
3543 
3544   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3545     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3546       // FIXME: This isn't correct for methods (results in bogus warning).
3547       // Get the last formal in the current function.
3548       const ParmVarDecl *LastArg;
3549       if (CurBlock)
3550         LastArg = CurBlock->TheDecl->parameters().back();
3551       else if (FunctionDecl *FD = getCurFunctionDecl())
3552         LastArg = FD->parameters().back();
3553       else
3554         LastArg = getCurMethodDecl()->parameters().back();
3555       SecondArgIsLastNamedArgument = PV == LastArg;
3556 
3557       Type = PV->getType();
3558       ParamLoc = PV->getLocation();
3559       IsCRegister =
3560           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3561     }
3562   }
3563 
3564   if (!SecondArgIsLastNamedArgument)
3565     Diag(TheCall->getArg(1)->getLocStart(),
3566          diag::warn_second_arg_of_va_start_not_last_named_param);
3567   else if (IsCRegister || Type->isReferenceType() ||
3568            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3569              // Promotable integers are UB, but enumerations need a bit of
3570              // extra checking to see what their promotable type actually is.
3571              if (!Type->isPromotableIntegerType())
3572                return false;
3573              if (!Type->isEnumeralType())
3574                return true;
3575              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3576              return !(ED &&
3577                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3578            }()) {
3579     unsigned Reason = 0;
3580     if (Type->isReferenceType())  Reason = 1;
3581     else if (IsCRegister)         Reason = 2;
3582     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3583     Diag(ParamLoc, diag::note_parameter_type) << Type;
3584   }
3585 
3586   TheCall->setType(Context.VoidTy);
3587   return false;
3588 }
3589 
3590 /// Check the arguments to '__builtin_va_start' for validity, and that
3591 /// it was called from a function of the native ABI.
3592 /// Emit an error and return true on failure; return false on success.
3593 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3594   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3595   // On x64 Windows, don't allow this in System V ABI functions.
3596   // (Yes, that means there's no corresponding way to support variadic
3597   // System V ABI functions on Windows.)
3598   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3599     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3600     clang::CallingConv CC = CC_C;
3601     if (const FunctionDecl *FD = getCurFunctionDecl())
3602       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3603     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3604         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3605       return Diag(TheCall->getCallee()->getLocStart(),
3606                   diag::err_va_start_used_in_wrong_abi_function)
3607              << (OS != llvm::Triple::Win32);
3608   }
3609   return SemaBuiltinVAStartImpl(TheCall);
3610 }
3611 
3612 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3613 /// it was called from a Win64 ABI function.
3614 /// Emit an error and return true on failure; return false on success.
3615 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3616   // This only makes sense for x86-64.
3617   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3618   Expr *Callee = TheCall->getCallee();
3619   if (TT.getArch() != llvm::Triple::x86_64)
3620     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3621   // Don't allow this in System V ABI functions.
3622   clang::CallingConv CC = CC_C;
3623   if (const FunctionDecl *FD = getCurFunctionDecl())
3624     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3625   if (CC == CC_X86_64SysV ||
3626       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3627     return Diag(Callee->getLocStart(),
3628                 diag::err_ms_va_start_used_in_sysv_function);
3629   return SemaBuiltinVAStartImpl(TheCall);
3630 }
3631 
3632 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3633   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3634   //                 const char *named_addr);
3635 
3636   Expr *Func = Call->getCallee();
3637 
3638   if (Call->getNumArgs() < 3)
3639     return Diag(Call->getLocEnd(),
3640                 diag::err_typecheck_call_too_few_args_at_least)
3641            << 0 /*function call*/ << 3 << Call->getNumArgs();
3642 
3643   // Determine whether the current function is variadic or not.
3644   bool IsVariadic;
3645   if (BlockScopeInfo *CurBlock = getCurBlock())
3646     IsVariadic = CurBlock->TheDecl->isVariadic();
3647   else if (FunctionDecl *FD = getCurFunctionDecl())
3648     IsVariadic = FD->isVariadic();
3649   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3650     IsVariadic = MD->isVariadic();
3651   else
3652     llvm_unreachable("unexpected statement type");
3653 
3654   if (!IsVariadic) {
3655     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3656     return true;
3657   }
3658 
3659   // Type-check the first argument normally.
3660   if (checkBuiltinArgument(*this, Call, 0))
3661     return true;
3662 
3663   const struct {
3664     unsigned ArgNo;
3665     QualType Type;
3666   } ArgumentTypes[] = {
3667     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3668     { 2, Context.getSizeType() },
3669   };
3670 
3671   for (const auto &AT : ArgumentTypes) {
3672     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3673     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3674       continue;
3675     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3676       << Arg->getType() << AT.Type << 1 /* different class */
3677       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3678       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3679   }
3680 
3681   return false;
3682 }
3683 
3684 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3685 /// friends.  This is declared to take (...), so we have to check everything.
3686 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3687   if (TheCall->getNumArgs() < 2)
3688     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3689       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3690   if (TheCall->getNumArgs() > 2)
3691     return Diag(TheCall->getArg(2)->getLocStart(),
3692                 diag::err_typecheck_call_too_many_args)
3693       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3694       << SourceRange(TheCall->getArg(2)->getLocStart(),
3695                      (*(TheCall->arg_end()-1))->getLocEnd());
3696 
3697   ExprResult OrigArg0 = TheCall->getArg(0);
3698   ExprResult OrigArg1 = TheCall->getArg(1);
3699 
3700   // Do standard promotions between the two arguments, returning their common
3701   // type.
3702   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3703   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3704     return true;
3705 
3706   // Make sure any conversions are pushed back into the call; this is
3707   // type safe since unordered compare builtins are declared as "_Bool
3708   // foo(...)".
3709   TheCall->setArg(0, OrigArg0.get());
3710   TheCall->setArg(1, OrigArg1.get());
3711 
3712   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3713     return false;
3714 
3715   // If the common type isn't a real floating type, then the arguments were
3716   // invalid for this operation.
3717   if (Res.isNull() || !Res->isRealFloatingType())
3718     return Diag(OrigArg0.get()->getLocStart(),
3719                 diag::err_typecheck_call_invalid_ordered_compare)
3720       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3721       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3722 
3723   return false;
3724 }
3725 
3726 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3727 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3728 /// to check everything. We expect the last argument to be a floating point
3729 /// value.
3730 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3731   if (TheCall->getNumArgs() < NumArgs)
3732     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3733       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3734   if (TheCall->getNumArgs() > NumArgs)
3735     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3736                 diag::err_typecheck_call_too_many_args)
3737       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3738       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3739                      (*(TheCall->arg_end()-1))->getLocEnd());
3740 
3741   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3742 
3743   if (OrigArg->isTypeDependent())
3744     return false;
3745 
3746   // This operation requires a non-_Complex floating-point number.
3747   if (!OrigArg->getType()->isRealFloatingType())
3748     return Diag(OrigArg->getLocStart(),
3749                 diag::err_typecheck_call_invalid_unary_fp)
3750       << OrigArg->getType() << OrigArg->getSourceRange();
3751 
3752   // If this is an implicit conversion from float -> double, remove it.
3753   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3754     Expr *CastArg = Cast->getSubExpr();
3755     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3756       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3757              "promotion from float to double is the only expected cast here");
3758       Cast->setSubExpr(nullptr);
3759       TheCall->setArg(NumArgs-1, CastArg);
3760     }
3761   }
3762 
3763   return false;
3764 }
3765 
3766 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3767 // This is declared to take (...), so we have to check everything.
3768 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3769   if (TheCall->getNumArgs() < 2)
3770     return ExprError(Diag(TheCall->getLocEnd(),
3771                           diag::err_typecheck_call_too_few_args_at_least)
3772                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3773                      << TheCall->getSourceRange());
3774 
3775   // Determine which of the following types of shufflevector we're checking:
3776   // 1) unary, vector mask: (lhs, mask)
3777   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3778   QualType resType = TheCall->getArg(0)->getType();
3779   unsigned numElements = 0;
3780 
3781   if (!TheCall->getArg(0)->isTypeDependent() &&
3782       !TheCall->getArg(1)->isTypeDependent()) {
3783     QualType LHSType = TheCall->getArg(0)->getType();
3784     QualType RHSType = TheCall->getArg(1)->getType();
3785 
3786     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3787       return ExprError(Diag(TheCall->getLocStart(),
3788                             diag::err_shufflevector_non_vector)
3789                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3790                                       TheCall->getArg(1)->getLocEnd()));
3791 
3792     numElements = LHSType->getAs<VectorType>()->getNumElements();
3793     unsigned numResElements = TheCall->getNumArgs() - 2;
3794 
3795     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3796     // with mask.  If so, verify that RHS is an integer vector type with the
3797     // same number of elts as lhs.
3798     if (TheCall->getNumArgs() == 2) {
3799       if (!RHSType->hasIntegerRepresentation() ||
3800           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3801         return ExprError(Diag(TheCall->getLocStart(),
3802                               diag::err_shufflevector_incompatible_vector)
3803                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3804                                         TheCall->getArg(1)->getLocEnd()));
3805     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3806       return ExprError(Diag(TheCall->getLocStart(),
3807                             diag::err_shufflevector_incompatible_vector)
3808                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3809                                       TheCall->getArg(1)->getLocEnd()));
3810     } else if (numElements != numResElements) {
3811       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3812       resType = Context.getVectorType(eltType, numResElements,
3813                                       VectorType::GenericVector);
3814     }
3815   }
3816 
3817   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3818     if (TheCall->getArg(i)->isTypeDependent() ||
3819         TheCall->getArg(i)->isValueDependent())
3820       continue;
3821 
3822     llvm::APSInt Result(32);
3823     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3824       return ExprError(Diag(TheCall->getLocStart(),
3825                             diag::err_shufflevector_nonconstant_argument)
3826                        << TheCall->getArg(i)->getSourceRange());
3827 
3828     // Allow -1 which will be translated to undef in the IR.
3829     if (Result.isSigned() && Result.isAllOnesValue())
3830       continue;
3831 
3832     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3833       return ExprError(Diag(TheCall->getLocStart(),
3834                             diag::err_shufflevector_argument_too_large)
3835                        << TheCall->getArg(i)->getSourceRange());
3836   }
3837 
3838   SmallVector<Expr*, 32> exprs;
3839 
3840   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3841     exprs.push_back(TheCall->getArg(i));
3842     TheCall->setArg(i, nullptr);
3843   }
3844 
3845   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3846                                          TheCall->getCallee()->getLocStart(),
3847                                          TheCall->getRParenLoc());
3848 }
3849 
3850 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3851 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3852                                        SourceLocation BuiltinLoc,
3853                                        SourceLocation RParenLoc) {
3854   ExprValueKind VK = VK_RValue;
3855   ExprObjectKind OK = OK_Ordinary;
3856   QualType DstTy = TInfo->getType();
3857   QualType SrcTy = E->getType();
3858 
3859   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3860     return ExprError(Diag(BuiltinLoc,
3861                           diag::err_convertvector_non_vector)
3862                      << E->getSourceRange());
3863   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3864     return ExprError(Diag(BuiltinLoc,
3865                           diag::err_convertvector_non_vector_type));
3866 
3867   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3868     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3869     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3870     if (SrcElts != DstElts)
3871       return ExprError(Diag(BuiltinLoc,
3872                             diag::err_convertvector_incompatible_vector)
3873                        << E->getSourceRange());
3874   }
3875 
3876   return new (Context)
3877       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3878 }
3879 
3880 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3881 // This is declared to take (const void*, ...) and can take two
3882 // optional constant int args.
3883 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3884   unsigned NumArgs = TheCall->getNumArgs();
3885 
3886   if (NumArgs > 3)
3887     return Diag(TheCall->getLocEnd(),
3888              diag::err_typecheck_call_too_many_args_at_most)
3889              << 0 /*function call*/ << 3 << NumArgs
3890              << TheCall->getSourceRange();
3891 
3892   // Argument 0 is checked for us and the remaining arguments must be
3893   // constant integers.
3894   for (unsigned i = 1; i != NumArgs; ++i)
3895     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3896       return true;
3897 
3898   return false;
3899 }
3900 
3901 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3902 // __assume does not evaluate its arguments, and should warn if its argument
3903 // has side effects.
3904 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3905   Expr *Arg = TheCall->getArg(0);
3906   if (Arg->isInstantiationDependent()) return false;
3907 
3908   if (Arg->HasSideEffects(Context))
3909     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3910       << Arg->getSourceRange()
3911       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3912 
3913   return false;
3914 }
3915 
3916 /// Handle __builtin_alloca_with_align. This is declared
3917 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3918 /// than 8.
3919 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3920   // The alignment must be a constant integer.
3921   Expr *Arg = TheCall->getArg(1);
3922 
3923   // We can't check the value of a dependent argument.
3924   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3925     if (const auto *UE =
3926             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3927       if (UE->getKind() == UETT_AlignOf)
3928         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3929           << Arg->getSourceRange();
3930 
3931     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3932 
3933     if (!Result.isPowerOf2())
3934       return Diag(TheCall->getLocStart(),
3935                   diag::err_alignment_not_power_of_two)
3936            << Arg->getSourceRange();
3937 
3938     if (Result < Context.getCharWidth())
3939       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3940            << (unsigned)Context.getCharWidth()
3941            << Arg->getSourceRange();
3942 
3943     if (Result > INT32_MAX)
3944       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3945            << INT32_MAX
3946            << Arg->getSourceRange();
3947   }
3948 
3949   return false;
3950 }
3951 
3952 /// Handle __builtin_assume_aligned. This is declared
3953 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3954 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3955   unsigned NumArgs = TheCall->getNumArgs();
3956 
3957   if (NumArgs > 3)
3958     return Diag(TheCall->getLocEnd(),
3959              diag::err_typecheck_call_too_many_args_at_most)
3960              << 0 /*function call*/ << 3 << NumArgs
3961              << TheCall->getSourceRange();
3962 
3963   // The alignment must be a constant integer.
3964   Expr *Arg = TheCall->getArg(1);
3965 
3966   // We can't check the value of a dependent argument.
3967   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3968     llvm::APSInt Result;
3969     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3970       return true;
3971 
3972     if (!Result.isPowerOf2())
3973       return Diag(TheCall->getLocStart(),
3974                   diag::err_alignment_not_power_of_two)
3975            << Arg->getSourceRange();
3976   }
3977 
3978   if (NumArgs > 2) {
3979     ExprResult Arg(TheCall->getArg(2));
3980     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3981       Context.getSizeType(), false);
3982     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3983     if (Arg.isInvalid()) return true;
3984     TheCall->setArg(2, Arg.get());
3985   }
3986 
3987   return false;
3988 }
3989 
3990 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3991   unsigned BuiltinID =
3992       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3993   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3994 
3995   unsigned NumArgs = TheCall->getNumArgs();
3996   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
3997   if (NumArgs < NumRequiredArgs) {
3998     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3999            << 0 /* function call */ << NumRequiredArgs << NumArgs
4000            << TheCall->getSourceRange();
4001   }
4002   if (NumArgs >= NumRequiredArgs + 0x100) {
4003     return Diag(TheCall->getLocEnd(),
4004                 diag::err_typecheck_call_too_many_args_at_most)
4005            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4006            << TheCall->getSourceRange();
4007   }
4008   unsigned i = 0;
4009 
4010   // For formatting call, check buffer arg.
4011   if (!IsSizeCall) {
4012     ExprResult Arg(TheCall->getArg(i));
4013     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4014         Context, Context.VoidPtrTy, false);
4015     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4016     if (Arg.isInvalid())
4017       return true;
4018     TheCall->setArg(i, Arg.get());
4019     i++;
4020   }
4021 
4022   // Check string literal arg.
4023   unsigned FormatIdx = i;
4024   {
4025     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4026     if (Arg.isInvalid())
4027       return true;
4028     TheCall->setArg(i, Arg.get());
4029     i++;
4030   }
4031 
4032   // Make sure variadic args are scalar.
4033   unsigned FirstDataArg = i;
4034   while (i < NumArgs) {
4035     ExprResult Arg = DefaultVariadicArgumentPromotion(
4036         TheCall->getArg(i), VariadicFunction, nullptr);
4037     if (Arg.isInvalid())
4038       return true;
4039     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4040     if (ArgSize.getQuantity() >= 0x100) {
4041       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4042              << i << (int)ArgSize.getQuantity() << 0xff
4043              << TheCall->getSourceRange();
4044     }
4045     TheCall->setArg(i, Arg.get());
4046     i++;
4047   }
4048 
4049   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4050   // call to avoid duplicate diagnostics.
4051   if (!IsSizeCall) {
4052     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4053     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4054     bool Success = CheckFormatArguments(
4055         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4056         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4057         CheckedVarArgs);
4058     if (!Success)
4059       return true;
4060   }
4061 
4062   if (IsSizeCall) {
4063     TheCall->setType(Context.getSizeType());
4064   } else {
4065     TheCall->setType(Context.VoidPtrTy);
4066   }
4067   return false;
4068 }
4069 
4070 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4071 /// TheCall is a constant expression.
4072 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4073                                   llvm::APSInt &Result) {
4074   Expr *Arg = TheCall->getArg(ArgNum);
4075   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4076   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4077 
4078   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4079 
4080   if (!Arg->isIntegerConstantExpr(Result, Context))
4081     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4082                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4083 
4084   return false;
4085 }
4086 
4087 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4088 /// TheCall is a constant expression in the range [Low, High].
4089 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4090                                        int Low, int High) {
4091   llvm::APSInt Result;
4092 
4093   // We can't check the value of a dependent argument.
4094   Expr *Arg = TheCall->getArg(ArgNum);
4095   if (Arg->isTypeDependent() || Arg->isValueDependent())
4096     return false;
4097 
4098   // Check constant-ness first.
4099   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4100     return true;
4101 
4102   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4103     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4104       << Low << High << Arg->getSourceRange();
4105 
4106   return false;
4107 }
4108 
4109 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4110 /// TheCall is a constant expression is a multiple of Num..
4111 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4112                                           unsigned Num) {
4113   llvm::APSInt Result;
4114 
4115   // We can't check the value of a dependent argument.
4116   Expr *Arg = TheCall->getArg(ArgNum);
4117   if (Arg->isTypeDependent() || Arg->isValueDependent())
4118     return false;
4119 
4120   // Check constant-ness first.
4121   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4122     return true;
4123 
4124   if (Result.getSExtValue() % Num != 0)
4125     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4126       << Num << Arg->getSourceRange();
4127 
4128   return false;
4129 }
4130 
4131 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4132 /// TheCall is an ARM/AArch64 special register string literal.
4133 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4134                                     int ArgNum, unsigned ExpectedFieldNum,
4135                                     bool AllowName) {
4136   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4137                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4138                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4139                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4140                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4141                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4142   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4143                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4144                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4145                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4146                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4147                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4148   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4149 
4150   // We can't check the value of a dependent argument.
4151   Expr *Arg = TheCall->getArg(ArgNum);
4152   if (Arg->isTypeDependent() || Arg->isValueDependent())
4153     return false;
4154 
4155   // Check if the argument is a string literal.
4156   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4157     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4158            << Arg->getSourceRange();
4159 
4160   // Check the type of special register given.
4161   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4162   SmallVector<StringRef, 6> Fields;
4163   Reg.split(Fields, ":");
4164 
4165   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4166     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4167            << Arg->getSourceRange();
4168 
4169   // If the string is the name of a register then we cannot check that it is
4170   // valid here but if the string is of one the forms described in ACLE then we
4171   // can check that the supplied fields are integers and within the valid
4172   // ranges.
4173   if (Fields.size() > 1) {
4174     bool FiveFields = Fields.size() == 5;
4175 
4176     bool ValidString = true;
4177     if (IsARMBuiltin) {
4178       ValidString &= Fields[0].startswith_lower("cp") ||
4179                      Fields[0].startswith_lower("p");
4180       if (ValidString)
4181         Fields[0] =
4182           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4183 
4184       ValidString &= Fields[2].startswith_lower("c");
4185       if (ValidString)
4186         Fields[2] = Fields[2].drop_front(1);
4187 
4188       if (FiveFields) {
4189         ValidString &= Fields[3].startswith_lower("c");
4190         if (ValidString)
4191           Fields[3] = Fields[3].drop_front(1);
4192       }
4193     }
4194 
4195     SmallVector<int, 5> Ranges;
4196     if (FiveFields)
4197       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
4198     else
4199       Ranges.append({15, 7, 15});
4200 
4201     for (unsigned i=0; i<Fields.size(); ++i) {
4202       int IntField;
4203       ValidString &= !Fields[i].getAsInteger(10, IntField);
4204       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4205     }
4206 
4207     if (!ValidString)
4208       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4209              << Arg->getSourceRange();
4210 
4211   } else if (IsAArch64Builtin && Fields.size() == 1) {
4212     // If the register name is one of those that appear in the condition below
4213     // and the special register builtin being used is one of the write builtins,
4214     // then we require that the argument provided for writing to the register
4215     // is an integer constant expression. This is because it will be lowered to
4216     // an MSR (immediate) instruction, so we need to know the immediate at
4217     // compile time.
4218     if (TheCall->getNumArgs() != 2)
4219       return false;
4220 
4221     std::string RegLower = Reg.lower();
4222     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4223         RegLower != "pan" && RegLower != "uao")
4224       return false;
4225 
4226     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4227   }
4228 
4229   return false;
4230 }
4231 
4232 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4233 /// This checks that the target supports __builtin_longjmp and
4234 /// that val is a constant 1.
4235 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4236   if (!Context.getTargetInfo().hasSjLjLowering())
4237     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4238              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4239 
4240   Expr *Arg = TheCall->getArg(1);
4241   llvm::APSInt Result;
4242 
4243   // TODO: This is less than ideal. Overload this to take a value.
4244   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4245     return true;
4246 
4247   if (Result != 1)
4248     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4249              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4250 
4251   return false;
4252 }
4253 
4254 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4255 /// This checks that the target supports __builtin_setjmp.
4256 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4257   if (!Context.getTargetInfo().hasSjLjLowering())
4258     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4259              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4260   return false;
4261 }
4262 
4263 namespace {
4264 class UncoveredArgHandler {
4265   enum { Unknown = -1, AllCovered = -2 };
4266   signed FirstUncoveredArg;
4267   SmallVector<const Expr *, 4> DiagnosticExprs;
4268 
4269 public:
4270   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4271 
4272   bool hasUncoveredArg() const {
4273     return (FirstUncoveredArg >= 0);
4274   }
4275 
4276   unsigned getUncoveredArg() const {
4277     assert(hasUncoveredArg() && "no uncovered argument");
4278     return FirstUncoveredArg;
4279   }
4280 
4281   void setAllCovered() {
4282     // A string has been found with all arguments covered, so clear out
4283     // the diagnostics.
4284     DiagnosticExprs.clear();
4285     FirstUncoveredArg = AllCovered;
4286   }
4287 
4288   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4289     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4290 
4291     // Don't update if a previous string covers all arguments.
4292     if (FirstUncoveredArg == AllCovered)
4293       return;
4294 
4295     // UncoveredArgHandler tracks the highest uncovered argument index
4296     // and with it all the strings that match this index.
4297     if (NewFirstUncoveredArg == FirstUncoveredArg)
4298       DiagnosticExprs.push_back(StrExpr);
4299     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4300       DiagnosticExprs.clear();
4301       DiagnosticExprs.push_back(StrExpr);
4302       FirstUncoveredArg = NewFirstUncoveredArg;
4303     }
4304   }
4305 
4306   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4307 };
4308 
4309 enum StringLiteralCheckType {
4310   SLCT_NotALiteral,
4311   SLCT_UncheckedLiteral,
4312   SLCT_CheckedLiteral
4313 };
4314 } // end anonymous namespace
4315 
4316 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4317                                      BinaryOperatorKind BinOpKind,
4318                                      bool AddendIsRight) {
4319   unsigned BitWidth = Offset.getBitWidth();
4320   unsigned AddendBitWidth = Addend.getBitWidth();
4321   // There might be negative interim results.
4322   if (Addend.isUnsigned()) {
4323     Addend = Addend.zext(++AddendBitWidth);
4324     Addend.setIsSigned(true);
4325   }
4326   // Adjust the bit width of the APSInts.
4327   if (AddendBitWidth > BitWidth) {
4328     Offset = Offset.sext(AddendBitWidth);
4329     BitWidth = AddendBitWidth;
4330   } else if (BitWidth > AddendBitWidth) {
4331     Addend = Addend.sext(BitWidth);
4332   }
4333 
4334   bool Ov = false;
4335   llvm::APSInt ResOffset = Offset;
4336   if (BinOpKind == BO_Add)
4337     ResOffset = Offset.sadd_ov(Addend, Ov);
4338   else {
4339     assert(AddendIsRight && BinOpKind == BO_Sub &&
4340            "operator must be add or sub with addend on the right");
4341     ResOffset = Offset.ssub_ov(Addend, Ov);
4342   }
4343 
4344   // We add an offset to a pointer here so we should support an offset as big as
4345   // possible.
4346   if (Ov) {
4347     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4348     Offset = Offset.sext(2 * BitWidth);
4349     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4350     return;
4351   }
4352 
4353   Offset = ResOffset;
4354 }
4355 
4356 namespace {
4357 // This is a wrapper class around StringLiteral to support offsetted string
4358 // literals as format strings. It takes the offset into account when returning
4359 // the string and its length or the source locations to display notes correctly.
4360 class FormatStringLiteral {
4361   const StringLiteral *FExpr;
4362   int64_t Offset;
4363 
4364  public:
4365   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4366       : FExpr(fexpr), Offset(Offset) {}
4367 
4368   StringRef getString() const {
4369     return FExpr->getString().drop_front(Offset);
4370   }
4371 
4372   unsigned getByteLength() const {
4373     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4374   }
4375   unsigned getLength() const { return FExpr->getLength() - Offset; }
4376   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4377 
4378   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4379 
4380   QualType getType() const { return FExpr->getType(); }
4381 
4382   bool isAscii() const { return FExpr->isAscii(); }
4383   bool isWide() const { return FExpr->isWide(); }
4384   bool isUTF8() const { return FExpr->isUTF8(); }
4385   bool isUTF16() const { return FExpr->isUTF16(); }
4386   bool isUTF32() const { return FExpr->isUTF32(); }
4387   bool isPascal() const { return FExpr->isPascal(); }
4388 
4389   SourceLocation getLocationOfByte(
4390       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4391       const TargetInfo &Target, unsigned *StartToken = nullptr,
4392       unsigned *StartTokenByteOffset = nullptr) const {
4393     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4394                                     StartToken, StartTokenByteOffset);
4395   }
4396 
4397   SourceLocation getLocStart() const LLVM_READONLY {
4398     return FExpr->getLocStart().getLocWithOffset(Offset);
4399   }
4400   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4401 };
4402 }  // end anonymous namespace
4403 
4404 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4405                               const Expr *OrigFormatExpr,
4406                               ArrayRef<const Expr *> Args,
4407                               bool HasVAListArg, unsigned format_idx,
4408                               unsigned firstDataArg,
4409                               Sema::FormatStringType Type,
4410                               bool inFunctionCall,
4411                               Sema::VariadicCallType CallType,
4412                               llvm::SmallBitVector &CheckedVarArgs,
4413                               UncoveredArgHandler &UncoveredArg);
4414 
4415 // Determine if an expression is a string literal or constant string.
4416 // If this function returns false on the arguments to a function expecting a
4417 // format string, we will usually need to emit a warning.
4418 // True string literals are then checked by CheckFormatString.
4419 static StringLiteralCheckType
4420 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4421                       bool HasVAListArg, unsigned format_idx,
4422                       unsigned firstDataArg, Sema::FormatStringType Type,
4423                       Sema::VariadicCallType CallType, bool InFunctionCall,
4424                       llvm::SmallBitVector &CheckedVarArgs,
4425                       UncoveredArgHandler &UncoveredArg,
4426                       llvm::APSInt Offset) {
4427  tryAgain:
4428   assert(Offset.isSigned() && "invalid offset");
4429 
4430   if (E->isTypeDependent() || E->isValueDependent())
4431     return SLCT_NotALiteral;
4432 
4433   E = E->IgnoreParenCasts();
4434 
4435   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4436     // Technically -Wformat-nonliteral does not warn about this case.
4437     // The behavior of printf and friends in this case is implementation
4438     // dependent.  Ideally if the format string cannot be null then
4439     // it should have a 'nonnull' attribute in the function prototype.
4440     return SLCT_UncheckedLiteral;
4441 
4442   switch (E->getStmtClass()) {
4443   case Stmt::BinaryConditionalOperatorClass:
4444   case Stmt::ConditionalOperatorClass: {
4445     // The expression is a literal if both sub-expressions were, and it was
4446     // completely checked only if both sub-expressions were checked.
4447     const AbstractConditionalOperator *C =
4448         cast<AbstractConditionalOperator>(E);
4449 
4450     // Determine whether it is necessary to check both sub-expressions, for
4451     // example, because the condition expression is a constant that can be
4452     // evaluated at compile time.
4453     bool CheckLeft = true, CheckRight = true;
4454 
4455     bool Cond;
4456     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4457       if (Cond)
4458         CheckRight = false;
4459       else
4460         CheckLeft = false;
4461     }
4462 
4463     // We need to maintain the offsets for the right and the left hand side
4464     // separately to check if every possible indexed expression is a valid
4465     // string literal. They might have different offsets for different string
4466     // literals in the end.
4467     StringLiteralCheckType Left;
4468     if (!CheckLeft)
4469       Left = SLCT_UncheckedLiteral;
4470     else {
4471       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4472                                    HasVAListArg, format_idx, firstDataArg,
4473                                    Type, CallType, InFunctionCall,
4474                                    CheckedVarArgs, UncoveredArg, Offset);
4475       if (Left == SLCT_NotALiteral || !CheckRight) {
4476         return Left;
4477       }
4478     }
4479 
4480     StringLiteralCheckType Right =
4481         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4482                               HasVAListArg, format_idx, firstDataArg,
4483                               Type, CallType, InFunctionCall, CheckedVarArgs,
4484                               UncoveredArg, Offset);
4485 
4486     return (CheckLeft && Left < Right) ? Left : Right;
4487   }
4488 
4489   case Stmt::ImplicitCastExprClass: {
4490     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4491     goto tryAgain;
4492   }
4493 
4494   case Stmt::OpaqueValueExprClass:
4495     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4496       E = src;
4497       goto tryAgain;
4498     }
4499     return SLCT_NotALiteral;
4500 
4501   case Stmt::PredefinedExprClass:
4502     // While __func__, etc., are technically not string literals, they
4503     // cannot contain format specifiers and thus are not a security
4504     // liability.
4505     return SLCT_UncheckedLiteral;
4506 
4507   case Stmt::DeclRefExprClass: {
4508     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4509 
4510     // As an exception, do not flag errors for variables binding to
4511     // const string literals.
4512     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4513       bool isConstant = false;
4514       QualType T = DR->getType();
4515 
4516       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4517         isConstant = AT->getElementType().isConstant(S.Context);
4518       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4519         isConstant = T.isConstant(S.Context) &&
4520                      PT->getPointeeType().isConstant(S.Context);
4521       } else if (T->isObjCObjectPointerType()) {
4522         // In ObjC, there is usually no "const ObjectPointer" type,
4523         // so don't check if the pointee type is constant.
4524         isConstant = T.isConstant(S.Context);
4525       }
4526 
4527       if (isConstant) {
4528         if (const Expr *Init = VD->getAnyInitializer()) {
4529           // Look through initializers like const char c[] = { "foo" }
4530           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4531             if (InitList->isStringLiteralInit())
4532               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4533           }
4534           return checkFormatStringExpr(S, Init, Args,
4535                                        HasVAListArg, format_idx,
4536                                        firstDataArg, Type, CallType,
4537                                        /*InFunctionCall*/ false, CheckedVarArgs,
4538                                        UncoveredArg, Offset);
4539         }
4540       }
4541 
4542       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4543       // special check to see if the format string is a function parameter
4544       // of the function calling the printf function.  If the function
4545       // has an attribute indicating it is a printf-like function, then we
4546       // should suppress warnings concerning non-literals being used in a call
4547       // to a vprintf function.  For example:
4548       //
4549       // void
4550       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4551       //      va_list ap;
4552       //      va_start(ap, fmt);
4553       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4554       //      ...
4555       // }
4556       if (HasVAListArg) {
4557         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4558           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4559             int PVIndex = PV->getFunctionScopeIndex() + 1;
4560             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4561               // adjust for implicit parameter
4562               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4563                 if (MD->isInstance())
4564                   ++PVIndex;
4565               // We also check if the formats are compatible.
4566               // We can't pass a 'scanf' string to a 'printf' function.
4567               if (PVIndex == PVFormat->getFormatIdx() &&
4568                   Type == S.GetFormatStringType(PVFormat))
4569                 return SLCT_UncheckedLiteral;
4570             }
4571           }
4572         }
4573       }
4574     }
4575 
4576     return SLCT_NotALiteral;
4577   }
4578 
4579   case Stmt::CallExprClass:
4580   case Stmt::CXXMemberCallExprClass: {
4581     const CallExpr *CE = cast<CallExpr>(E);
4582     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4583       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4584         unsigned ArgIndex = FA->getFormatIdx();
4585         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4586           if (MD->isInstance())
4587             --ArgIndex;
4588         const Expr *Arg = CE->getArg(ArgIndex - 1);
4589 
4590         return checkFormatStringExpr(S, Arg, Args,
4591                                      HasVAListArg, format_idx, firstDataArg,
4592                                      Type, CallType, InFunctionCall,
4593                                      CheckedVarArgs, UncoveredArg, Offset);
4594       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4595         unsigned BuiltinID = FD->getBuiltinID();
4596         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4597             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4598           const Expr *Arg = CE->getArg(0);
4599           return checkFormatStringExpr(S, Arg, Args,
4600                                        HasVAListArg, format_idx,
4601                                        firstDataArg, Type, CallType,
4602                                        InFunctionCall, CheckedVarArgs,
4603                                        UncoveredArg, Offset);
4604         }
4605       }
4606     }
4607 
4608     return SLCT_NotALiteral;
4609   }
4610   case Stmt::ObjCMessageExprClass: {
4611     const auto *ME = cast<ObjCMessageExpr>(E);
4612     if (const auto *ND = ME->getMethodDecl()) {
4613       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4614         unsigned ArgIndex = FA->getFormatIdx();
4615         const Expr *Arg = ME->getArg(ArgIndex - 1);
4616         return checkFormatStringExpr(
4617             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4618             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4619       }
4620     }
4621 
4622     return SLCT_NotALiteral;
4623   }
4624   case Stmt::ObjCStringLiteralClass:
4625   case Stmt::StringLiteralClass: {
4626     const StringLiteral *StrE = nullptr;
4627 
4628     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4629       StrE = ObjCFExpr->getString();
4630     else
4631       StrE = cast<StringLiteral>(E);
4632 
4633     if (StrE) {
4634       if (Offset.isNegative() || Offset > StrE->getLength()) {
4635         // TODO: It would be better to have an explicit warning for out of
4636         // bounds literals.
4637         return SLCT_NotALiteral;
4638       }
4639       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4640       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4641                         firstDataArg, Type, InFunctionCall, CallType,
4642                         CheckedVarArgs, UncoveredArg);
4643       return SLCT_CheckedLiteral;
4644     }
4645 
4646     return SLCT_NotALiteral;
4647   }
4648   case Stmt::BinaryOperatorClass: {
4649     llvm::APSInt LResult;
4650     llvm::APSInt RResult;
4651 
4652     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4653 
4654     // A string literal + an int offset is still a string literal.
4655     if (BinOp->isAdditiveOp()) {
4656       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4657       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4658 
4659       if (LIsInt != RIsInt) {
4660         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4661 
4662         if (LIsInt) {
4663           if (BinOpKind == BO_Add) {
4664             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4665             E = BinOp->getRHS();
4666             goto tryAgain;
4667           }
4668         } else {
4669           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4670           E = BinOp->getLHS();
4671           goto tryAgain;
4672         }
4673       }
4674     }
4675 
4676     return SLCT_NotALiteral;
4677   }
4678   case Stmt::UnaryOperatorClass: {
4679     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4680     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4681     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4682       llvm::APSInt IndexResult;
4683       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4684         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4685         E = ASE->getBase();
4686         goto tryAgain;
4687       }
4688     }
4689 
4690     return SLCT_NotALiteral;
4691   }
4692 
4693   default:
4694     return SLCT_NotALiteral;
4695   }
4696 }
4697 
4698 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4699   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4700       .Case("scanf", FST_Scanf)
4701       .Cases("printf", "printf0", FST_Printf)
4702       .Cases("NSString", "CFString", FST_NSString)
4703       .Case("strftime", FST_Strftime)
4704       .Case("strfmon", FST_Strfmon)
4705       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4706       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4707       .Case("os_trace", FST_OSLog)
4708       .Case("os_log", FST_OSLog)
4709       .Default(FST_Unknown);
4710 }
4711 
4712 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4713 /// functions) for correct use of format strings.
4714 /// Returns true if a format string has been fully checked.
4715 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4716                                 ArrayRef<const Expr *> Args,
4717                                 bool IsCXXMember,
4718                                 VariadicCallType CallType,
4719                                 SourceLocation Loc, SourceRange Range,
4720                                 llvm::SmallBitVector &CheckedVarArgs) {
4721   FormatStringInfo FSI;
4722   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4723     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4724                                 FSI.FirstDataArg, GetFormatStringType(Format),
4725                                 CallType, Loc, Range, CheckedVarArgs);
4726   return false;
4727 }
4728 
4729 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4730                                 bool HasVAListArg, unsigned format_idx,
4731                                 unsigned firstDataArg, FormatStringType Type,
4732                                 VariadicCallType CallType,
4733                                 SourceLocation Loc, SourceRange Range,
4734                                 llvm::SmallBitVector &CheckedVarArgs) {
4735   // CHECK: printf/scanf-like function is called with no format string.
4736   if (format_idx >= Args.size()) {
4737     Diag(Loc, diag::warn_missing_format_string) << Range;
4738     return false;
4739   }
4740 
4741   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4742 
4743   // CHECK: format string is not a string literal.
4744   //
4745   // Dynamically generated format strings are difficult to
4746   // automatically vet at compile time.  Requiring that format strings
4747   // are string literals: (1) permits the checking of format strings by
4748   // the compiler and thereby (2) can practically remove the source of
4749   // many format string exploits.
4750 
4751   // Format string can be either ObjC string (e.g. @"%d") or
4752   // C string (e.g. "%d")
4753   // ObjC string uses the same format specifiers as C string, so we can use
4754   // the same format string checking logic for both ObjC and C strings.
4755   UncoveredArgHandler UncoveredArg;
4756   StringLiteralCheckType CT =
4757       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4758                             format_idx, firstDataArg, Type, CallType,
4759                             /*IsFunctionCall*/ true, CheckedVarArgs,
4760                             UncoveredArg,
4761                             /*no string offset*/ llvm::APSInt(64, false) = 0);
4762 
4763   // Generate a diagnostic where an uncovered argument is detected.
4764   if (UncoveredArg.hasUncoveredArg()) {
4765     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4766     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4767     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4768   }
4769 
4770   if (CT != SLCT_NotALiteral)
4771     // Literal format string found, check done!
4772     return CT == SLCT_CheckedLiteral;
4773 
4774   // Strftime is particular as it always uses a single 'time' argument,
4775   // so it is safe to pass a non-literal string.
4776   if (Type == FST_Strftime)
4777     return false;
4778 
4779   // Do not emit diag when the string param is a macro expansion and the
4780   // format is either NSString or CFString. This is a hack to prevent
4781   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4782   // which are usually used in place of NS and CF string literals.
4783   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4784   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4785     return false;
4786 
4787   // If there are no arguments specified, warn with -Wformat-security, otherwise
4788   // warn only with -Wformat-nonliteral.
4789   if (Args.size() == firstDataArg) {
4790     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4791       << OrigFormatExpr->getSourceRange();
4792     switch (Type) {
4793     default:
4794       break;
4795     case FST_Kprintf:
4796     case FST_FreeBSDKPrintf:
4797     case FST_Printf:
4798       Diag(FormatLoc, diag::note_format_security_fixit)
4799         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4800       break;
4801     case FST_NSString:
4802       Diag(FormatLoc, diag::note_format_security_fixit)
4803         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4804       break;
4805     }
4806   } else {
4807     Diag(FormatLoc, diag::warn_format_nonliteral)
4808       << OrigFormatExpr->getSourceRange();
4809   }
4810   return false;
4811 }
4812 
4813 namespace {
4814 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4815 protected:
4816   Sema &S;
4817   const FormatStringLiteral *FExpr;
4818   const Expr *OrigFormatExpr;
4819   const Sema::FormatStringType FSType;
4820   const unsigned FirstDataArg;
4821   const unsigned NumDataArgs;
4822   const char *Beg; // Start of format string.
4823   const bool HasVAListArg;
4824   ArrayRef<const Expr *> Args;
4825   unsigned FormatIdx;
4826   llvm::SmallBitVector CoveredArgs;
4827   bool usesPositionalArgs;
4828   bool atFirstArg;
4829   bool inFunctionCall;
4830   Sema::VariadicCallType CallType;
4831   llvm::SmallBitVector &CheckedVarArgs;
4832   UncoveredArgHandler &UncoveredArg;
4833 
4834 public:
4835   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4836                      const Expr *origFormatExpr,
4837                      const Sema::FormatStringType type, unsigned firstDataArg,
4838                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
4839                      ArrayRef<const Expr *> Args, unsigned formatIdx,
4840                      bool inFunctionCall, Sema::VariadicCallType callType,
4841                      llvm::SmallBitVector &CheckedVarArgs,
4842                      UncoveredArgHandler &UncoveredArg)
4843       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4844         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4845         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4846         usesPositionalArgs(false), atFirstArg(true),
4847         inFunctionCall(inFunctionCall), CallType(callType),
4848         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4849     CoveredArgs.resize(numDataArgs);
4850     CoveredArgs.reset();
4851   }
4852 
4853   void DoneProcessing();
4854 
4855   void HandleIncompleteSpecifier(const char *startSpecifier,
4856                                  unsigned specifierLen) override;
4857 
4858   void HandleInvalidLengthModifier(
4859                            const analyze_format_string::FormatSpecifier &FS,
4860                            const analyze_format_string::ConversionSpecifier &CS,
4861                            const char *startSpecifier, unsigned specifierLen,
4862                            unsigned DiagID);
4863 
4864   void HandleNonStandardLengthModifier(
4865                     const analyze_format_string::FormatSpecifier &FS,
4866                     const char *startSpecifier, unsigned specifierLen);
4867 
4868   void HandleNonStandardConversionSpecifier(
4869                     const analyze_format_string::ConversionSpecifier &CS,
4870                     const char *startSpecifier, unsigned specifierLen);
4871 
4872   void HandlePosition(const char *startPos, unsigned posLen) override;
4873 
4874   void HandleInvalidPosition(const char *startSpecifier,
4875                              unsigned specifierLen,
4876                              analyze_format_string::PositionContext p) override;
4877 
4878   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4879 
4880   void HandleNullChar(const char *nullCharacter) override;
4881 
4882   template <typename Range>
4883   static void
4884   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4885                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4886                        bool IsStringLocation, Range StringRange,
4887                        ArrayRef<FixItHint> Fixit = None);
4888 
4889 protected:
4890   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4891                                         const char *startSpec,
4892                                         unsigned specifierLen,
4893                                         const char *csStart, unsigned csLen);
4894 
4895   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4896                                          const char *startSpec,
4897                                          unsigned specifierLen);
4898 
4899   SourceRange getFormatStringRange();
4900   CharSourceRange getSpecifierRange(const char *startSpecifier,
4901                                     unsigned specifierLen);
4902   SourceLocation getLocationOfByte(const char *x);
4903 
4904   const Expr *getDataArg(unsigned i) const;
4905 
4906   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4907                     const analyze_format_string::ConversionSpecifier &CS,
4908                     const char *startSpecifier, unsigned specifierLen,
4909                     unsigned argIndex);
4910 
4911   template <typename Range>
4912   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4913                             bool IsStringLocation, Range StringRange,
4914                             ArrayRef<FixItHint> Fixit = None);
4915 };
4916 } // end anonymous namespace
4917 
4918 SourceRange CheckFormatHandler::getFormatStringRange() {
4919   return OrigFormatExpr->getSourceRange();
4920 }
4921 
4922 CharSourceRange CheckFormatHandler::
4923 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4924   SourceLocation Start = getLocationOfByte(startSpecifier);
4925   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4926 
4927   // Advance the end SourceLocation by one due to half-open ranges.
4928   End = End.getLocWithOffset(1);
4929 
4930   return CharSourceRange::getCharRange(Start, End);
4931 }
4932 
4933 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4934   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4935                                   S.getLangOpts(), S.Context.getTargetInfo());
4936 }
4937 
4938 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4939                                                    unsigned specifierLen){
4940   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4941                        getLocationOfByte(startSpecifier),
4942                        /*IsStringLocation*/true,
4943                        getSpecifierRange(startSpecifier, specifierLen));
4944 }
4945 
4946 void CheckFormatHandler::HandleInvalidLengthModifier(
4947     const analyze_format_string::FormatSpecifier &FS,
4948     const analyze_format_string::ConversionSpecifier &CS,
4949     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4950   using namespace analyze_format_string;
4951 
4952   const LengthModifier &LM = FS.getLengthModifier();
4953   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4954 
4955   // See if we know how to fix this length modifier.
4956   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4957   if (FixedLM) {
4958     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4959                          getLocationOfByte(LM.getStart()),
4960                          /*IsStringLocation*/true,
4961                          getSpecifierRange(startSpecifier, specifierLen));
4962 
4963     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4964       << FixedLM->toString()
4965       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4966 
4967   } else {
4968     FixItHint Hint;
4969     if (DiagID == diag::warn_format_nonsensical_length)
4970       Hint = FixItHint::CreateRemoval(LMRange);
4971 
4972     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4973                          getLocationOfByte(LM.getStart()),
4974                          /*IsStringLocation*/true,
4975                          getSpecifierRange(startSpecifier, specifierLen),
4976                          Hint);
4977   }
4978 }
4979 
4980 void CheckFormatHandler::HandleNonStandardLengthModifier(
4981     const analyze_format_string::FormatSpecifier &FS,
4982     const char *startSpecifier, unsigned specifierLen) {
4983   using namespace analyze_format_string;
4984 
4985   const LengthModifier &LM = FS.getLengthModifier();
4986   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4987 
4988   // See if we know how to fix this length modifier.
4989   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4990   if (FixedLM) {
4991     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4992                            << LM.toString() << 0,
4993                          getLocationOfByte(LM.getStart()),
4994                          /*IsStringLocation*/true,
4995                          getSpecifierRange(startSpecifier, specifierLen));
4996 
4997     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4998       << FixedLM->toString()
4999       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5000 
5001   } else {
5002     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5003                            << LM.toString() << 0,
5004                          getLocationOfByte(LM.getStart()),
5005                          /*IsStringLocation*/true,
5006                          getSpecifierRange(startSpecifier, specifierLen));
5007   }
5008 }
5009 
5010 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5011     const analyze_format_string::ConversionSpecifier &CS,
5012     const char *startSpecifier, unsigned specifierLen) {
5013   using namespace analyze_format_string;
5014 
5015   // See if we know how to fix this conversion specifier.
5016   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5017   if (FixedCS) {
5018     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5019                           << CS.toString() << /*conversion specifier*/1,
5020                          getLocationOfByte(CS.getStart()),
5021                          /*IsStringLocation*/true,
5022                          getSpecifierRange(startSpecifier, specifierLen));
5023 
5024     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5025     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5026       << FixedCS->toString()
5027       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5028   } else {
5029     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5030                           << CS.toString() << /*conversion specifier*/1,
5031                          getLocationOfByte(CS.getStart()),
5032                          /*IsStringLocation*/true,
5033                          getSpecifierRange(startSpecifier, specifierLen));
5034   }
5035 }
5036 
5037 void CheckFormatHandler::HandlePosition(const char *startPos,
5038                                         unsigned posLen) {
5039   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5040                                getLocationOfByte(startPos),
5041                                /*IsStringLocation*/true,
5042                                getSpecifierRange(startPos, posLen));
5043 }
5044 
5045 void
5046 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5047                                      analyze_format_string::PositionContext p) {
5048   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5049                          << (unsigned) p,
5050                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5051                        getSpecifierRange(startPos, posLen));
5052 }
5053 
5054 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5055                                             unsigned posLen) {
5056   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5057                                getLocationOfByte(startPos),
5058                                /*IsStringLocation*/true,
5059                                getSpecifierRange(startPos, posLen));
5060 }
5061 
5062 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5063   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5064     // The presence of a null character is likely an error.
5065     EmitFormatDiagnostic(
5066       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5067       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5068       getFormatStringRange());
5069   }
5070 }
5071 
5072 // Note that this may return NULL if there was an error parsing or building
5073 // one of the argument expressions.
5074 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5075   return Args[FirstDataArg + i];
5076 }
5077 
5078 void CheckFormatHandler::DoneProcessing() {
5079   // Does the number of data arguments exceed the number of
5080   // format conversions in the format string?
5081   if (!HasVAListArg) {
5082       // Find any arguments that weren't covered.
5083     CoveredArgs.flip();
5084     signed notCoveredArg = CoveredArgs.find_first();
5085     if (notCoveredArg >= 0) {
5086       assert((unsigned)notCoveredArg < NumDataArgs);
5087       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5088     } else {
5089       UncoveredArg.setAllCovered();
5090     }
5091   }
5092 }
5093 
5094 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5095                                    const Expr *ArgExpr) {
5096   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5097          "Invalid state");
5098 
5099   if (!ArgExpr)
5100     return;
5101 
5102   SourceLocation Loc = ArgExpr->getLocStart();
5103 
5104   if (S.getSourceManager().isInSystemMacro(Loc))
5105     return;
5106 
5107   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5108   for (auto E : DiagnosticExprs)
5109     PDiag << E->getSourceRange();
5110 
5111   CheckFormatHandler::EmitFormatDiagnostic(
5112                                   S, IsFunctionCall, DiagnosticExprs[0],
5113                                   PDiag, Loc, /*IsStringLocation*/false,
5114                                   DiagnosticExprs[0]->getSourceRange());
5115 }
5116 
5117 bool
5118 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5119                                                      SourceLocation Loc,
5120                                                      const char *startSpec,
5121                                                      unsigned specifierLen,
5122                                                      const char *csStart,
5123                                                      unsigned csLen) {
5124   bool keepGoing = true;
5125   if (argIndex < NumDataArgs) {
5126     // Consider the argument coverered, even though the specifier doesn't
5127     // make sense.
5128     CoveredArgs.set(argIndex);
5129   }
5130   else {
5131     // If argIndex exceeds the number of data arguments we
5132     // don't issue a warning because that is just a cascade of warnings (and
5133     // they may have intended '%%' anyway). We don't want to continue processing
5134     // the format string after this point, however, as we will like just get
5135     // gibberish when trying to match arguments.
5136     keepGoing = false;
5137   }
5138 
5139   StringRef Specifier(csStart, csLen);
5140 
5141   // If the specifier in non-printable, it could be the first byte of a UTF-8
5142   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5143   // hex value.
5144   std::string CodePointStr;
5145   if (!llvm::sys::locale::isPrint(*csStart)) {
5146     llvm::UTF32 CodePoint;
5147     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5148     const llvm::UTF8 *E =
5149         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5150     llvm::ConversionResult Result =
5151         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5152 
5153     if (Result != llvm::conversionOK) {
5154       unsigned char FirstChar = *csStart;
5155       CodePoint = (llvm::UTF32)FirstChar;
5156     }
5157 
5158     llvm::raw_string_ostream OS(CodePointStr);
5159     if (CodePoint < 256)
5160       OS << "\\x" << llvm::format("%02x", CodePoint);
5161     else if (CodePoint <= 0xFFFF)
5162       OS << "\\u" << llvm::format("%04x", CodePoint);
5163     else
5164       OS << "\\U" << llvm::format("%08x", CodePoint);
5165     OS.flush();
5166     Specifier = CodePointStr;
5167   }
5168 
5169   EmitFormatDiagnostic(
5170       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5171       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5172 
5173   return keepGoing;
5174 }
5175 
5176 void
5177 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5178                                                       const char *startSpec,
5179                                                       unsigned specifierLen) {
5180   EmitFormatDiagnostic(
5181     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5182     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5183 }
5184 
5185 bool
5186 CheckFormatHandler::CheckNumArgs(
5187   const analyze_format_string::FormatSpecifier &FS,
5188   const analyze_format_string::ConversionSpecifier &CS,
5189   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5190 
5191   if (argIndex >= NumDataArgs) {
5192     PartialDiagnostic PDiag = FS.usesPositionalArg()
5193       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5194            << (argIndex+1) << NumDataArgs)
5195       : S.PDiag(diag::warn_printf_insufficient_data_args);
5196     EmitFormatDiagnostic(
5197       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5198       getSpecifierRange(startSpecifier, specifierLen));
5199 
5200     // Since more arguments than conversion tokens are given, by extension
5201     // all arguments are covered, so mark this as so.
5202     UncoveredArg.setAllCovered();
5203     return false;
5204   }
5205   return true;
5206 }
5207 
5208 template<typename Range>
5209 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5210                                               SourceLocation Loc,
5211                                               bool IsStringLocation,
5212                                               Range StringRange,
5213                                               ArrayRef<FixItHint> FixIt) {
5214   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5215                        Loc, IsStringLocation, StringRange, FixIt);
5216 }
5217 
5218 /// \brief If the format string is not within the funcion call, emit a note
5219 /// so that the function call and string are in diagnostic messages.
5220 ///
5221 /// \param InFunctionCall if true, the format string is within the function
5222 /// call and only one diagnostic message will be produced.  Otherwise, an
5223 /// extra note will be emitted pointing to location of the format string.
5224 ///
5225 /// \param ArgumentExpr the expression that is passed as the format string
5226 /// argument in the function call.  Used for getting locations when two
5227 /// diagnostics are emitted.
5228 ///
5229 /// \param PDiag the callee should already have provided any strings for the
5230 /// diagnostic message.  This function only adds locations and fixits
5231 /// to diagnostics.
5232 ///
5233 /// \param Loc primary location for diagnostic.  If two diagnostics are
5234 /// required, one will be at Loc and a new SourceLocation will be created for
5235 /// the other one.
5236 ///
5237 /// \param IsStringLocation if true, Loc points to the format string should be
5238 /// used for the note.  Otherwise, Loc points to the argument list and will
5239 /// be used with PDiag.
5240 ///
5241 /// \param StringRange some or all of the string to highlight.  This is
5242 /// templated so it can accept either a CharSourceRange or a SourceRange.
5243 ///
5244 /// \param FixIt optional fix it hint for the format string.
5245 template <typename Range>
5246 void CheckFormatHandler::EmitFormatDiagnostic(
5247     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5248     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5249     Range StringRange, ArrayRef<FixItHint> FixIt) {
5250   if (InFunctionCall) {
5251     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5252     D << StringRange;
5253     D << FixIt;
5254   } else {
5255     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5256       << ArgumentExpr->getSourceRange();
5257 
5258     const Sema::SemaDiagnosticBuilder &Note =
5259       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5260              diag::note_format_string_defined);
5261 
5262     Note << StringRange;
5263     Note << FixIt;
5264   }
5265 }
5266 
5267 //===--- CHECK: Printf format string checking ------------------------------===//
5268 
5269 namespace {
5270 class CheckPrintfHandler : public CheckFormatHandler {
5271 public:
5272   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5273                      const Expr *origFormatExpr,
5274                      const Sema::FormatStringType type, unsigned firstDataArg,
5275                      unsigned numDataArgs, bool isObjC, const char *beg,
5276                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5277                      unsigned formatIdx, bool inFunctionCall,
5278                      Sema::VariadicCallType CallType,
5279                      llvm::SmallBitVector &CheckedVarArgs,
5280                      UncoveredArgHandler &UncoveredArg)
5281       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5282                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5283                            inFunctionCall, CallType, CheckedVarArgs,
5284                            UncoveredArg) {}
5285 
5286   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5287 
5288   /// Returns true if '%@' specifiers are allowed in the format string.
5289   bool allowsObjCArg() const {
5290     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5291            FSType == Sema::FST_OSTrace;
5292   }
5293 
5294   bool HandleInvalidPrintfConversionSpecifier(
5295                                       const analyze_printf::PrintfSpecifier &FS,
5296                                       const char *startSpecifier,
5297                                       unsigned specifierLen) override;
5298 
5299   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5300                              const char *startSpecifier,
5301                              unsigned specifierLen) override;
5302   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5303                        const char *StartSpecifier,
5304                        unsigned SpecifierLen,
5305                        const Expr *E);
5306 
5307   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5308                     const char *startSpecifier, unsigned specifierLen);
5309   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5310                            const analyze_printf::OptionalAmount &Amt,
5311                            unsigned type,
5312                            const char *startSpecifier, unsigned specifierLen);
5313   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5314                   const analyze_printf::OptionalFlag &flag,
5315                   const char *startSpecifier, unsigned specifierLen);
5316   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5317                          const analyze_printf::OptionalFlag &ignoredFlag,
5318                          const analyze_printf::OptionalFlag &flag,
5319                          const char *startSpecifier, unsigned specifierLen);
5320   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5321                            const Expr *E);
5322 
5323   void HandleEmptyObjCModifierFlag(const char *startFlag,
5324                                    unsigned flagLen) override;
5325 
5326   void HandleInvalidObjCModifierFlag(const char *startFlag,
5327                                             unsigned flagLen) override;
5328 
5329   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5330                                            const char *flagsEnd,
5331                                            const char *conversionPosition)
5332                                              override;
5333 };
5334 } // end anonymous namespace
5335 
5336 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5337                                       const analyze_printf::PrintfSpecifier &FS,
5338                                       const char *startSpecifier,
5339                                       unsigned specifierLen) {
5340   const analyze_printf::PrintfConversionSpecifier &CS =
5341     FS.getConversionSpecifier();
5342 
5343   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5344                                           getLocationOfByte(CS.getStart()),
5345                                           startSpecifier, specifierLen,
5346                                           CS.getStart(), CS.getLength());
5347 }
5348 
5349 bool CheckPrintfHandler::HandleAmount(
5350                                const analyze_format_string::OptionalAmount &Amt,
5351                                unsigned k, const char *startSpecifier,
5352                                unsigned specifierLen) {
5353   if (Amt.hasDataArgument()) {
5354     if (!HasVAListArg) {
5355       unsigned argIndex = Amt.getArgIndex();
5356       if (argIndex >= NumDataArgs) {
5357         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5358                                << k,
5359                              getLocationOfByte(Amt.getStart()),
5360                              /*IsStringLocation*/true,
5361                              getSpecifierRange(startSpecifier, specifierLen));
5362         // Don't do any more checking.  We will just emit
5363         // spurious errors.
5364         return false;
5365       }
5366 
5367       // Type check the data argument.  It should be an 'int'.
5368       // Although not in conformance with C99, we also allow the argument to be
5369       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5370       // doesn't emit a warning for that case.
5371       CoveredArgs.set(argIndex);
5372       const Expr *Arg = getDataArg(argIndex);
5373       if (!Arg)
5374         return false;
5375 
5376       QualType T = Arg->getType();
5377 
5378       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5379       assert(AT.isValid());
5380 
5381       if (!AT.matchesType(S.Context, T)) {
5382         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5383                                << k << AT.getRepresentativeTypeName(S.Context)
5384                                << T << Arg->getSourceRange(),
5385                              getLocationOfByte(Amt.getStart()),
5386                              /*IsStringLocation*/true,
5387                              getSpecifierRange(startSpecifier, specifierLen));
5388         // Don't do any more checking.  We will just emit
5389         // spurious errors.
5390         return false;
5391       }
5392     }
5393   }
5394   return true;
5395 }
5396 
5397 void CheckPrintfHandler::HandleInvalidAmount(
5398                                       const analyze_printf::PrintfSpecifier &FS,
5399                                       const analyze_printf::OptionalAmount &Amt,
5400                                       unsigned type,
5401                                       const char *startSpecifier,
5402                                       unsigned specifierLen) {
5403   const analyze_printf::PrintfConversionSpecifier &CS =
5404     FS.getConversionSpecifier();
5405 
5406   FixItHint fixit =
5407     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5408       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5409                                  Amt.getConstantLength()))
5410       : FixItHint();
5411 
5412   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5413                          << type << CS.toString(),
5414                        getLocationOfByte(Amt.getStart()),
5415                        /*IsStringLocation*/true,
5416                        getSpecifierRange(startSpecifier, specifierLen),
5417                        fixit);
5418 }
5419 
5420 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5421                                     const analyze_printf::OptionalFlag &flag,
5422                                     const char *startSpecifier,
5423                                     unsigned specifierLen) {
5424   // Warn about pointless flag with a fixit removal.
5425   const analyze_printf::PrintfConversionSpecifier &CS =
5426     FS.getConversionSpecifier();
5427   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5428                          << flag.toString() << CS.toString(),
5429                        getLocationOfByte(flag.getPosition()),
5430                        /*IsStringLocation*/true,
5431                        getSpecifierRange(startSpecifier, specifierLen),
5432                        FixItHint::CreateRemoval(
5433                          getSpecifierRange(flag.getPosition(), 1)));
5434 }
5435 
5436 void CheckPrintfHandler::HandleIgnoredFlag(
5437                                 const analyze_printf::PrintfSpecifier &FS,
5438                                 const analyze_printf::OptionalFlag &ignoredFlag,
5439                                 const analyze_printf::OptionalFlag &flag,
5440                                 const char *startSpecifier,
5441                                 unsigned specifierLen) {
5442   // Warn about ignored flag with a fixit removal.
5443   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5444                          << ignoredFlag.toString() << flag.toString(),
5445                        getLocationOfByte(ignoredFlag.getPosition()),
5446                        /*IsStringLocation*/true,
5447                        getSpecifierRange(startSpecifier, specifierLen),
5448                        FixItHint::CreateRemoval(
5449                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5450 }
5451 
5452 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5453 //                            bool IsStringLocation, Range StringRange,
5454 //                            ArrayRef<FixItHint> Fixit = None);
5455 
5456 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5457                                                      unsigned flagLen) {
5458   // Warn about an empty flag.
5459   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5460                        getLocationOfByte(startFlag),
5461                        /*IsStringLocation*/true,
5462                        getSpecifierRange(startFlag, flagLen));
5463 }
5464 
5465 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5466                                                        unsigned flagLen) {
5467   // Warn about an invalid flag.
5468   auto Range = getSpecifierRange(startFlag, flagLen);
5469   StringRef flag(startFlag, flagLen);
5470   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5471                       getLocationOfByte(startFlag),
5472                       /*IsStringLocation*/true,
5473                       Range, FixItHint::CreateRemoval(Range));
5474 }
5475 
5476 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5477     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5478     // Warn about using '[...]' without a '@' conversion.
5479     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5480     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5481     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5482                          getLocationOfByte(conversionPosition),
5483                          /*IsStringLocation*/true,
5484                          Range, FixItHint::CreateRemoval(Range));
5485 }
5486 
5487 // Determines if the specified is a C++ class or struct containing
5488 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5489 // "c_str()").
5490 template<typename MemberKind>
5491 static llvm::SmallPtrSet<MemberKind*, 1>
5492 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5493   const RecordType *RT = Ty->getAs<RecordType>();
5494   llvm::SmallPtrSet<MemberKind*, 1> Results;
5495 
5496   if (!RT)
5497     return Results;
5498   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5499   if (!RD || !RD->getDefinition())
5500     return Results;
5501 
5502   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5503                  Sema::LookupMemberName);
5504   R.suppressDiagnostics();
5505 
5506   // We just need to include all members of the right kind turned up by the
5507   // filter, at this point.
5508   if (S.LookupQualifiedName(R, RT->getDecl()))
5509     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5510       NamedDecl *decl = (*I)->getUnderlyingDecl();
5511       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5512         Results.insert(FK);
5513     }
5514   return Results;
5515 }
5516 
5517 /// Check if we could call '.c_str()' on an object.
5518 ///
5519 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5520 /// allow the call, or if it would be ambiguous).
5521 bool Sema::hasCStrMethod(const Expr *E) {
5522   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5523   MethodSet Results =
5524       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5525   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5526        MI != ME; ++MI)
5527     if ((*MI)->getMinRequiredArguments() == 0)
5528       return true;
5529   return false;
5530 }
5531 
5532 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5533 // better diagnostic if so. AT is assumed to be valid.
5534 // Returns true when a c_str() conversion method is found.
5535 bool CheckPrintfHandler::checkForCStrMembers(
5536     const analyze_printf::ArgType &AT, const Expr *E) {
5537   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5538 
5539   MethodSet Results =
5540       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5541 
5542   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5543        MI != ME; ++MI) {
5544     const CXXMethodDecl *Method = *MI;
5545     if (Method->getMinRequiredArguments() == 0 &&
5546         AT.matchesType(S.Context, Method->getReturnType())) {
5547       // FIXME: Suggest parens if the expression needs them.
5548       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5549       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5550           << "c_str()"
5551           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5552       return true;
5553     }
5554   }
5555 
5556   return false;
5557 }
5558 
5559 bool
5560 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5561                                             &FS,
5562                                           const char *startSpecifier,
5563                                           unsigned specifierLen) {
5564   using namespace analyze_format_string;
5565   using namespace analyze_printf;
5566   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5567 
5568   if (FS.consumesDataArgument()) {
5569     if (atFirstArg) {
5570         atFirstArg = false;
5571         usesPositionalArgs = FS.usesPositionalArg();
5572     }
5573     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5574       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5575                                         startSpecifier, specifierLen);
5576       return false;
5577     }
5578   }
5579 
5580   // First check if the field width, precision, and conversion specifier
5581   // have matching data arguments.
5582   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5583                     startSpecifier, specifierLen)) {
5584     return false;
5585   }
5586 
5587   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5588                     startSpecifier, specifierLen)) {
5589     return false;
5590   }
5591 
5592   if (!CS.consumesDataArgument()) {
5593     // FIXME: Technically specifying a precision or field width here
5594     // makes no sense.  Worth issuing a warning at some point.
5595     return true;
5596   }
5597 
5598   // Consume the argument.
5599   unsigned argIndex = FS.getArgIndex();
5600   if (argIndex < NumDataArgs) {
5601     // The check to see if the argIndex is valid will come later.
5602     // We set the bit here because we may exit early from this
5603     // function if we encounter some other error.
5604     CoveredArgs.set(argIndex);
5605   }
5606 
5607   // FreeBSD kernel extensions.
5608   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5609       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5610     // We need at least two arguments.
5611     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5612       return false;
5613 
5614     // Claim the second argument.
5615     CoveredArgs.set(argIndex + 1);
5616 
5617     // Type check the first argument (int for %b, pointer for %D)
5618     const Expr *Ex = getDataArg(argIndex);
5619     const analyze_printf::ArgType &AT =
5620       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5621         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5622     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5623       EmitFormatDiagnostic(
5624         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5625         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5626         << false << Ex->getSourceRange(),
5627         Ex->getLocStart(), /*IsStringLocation*/false,
5628         getSpecifierRange(startSpecifier, specifierLen));
5629 
5630     // Type check the second argument (char * for both %b and %D)
5631     Ex = getDataArg(argIndex + 1);
5632     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5633     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5634       EmitFormatDiagnostic(
5635         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5636         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5637         << false << Ex->getSourceRange(),
5638         Ex->getLocStart(), /*IsStringLocation*/false,
5639         getSpecifierRange(startSpecifier, specifierLen));
5640 
5641      return true;
5642   }
5643 
5644   // Check for using an Objective-C specific conversion specifier
5645   // in a non-ObjC literal.
5646   if (!allowsObjCArg() && CS.isObjCArg()) {
5647     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5648                                                   specifierLen);
5649   }
5650 
5651   // %P can only be used with os_log.
5652   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5653     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5654                                                   specifierLen);
5655   }
5656 
5657   // %n is not allowed with os_log.
5658   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5659     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5660                          getLocationOfByte(CS.getStart()),
5661                          /*IsStringLocation*/ false,
5662                          getSpecifierRange(startSpecifier, specifierLen));
5663 
5664     return true;
5665   }
5666 
5667   // Only scalars are allowed for os_trace.
5668   if (FSType == Sema::FST_OSTrace &&
5669       (CS.getKind() == ConversionSpecifier::PArg ||
5670        CS.getKind() == ConversionSpecifier::sArg ||
5671        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5672     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5673                                                   specifierLen);
5674   }
5675 
5676   // Check for use of public/private annotation outside of os_log().
5677   if (FSType != Sema::FST_OSLog) {
5678     if (FS.isPublic().isSet()) {
5679       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5680                                << "public",
5681                            getLocationOfByte(FS.isPublic().getPosition()),
5682                            /*IsStringLocation*/ false,
5683                            getSpecifierRange(startSpecifier, specifierLen));
5684     }
5685     if (FS.isPrivate().isSet()) {
5686       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5687                                << "private",
5688                            getLocationOfByte(FS.isPrivate().getPosition()),
5689                            /*IsStringLocation*/ false,
5690                            getSpecifierRange(startSpecifier, specifierLen));
5691     }
5692   }
5693 
5694   // Check for invalid use of field width
5695   if (!FS.hasValidFieldWidth()) {
5696     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5697         startSpecifier, specifierLen);
5698   }
5699 
5700   // Check for invalid use of precision
5701   if (!FS.hasValidPrecision()) {
5702     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5703         startSpecifier, specifierLen);
5704   }
5705 
5706   // Precision is mandatory for %P specifier.
5707   if (CS.getKind() == ConversionSpecifier::PArg &&
5708       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5709     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5710                          getLocationOfByte(startSpecifier),
5711                          /*IsStringLocation*/ false,
5712                          getSpecifierRange(startSpecifier, specifierLen));
5713   }
5714 
5715   // Check each flag does not conflict with any other component.
5716   if (!FS.hasValidThousandsGroupingPrefix())
5717     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5718   if (!FS.hasValidLeadingZeros())
5719     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5720   if (!FS.hasValidPlusPrefix())
5721     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5722   if (!FS.hasValidSpacePrefix())
5723     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5724   if (!FS.hasValidAlternativeForm())
5725     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5726   if (!FS.hasValidLeftJustified())
5727     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5728 
5729   // Check that flags are not ignored by another flag
5730   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5731     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5732         startSpecifier, specifierLen);
5733   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5734     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5735             startSpecifier, specifierLen);
5736 
5737   // Check the length modifier is valid with the given conversion specifier.
5738   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5739     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5740                                 diag::warn_format_nonsensical_length);
5741   else if (!FS.hasStandardLengthModifier())
5742     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5743   else if (!FS.hasStandardLengthConversionCombination())
5744     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5745                                 diag::warn_format_non_standard_conversion_spec);
5746 
5747   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5748     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5749 
5750   // The remaining checks depend on the data arguments.
5751   if (HasVAListArg)
5752     return true;
5753 
5754   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5755     return false;
5756 
5757   const Expr *Arg = getDataArg(argIndex);
5758   if (!Arg)
5759     return true;
5760 
5761   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5762 }
5763 
5764 static bool requiresParensToAddCast(const Expr *E) {
5765   // FIXME: We should have a general way to reason about operator
5766   // precedence and whether parens are actually needed here.
5767   // Take care of a few common cases where they aren't.
5768   const Expr *Inside = E->IgnoreImpCasts();
5769   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5770     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5771 
5772   switch (Inside->getStmtClass()) {
5773   case Stmt::ArraySubscriptExprClass:
5774   case Stmt::CallExprClass:
5775   case Stmt::CharacterLiteralClass:
5776   case Stmt::CXXBoolLiteralExprClass:
5777   case Stmt::DeclRefExprClass:
5778   case Stmt::FloatingLiteralClass:
5779   case Stmt::IntegerLiteralClass:
5780   case Stmt::MemberExprClass:
5781   case Stmt::ObjCArrayLiteralClass:
5782   case Stmt::ObjCBoolLiteralExprClass:
5783   case Stmt::ObjCBoxedExprClass:
5784   case Stmt::ObjCDictionaryLiteralClass:
5785   case Stmt::ObjCEncodeExprClass:
5786   case Stmt::ObjCIvarRefExprClass:
5787   case Stmt::ObjCMessageExprClass:
5788   case Stmt::ObjCPropertyRefExprClass:
5789   case Stmt::ObjCStringLiteralClass:
5790   case Stmt::ObjCSubscriptRefExprClass:
5791   case Stmt::ParenExprClass:
5792   case Stmt::StringLiteralClass:
5793   case Stmt::UnaryOperatorClass:
5794     return false;
5795   default:
5796     return true;
5797   }
5798 }
5799 
5800 static std::pair<QualType, StringRef>
5801 shouldNotPrintDirectly(const ASTContext &Context,
5802                        QualType IntendedTy,
5803                        const Expr *E) {
5804   // Use a 'while' to peel off layers of typedefs.
5805   QualType TyTy = IntendedTy;
5806   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5807     StringRef Name = UserTy->getDecl()->getName();
5808     QualType CastTy = llvm::StringSwitch<QualType>(Name)
5809       .Case("NSInteger", Context.LongTy)
5810       .Case("NSUInteger", Context.UnsignedLongTy)
5811       .Case("SInt32", Context.IntTy)
5812       .Case("UInt32", Context.UnsignedIntTy)
5813       .Default(QualType());
5814 
5815     if (!CastTy.isNull())
5816       return std::make_pair(CastTy, Name);
5817 
5818     TyTy = UserTy->desugar();
5819   }
5820 
5821   // Strip parens if necessary.
5822   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5823     return shouldNotPrintDirectly(Context,
5824                                   PE->getSubExpr()->getType(),
5825                                   PE->getSubExpr());
5826 
5827   // If this is a conditional expression, then its result type is constructed
5828   // via usual arithmetic conversions and thus there might be no necessary
5829   // typedef sugar there.  Recurse to operands to check for NSInteger &
5830   // Co. usage condition.
5831   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5832     QualType TrueTy, FalseTy;
5833     StringRef TrueName, FalseName;
5834 
5835     std::tie(TrueTy, TrueName) =
5836       shouldNotPrintDirectly(Context,
5837                              CO->getTrueExpr()->getType(),
5838                              CO->getTrueExpr());
5839     std::tie(FalseTy, FalseName) =
5840       shouldNotPrintDirectly(Context,
5841                              CO->getFalseExpr()->getType(),
5842                              CO->getFalseExpr());
5843 
5844     if (TrueTy == FalseTy)
5845       return std::make_pair(TrueTy, TrueName);
5846     else if (TrueTy.isNull())
5847       return std::make_pair(FalseTy, FalseName);
5848     else if (FalseTy.isNull())
5849       return std::make_pair(TrueTy, TrueName);
5850   }
5851 
5852   return std::make_pair(QualType(), StringRef());
5853 }
5854 
5855 bool
5856 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5857                                     const char *StartSpecifier,
5858                                     unsigned SpecifierLen,
5859                                     const Expr *E) {
5860   using namespace analyze_format_string;
5861   using namespace analyze_printf;
5862   // Now type check the data expression that matches the
5863   // format specifier.
5864   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
5865   if (!AT.isValid())
5866     return true;
5867 
5868   QualType ExprTy = E->getType();
5869   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5870     ExprTy = TET->getUnderlyingExpr()->getType();
5871   }
5872 
5873   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5874 
5875   if (match == analyze_printf::ArgType::Match) {
5876     return true;
5877   }
5878 
5879   // Look through argument promotions for our error message's reported type.
5880   // This includes the integral and floating promotions, but excludes array
5881   // and function pointer decay; seeing that an argument intended to be a
5882   // string has type 'char [6]' is probably more confusing than 'char *'.
5883   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5884     if (ICE->getCastKind() == CK_IntegralCast ||
5885         ICE->getCastKind() == CK_FloatingCast) {
5886       E = ICE->getSubExpr();
5887       ExprTy = E->getType();
5888 
5889       // Check if we didn't match because of an implicit cast from a 'char'
5890       // or 'short' to an 'int'.  This is done because printf is a varargs
5891       // function.
5892       if (ICE->getType() == S.Context.IntTy ||
5893           ICE->getType() == S.Context.UnsignedIntTy) {
5894         // All further checking is done on the subexpression.
5895         if (AT.matchesType(S.Context, ExprTy))
5896           return true;
5897       }
5898     }
5899   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5900     // Special case for 'a', which has type 'int' in C.
5901     // Note, however, that we do /not/ want to treat multibyte constants like
5902     // 'MooV' as characters! This form is deprecated but still exists.
5903     if (ExprTy == S.Context.IntTy)
5904       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5905         ExprTy = S.Context.CharTy;
5906   }
5907 
5908   // Look through enums to their underlying type.
5909   bool IsEnum = false;
5910   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5911     ExprTy = EnumTy->getDecl()->getIntegerType();
5912     IsEnum = true;
5913   }
5914 
5915   // %C in an Objective-C context prints a unichar, not a wchar_t.
5916   // If the argument is an integer of some kind, believe the %C and suggest
5917   // a cast instead of changing the conversion specifier.
5918   QualType IntendedTy = ExprTy;
5919   if (isObjCContext() &&
5920       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5921     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5922         !ExprTy->isCharType()) {
5923       // 'unichar' is defined as a typedef of unsigned short, but we should
5924       // prefer using the typedef if it is visible.
5925       IntendedTy = S.Context.UnsignedShortTy;
5926 
5927       // While we are here, check if the value is an IntegerLiteral that happens
5928       // to be within the valid range.
5929       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5930         const llvm::APInt &V = IL->getValue();
5931         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5932           return true;
5933       }
5934 
5935       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5936                           Sema::LookupOrdinaryName);
5937       if (S.LookupName(Result, S.getCurScope())) {
5938         NamedDecl *ND = Result.getFoundDecl();
5939         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5940           if (TD->getUnderlyingType() == IntendedTy)
5941             IntendedTy = S.Context.getTypedefType(TD);
5942       }
5943     }
5944   }
5945 
5946   // Special-case some of Darwin's platform-independence types by suggesting
5947   // casts to primitive types that are known to be large enough.
5948   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5949   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5950     QualType CastTy;
5951     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5952     if (!CastTy.isNull()) {
5953       IntendedTy = CastTy;
5954       ShouldNotPrintDirectly = true;
5955     }
5956   }
5957 
5958   // We may be able to offer a FixItHint if it is a supported type.
5959   PrintfSpecifier fixedFS = FS;
5960   bool success =
5961       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
5962 
5963   if (success) {
5964     // Get the fix string from the fixed format specifier
5965     SmallString<16> buf;
5966     llvm::raw_svector_ostream os(buf);
5967     fixedFS.toString(os);
5968 
5969     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5970 
5971     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5972       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5973       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5974         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5975       }
5976       // In this case, the specifier is wrong and should be changed to match
5977       // the argument.
5978       EmitFormatDiagnostic(S.PDiag(diag)
5979                                << AT.getRepresentativeTypeName(S.Context)
5980                                << IntendedTy << IsEnum << E->getSourceRange(),
5981                            E->getLocStart(),
5982                            /*IsStringLocation*/ false, SpecRange,
5983                            FixItHint::CreateReplacement(SpecRange, os.str()));
5984     } else {
5985       // The canonical type for formatting this value is different from the
5986       // actual type of the expression. (This occurs, for example, with Darwin's
5987       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5988       // should be printed as 'long' for 64-bit compatibility.)
5989       // Rather than emitting a normal format/argument mismatch, we want to
5990       // add a cast to the recommended type (and correct the format string
5991       // if necessary).
5992       SmallString<16> CastBuf;
5993       llvm::raw_svector_ostream CastFix(CastBuf);
5994       CastFix << "(";
5995       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5996       CastFix << ")";
5997 
5998       SmallVector<FixItHint,4> Hints;
5999       if (!AT.matchesType(S.Context, IntendedTy))
6000         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6001 
6002       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6003         // If there's already a cast present, just replace it.
6004         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6005         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6006 
6007       } else if (!requiresParensToAddCast(E)) {
6008         // If the expression has high enough precedence,
6009         // just write the C-style cast.
6010         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6011                                                    CastFix.str()));
6012       } else {
6013         // Otherwise, add parens around the expression as well as the cast.
6014         CastFix << "(";
6015         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6016                                                    CastFix.str()));
6017 
6018         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6019         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6020       }
6021 
6022       if (ShouldNotPrintDirectly) {
6023         // The expression has a type that should not be printed directly.
6024         // We extract the name from the typedef because we don't want to show
6025         // the underlying type in the diagnostic.
6026         StringRef Name;
6027         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6028           Name = TypedefTy->getDecl()->getName();
6029         else
6030           Name = CastTyName;
6031         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6032                                << Name << IntendedTy << IsEnum
6033                                << E->getSourceRange(),
6034                              E->getLocStart(), /*IsStringLocation=*/false,
6035                              SpecRange, Hints);
6036       } else {
6037         // In this case, the expression could be printed using a different
6038         // specifier, but we've decided that the specifier is probably correct
6039         // and we should cast instead. Just use the normal warning message.
6040         EmitFormatDiagnostic(
6041           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6042             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6043             << E->getSourceRange(),
6044           E->getLocStart(), /*IsStringLocation*/false,
6045           SpecRange, Hints);
6046       }
6047     }
6048   } else {
6049     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6050                                                    SpecifierLen);
6051     // Since the warning for passing non-POD types to variadic functions
6052     // was deferred until now, we emit a warning for non-POD
6053     // arguments here.
6054     switch (S.isValidVarArgType(ExprTy)) {
6055     case Sema::VAK_Valid:
6056     case Sema::VAK_ValidInCXX11: {
6057       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6058       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6059         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6060       }
6061 
6062       EmitFormatDiagnostic(
6063           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6064                         << IsEnum << CSR << E->getSourceRange(),
6065           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6066       break;
6067     }
6068     case Sema::VAK_Undefined:
6069     case Sema::VAK_MSVCUndefined:
6070       EmitFormatDiagnostic(
6071         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6072           << S.getLangOpts().CPlusPlus11
6073           << ExprTy
6074           << CallType
6075           << AT.getRepresentativeTypeName(S.Context)
6076           << CSR
6077           << E->getSourceRange(),
6078         E->getLocStart(), /*IsStringLocation*/false, CSR);
6079       checkForCStrMembers(AT, E);
6080       break;
6081 
6082     case Sema::VAK_Invalid:
6083       if (ExprTy->isObjCObjectType())
6084         EmitFormatDiagnostic(
6085           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6086             << S.getLangOpts().CPlusPlus11
6087             << ExprTy
6088             << CallType
6089             << AT.getRepresentativeTypeName(S.Context)
6090             << CSR
6091             << E->getSourceRange(),
6092           E->getLocStart(), /*IsStringLocation*/false, CSR);
6093       else
6094         // FIXME: If this is an initializer list, suggest removing the braces
6095         // or inserting a cast to the target type.
6096         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6097           << isa<InitListExpr>(E) << ExprTy << CallType
6098           << AT.getRepresentativeTypeName(S.Context)
6099           << E->getSourceRange();
6100       break;
6101     }
6102 
6103     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6104            "format string specifier index out of range");
6105     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6106   }
6107 
6108   return true;
6109 }
6110 
6111 //===--- CHECK: Scanf format string checking ------------------------------===//
6112 
6113 namespace {
6114 class CheckScanfHandler : public CheckFormatHandler {
6115 public:
6116   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6117                     const Expr *origFormatExpr, Sema::FormatStringType type,
6118                     unsigned firstDataArg, unsigned numDataArgs,
6119                     const char *beg, bool hasVAListArg,
6120                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6121                     bool inFunctionCall, Sema::VariadicCallType CallType,
6122                     llvm::SmallBitVector &CheckedVarArgs,
6123                     UncoveredArgHandler &UncoveredArg)
6124       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6125                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6126                            inFunctionCall, CallType, CheckedVarArgs,
6127                            UncoveredArg) {}
6128 
6129   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6130                             const char *startSpecifier,
6131                             unsigned specifierLen) override;
6132 
6133   bool HandleInvalidScanfConversionSpecifier(
6134           const analyze_scanf::ScanfSpecifier &FS,
6135           const char *startSpecifier,
6136           unsigned specifierLen) override;
6137 
6138   void HandleIncompleteScanList(const char *start, const char *end) override;
6139 };
6140 } // end anonymous namespace
6141 
6142 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6143                                                  const char *end) {
6144   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6145                        getLocationOfByte(end), /*IsStringLocation*/true,
6146                        getSpecifierRange(start, end - start));
6147 }
6148 
6149 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6150                                         const analyze_scanf::ScanfSpecifier &FS,
6151                                         const char *startSpecifier,
6152                                         unsigned specifierLen) {
6153 
6154   const analyze_scanf::ScanfConversionSpecifier &CS =
6155     FS.getConversionSpecifier();
6156 
6157   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6158                                           getLocationOfByte(CS.getStart()),
6159                                           startSpecifier, specifierLen,
6160                                           CS.getStart(), CS.getLength());
6161 }
6162 
6163 bool CheckScanfHandler::HandleScanfSpecifier(
6164                                        const analyze_scanf::ScanfSpecifier &FS,
6165                                        const char *startSpecifier,
6166                                        unsigned specifierLen) {
6167   using namespace analyze_scanf;
6168   using namespace analyze_format_string;
6169 
6170   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6171 
6172   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6173   // be used to decide if we are using positional arguments consistently.
6174   if (FS.consumesDataArgument()) {
6175     if (atFirstArg) {
6176       atFirstArg = false;
6177       usesPositionalArgs = FS.usesPositionalArg();
6178     }
6179     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6180       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6181                                         startSpecifier, specifierLen);
6182       return false;
6183     }
6184   }
6185 
6186   // Check if the field with is non-zero.
6187   const OptionalAmount &Amt = FS.getFieldWidth();
6188   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6189     if (Amt.getConstantAmount() == 0) {
6190       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6191                                                    Amt.getConstantLength());
6192       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6193                            getLocationOfByte(Amt.getStart()),
6194                            /*IsStringLocation*/true, R,
6195                            FixItHint::CreateRemoval(R));
6196     }
6197   }
6198 
6199   if (!FS.consumesDataArgument()) {
6200     // FIXME: Technically specifying a precision or field width here
6201     // makes no sense.  Worth issuing a warning at some point.
6202     return true;
6203   }
6204 
6205   // Consume the argument.
6206   unsigned argIndex = FS.getArgIndex();
6207   if (argIndex < NumDataArgs) {
6208       // The check to see if the argIndex is valid will come later.
6209       // We set the bit here because we may exit early from this
6210       // function if we encounter some other error.
6211     CoveredArgs.set(argIndex);
6212   }
6213 
6214   // Check the length modifier is valid with the given conversion specifier.
6215   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6216     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6217                                 diag::warn_format_nonsensical_length);
6218   else if (!FS.hasStandardLengthModifier())
6219     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6220   else if (!FS.hasStandardLengthConversionCombination())
6221     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6222                                 diag::warn_format_non_standard_conversion_spec);
6223 
6224   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6225     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6226 
6227   // The remaining checks depend on the data arguments.
6228   if (HasVAListArg)
6229     return true;
6230 
6231   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6232     return false;
6233 
6234   // Check that the argument type matches the format specifier.
6235   const Expr *Ex = getDataArg(argIndex);
6236   if (!Ex)
6237     return true;
6238 
6239   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6240 
6241   if (!AT.isValid()) {
6242     return true;
6243   }
6244 
6245   analyze_format_string::ArgType::MatchKind match =
6246       AT.matchesType(S.Context, Ex->getType());
6247   if (match == analyze_format_string::ArgType::Match) {
6248     return true;
6249   }
6250 
6251   ScanfSpecifier fixedFS = FS;
6252   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6253                                  S.getLangOpts(), S.Context);
6254 
6255   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6256   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6257     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6258   }
6259 
6260   if (success) {
6261     // Get the fix string from the fixed format specifier.
6262     SmallString<128> buf;
6263     llvm::raw_svector_ostream os(buf);
6264     fixedFS.toString(os);
6265 
6266     EmitFormatDiagnostic(
6267         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6268                       << Ex->getType() << false << Ex->getSourceRange(),
6269         Ex->getLocStart(),
6270         /*IsStringLocation*/ false,
6271         getSpecifierRange(startSpecifier, specifierLen),
6272         FixItHint::CreateReplacement(
6273             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6274   } else {
6275     EmitFormatDiagnostic(S.PDiag(diag)
6276                              << AT.getRepresentativeTypeName(S.Context)
6277                              << Ex->getType() << false << Ex->getSourceRange(),
6278                          Ex->getLocStart(),
6279                          /*IsStringLocation*/ false,
6280                          getSpecifierRange(startSpecifier, specifierLen));
6281   }
6282 
6283   return true;
6284 }
6285 
6286 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6287                               const Expr *OrigFormatExpr,
6288                               ArrayRef<const Expr *> Args,
6289                               bool HasVAListArg, unsigned format_idx,
6290                               unsigned firstDataArg,
6291                               Sema::FormatStringType Type,
6292                               bool inFunctionCall,
6293                               Sema::VariadicCallType CallType,
6294                               llvm::SmallBitVector &CheckedVarArgs,
6295                               UncoveredArgHandler &UncoveredArg) {
6296   // CHECK: is the format string a wide literal?
6297   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6298     CheckFormatHandler::EmitFormatDiagnostic(
6299       S, inFunctionCall, Args[format_idx],
6300       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6301       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6302     return;
6303   }
6304 
6305   // Str - The format string.  NOTE: this is NOT null-terminated!
6306   StringRef StrRef = FExpr->getString();
6307   const char *Str = StrRef.data();
6308   // Account for cases where the string literal is truncated in a declaration.
6309   const ConstantArrayType *T =
6310     S.Context.getAsConstantArrayType(FExpr->getType());
6311   assert(T && "String literal not of constant array type!");
6312   size_t TypeSize = T->getSize().getZExtValue();
6313   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6314   const unsigned numDataArgs = Args.size() - firstDataArg;
6315 
6316   // Emit a warning if the string literal is truncated and does not contain an
6317   // embedded null character.
6318   if (TypeSize <= StrRef.size() &&
6319       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6320     CheckFormatHandler::EmitFormatDiagnostic(
6321         S, inFunctionCall, Args[format_idx],
6322         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6323         FExpr->getLocStart(),
6324         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6325     return;
6326   }
6327 
6328   // CHECK: empty format string?
6329   if (StrLen == 0 && numDataArgs > 0) {
6330     CheckFormatHandler::EmitFormatDiagnostic(
6331       S, inFunctionCall, Args[format_idx],
6332       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6333       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6334     return;
6335   }
6336 
6337   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6338       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6339       Type == Sema::FST_OSTrace) {
6340     CheckPrintfHandler H(
6341         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6342         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6343         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6344         CheckedVarArgs, UncoveredArg);
6345 
6346     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6347                                                   S.getLangOpts(),
6348                                                   S.Context.getTargetInfo(),
6349                                             Type == Sema::FST_FreeBSDKPrintf))
6350       H.DoneProcessing();
6351   } else if (Type == Sema::FST_Scanf) {
6352     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6353                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6354                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6355 
6356     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6357                                                  S.getLangOpts(),
6358                                                  S.Context.getTargetInfo()))
6359       H.DoneProcessing();
6360   } // TODO: handle other formats
6361 }
6362 
6363 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6364   // Str - The format string.  NOTE: this is NOT null-terminated!
6365   StringRef StrRef = FExpr->getString();
6366   const char *Str = StrRef.data();
6367   // Account for cases where the string literal is truncated in a declaration.
6368   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6369   assert(T && "String literal not of constant array type!");
6370   size_t TypeSize = T->getSize().getZExtValue();
6371   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6372   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6373                                                          getLangOpts(),
6374                                                          Context.getTargetInfo());
6375 }
6376 
6377 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6378 
6379 // Returns the related absolute value function that is larger, of 0 if one
6380 // does not exist.
6381 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6382   switch (AbsFunction) {
6383   default:
6384     return 0;
6385 
6386   case Builtin::BI__builtin_abs:
6387     return Builtin::BI__builtin_labs;
6388   case Builtin::BI__builtin_labs:
6389     return Builtin::BI__builtin_llabs;
6390   case Builtin::BI__builtin_llabs:
6391     return 0;
6392 
6393   case Builtin::BI__builtin_fabsf:
6394     return Builtin::BI__builtin_fabs;
6395   case Builtin::BI__builtin_fabs:
6396     return Builtin::BI__builtin_fabsl;
6397   case Builtin::BI__builtin_fabsl:
6398     return 0;
6399 
6400   case Builtin::BI__builtin_cabsf:
6401     return Builtin::BI__builtin_cabs;
6402   case Builtin::BI__builtin_cabs:
6403     return Builtin::BI__builtin_cabsl;
6404   case Builtin::BI__builtin_cabsl:
6405     return 0;
6406 
6407   case Builtin::BIabs:
6408     return Builtin::BIlabs;
6409   case Builtin::BIlabs:
6410     return Builtin::BIllabs;
6411   case Builtin::BIllabs:
6412     return 0;
6413 
6414   case Builtin::BIfabsf:
6415     return Builtin::BIfabs;
6416   case Builtin::BIfabs:
6417     return Builtin::BIfabsl;
6418   case Builtin::BIfabsl:
6419     return 0;
6420 
6421   case Builtin::BIcabsf:
6422    return Builtin::BIcabs;
6423   case Builtin::BIcabs:
6424     return Builtin::BIcabsl;
6425   case Builtin::BIcabsl:
6426     return 0;
6427   }
6428 }
6429 
6430 // Returns the argument type of the absolute value function.
6431 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6432                                              unsigned AbsType) {
6433   if (AbsType == 0)
6434     return QualType();
6435 
6436   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6437   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6438   if (Error != ASTContext::GE_None)
6439     return QualType();
6440 
6441   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6442   if (!FT)
6443     return QualType();
6444 
6445   if (FT->getNumParams() != 1)
6446     return QualType();
6447 
6448   return FT->getParamType(0);
6449 }
6450 
6451 // Returns the best absolute value function, or zero, based on type and
6452 // current absolute value function.
6453 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6454                                    unsigned AbsFunctionKind) {
6455   unsigned BestKind = 0;
6456   uint64_t ArgSize = Context.getTypeSize(ArgType);
6457   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6458        Kind = getLargerAbsoluteValueFunction(Kind)) {
6459     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6460     if (Context.getTypeSize(ParamType) >= ArgSize) {
6461       if (BestKind == 0)
6462         BestKind = Kind;
6463       else if (Context.hasSameType(ParamType, ArgType)) {
6464         BestKind = Kind;
6465         break;
6466       }
6467     }
6468   }
6469   return BestKind;
6470 }
6471 
6472 enum AbsoluteValueKind {
6473   AVK_Integer,
6474   AVK_Floating,
6475   AVK_Complex
6476 };
6477 
6478 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6479   if (T->isIntegralOrEnumerationType())
6480     return AVK_Integer;
6481   if (T->isRealFloatingType())
6482     return AVK_Floating;
6483   if (T->isAnyComplexType())
6484     return AVK_Complex;
6485 
6486   llvm_unreachable("Type not integer, floating, or complex");
6487 }
6488 
6489 // Changes the absolute value function to a different type.  Preserves whether
6490 // the function is a builtin.
6491 static unsigned changeAbsFunction(unsigned AbsKind,
6492                                   AbsoluteValueKind ValueKind) {
6493   switch (ValueKind) {
6494   case AVK_Integer:
6495     switch (AbsKind) {
6496     default:
6497       return 0;
6498     case Builtin::BI__builtin_fabsf:
6499     case Builtin::BI__builtin_fabs:
6500     case Builtin::BI__builtin_fabsl:
6501     case Builtin::BI__builtin_cabsf:
6502     case Builtin::BI__builtin_cabs:
6503     case Builtin::BI__builtin_cabsl:
6504       return Builtin::BI__builtin_abs;
6505     case Builtin::BIfabsf:
6506     case Builtin::BIfabs:
6507     case Builtin::BIfabsl:
6508     case Builtin::BIcabsf:
6509     case Builtin::BIcabs:
6510     case Builtin::BIcabsl:
6511       return Builtin::BIabs;
6512     }
6513   case AVK_Floating:
6514     switch (AbsKind) {
6515     default:
6516       return 0;
6517     case Builtin::BI__builtin_abs:
6518     case Builtin::BI__builtin_labs:
6519     case Builtin::BI__builtin_llabs:
6520     case Builtin::BI__builtin_cabsf:
6521     case Builtin::BI__builtin_cabs:
6522     case Builtin::BI__builtin_cabsl:
6523       return Builtin::BI__builtin_fabsf;
6524     case Builtin::BIabs:
6525     case Builtin::BIlabs:
6526     case Builtin::BIllabs:
6527     case Builtin::BIcabsf:
6528     case Builtin::BIcabs:
6529     case Builtin::BIcabsl:
6530       return Builtin::BIfabsf;
6531     }
6532   case AVK_Complex:
6533     switch (AbsKind) {
6534     default:
6535       return 0;
6536     case Builtin::BI__builtin_abs:
6537     case Builtin::BI__builtin_labs:
6538     case Builtin::BI__builtin_llabs:
6539     case Builtin::BI__builtin_fabsf:
6540     case Builtin::BI__builtin_fabs:
6541     case Builtin::BI__builtin_fabsl:
6542       return Builtin::BI__builtin_cabsf;
6543     case Builtin::BIabs:
6544     case Builtin::BIlabs:
6545     case Builtin::BIllabs:
6546     case Builtin::BIfabsf:
6547     case Builtin::BIfabs:
6548     case Builtin::BIfabsl:
6549       return Builtin::BIcabsf;
6550     }
6551   }
6552   llvm_unreachable("Unable to convert function");
6553 }
6554 
6555 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6556   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6557   if (!FnInfo)
6558     return 0;
6559 
6560   switch (FDecl->getBuiltinID()) {
6561   default:
6562     return 0;
6563   case Builtin::BI__builtin_abs:
6564   case Builtin::BI__builtin_fabs:
6565   case Builtin::BI__builtin_fabsf:
6566   case Builtin::BI__builtin_fabsl:
6567   case Builtin::BI__builtin_labs:
6568   case Builtin::BI__builtin_llabs:
6569   case Builtin::BI__builtin_cabs:
6570   case Builtin::BI__builtin_cabsf:
6571   case Builtin::BI__builtin_cabsl:
6572   case Builtin::BIabs:
6573   case Builtin::BIlabs:
6574   case Builtin::BIllabs:
6575   case Builtin::BIfabs:
6576   case Builtin::BIfabsf:
6577   case Builtin::BIfabsl:
6578   case Builtin::BIcabs:
6579   case Builtin::BIcabsf:
6580   case Builtin::BIcabsl:
6581     return FDecl->getBuiltinID();
6582   }
6583   llvm_unreachable("Unknown Builtin type");
6584 }
6585 
6586 // If the replacement is valid, emit a note with replacement function.
6587 // Additionally, suggest including the proper header if not already included.
6588 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6589                             unsigned AbsKind, QualType ArgType) {
6590   bool EmitHeaderHint = true;
6591   const char *HeaderName = nullptr;
6592   const char *FunctionName = nullptr;
6593   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6594     FunctionName = "std::abs";
6595     if (ArgType->isIntegralOrEnumerationType()) {
6596       HeaderName = "cstdlib";
6597     } else if (ArgType->isRealFloatingType()) {
6598       HeaderName = "cmath";
6599     } else {
6600       llvm_unreachable("Invalid Type");
6601     }
6602 
6603     // Lookup all std::abs
6604     if (NamespaceDecl *Std = S.getStdNamespace()) {
6605       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6606       R.suppressDiagnostics();
6607       S.LookupQualifiedName(R, Std);
6608 
6609       for (const auto *I : R) {
6610         const FunctionDecl *FDecl = nullptr;
6611         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6612           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6613         } else {
6614           FDecl = dyn_cast<FunctionDecl>(I);
6615         }
6616         if (!FDecl)
6617           continue;
6618 
6619         // Found std::abs(), check that they are the right ones.
6620         if (FDecl->getNumParams() != 1)
6621           continue;
6622 
6623         // Check that the parameter type can handle the argument.
6624         QualType ParamType = FDecl->getParamDecl(0)->getType();
6625         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6626             S.Context.getTypeSize(ArgType) <=
6627                 S.Context.getTypeSize(ParamType)) {
6628           // Found a function, don't need the header hint.
6629           EmitHeaderHint = false;
6630           break;
6631         }
6632       }
6633     }
6634   } else {
6635     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6636     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6637 
6638     if (HeaderName) {
6639       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6640       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6641       R.suppressDiagnostics();
6642       S.LookupName(R, S.getCurScope());
6643 
6644       if (R.isSingleResult()) {
6645         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6646         if (FD && FD->getBuiltinID() == AbsKind) {
6647           EmitHeaderHint = false;
6648         } else {
6649           return;
6650         }
6651       } else if (!R.empty()) {
6652         return;
6653       }
6654     }
6655   }
6656 
6657   S.Diag(Loc, diag::note_replace_abs_function)
6658       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6659 
6660   if (!HeaderName)
6661     return;
6662 
6663   if (!EmitHeaderHint)
6664     return;
6665 
6666   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6667                                                     << FunctionName;
6668 }
6669 
6670 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6671   if (!FDecl)
6672     return false;
6673 
6674   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6675     return false;
6676 
6677   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6678 
6679   while (ND && ND->isInlineNamespace()) {
6680     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
6681   }
6682 
6683   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6684     return false;
6685 
6686   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6687     return false;
6688 
6689   return true;
6690 }
6691 
6692 // Warn when using the wrong abs() function.
6693 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6694                                       const FunctionDecl *FDecl,
6695                                       IdentifierInfo *FnInfo) {
6696   if (Call->getNumArgs() != 1)
6697     return;
6698 
6699   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6700   bool IsStdAbs = IsFunctionStdAbs(FDecl);
6701   if (AbsKind == 0 && !IsStdAbs)
6702     return;
6703 
6704   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6705   QualType ParamType = Call->getArg(0)->getType();
6706 
6707   // Unsigned types cannot be negative.  Suggest removing the absolute value
6708   // function call.
6709   if (ArgType->isUnsignedIntegerType()) {
6710     const char *FunctionName =
6711         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6712     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6713     Diag(Call->getExprLoc(), diag::note_remove_abs)
6714         << FunctionName
6715         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6716     return;
6717   }
6718 
6719   // Taking the absolute value of a pointer is very suspicious, they probably
6720   // wanted to index into an array, dereference a pointer, call a function, etc.
6721   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6722     unsigned DiagType = 0;
6723     if (ArgType->isFunctionType())
6724       DiagType = 1;
6725     else if (ArgType->isArrayType())
6726       DiagType = 2;
6727 
6728     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6729     return;
6730   }
6731 
6732   // std::abs has overloads which prevent most of the absolute value problems
6733   // from occurring.
6734   if (IsStdAbs)
6735     return;
6736 
6737   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6738   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6739 
6740   // The argument and parameter are the same kind.  Check if they are the right
6741   // size.
6742   if (ArgValueKind == ParamValueKind) {
6743     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6744       return;
6745 
6746     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6747     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6748         << FDecl << ArgType << ParamType;
6749 
6750     if (NewAbsKind == 0)
6751       return;
6752 
6753     emitReplacement(*this, Call->getExprLoc(),
6754                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6755     return;
6756   }
6757 
6758   // ArgValueKind != ParamValueKind
6759   // The wrong type of absolute value function was used.  Attempt to find the
6760   // proper one.
6761   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6762   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6763   if (NewAbsKind == 0)
6764     return;
6765 
6766   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6767       << FDecl << ParamValueKind << ArgValueKind;
6768 
6769   emitReplacement(*this, Call->getExprLoc(),
6770                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6771 }
6772 
6773 //===--- CHECK: Standard memory functions ---------------------------------===//
6774 
6775 /// \brief Takes the expression passed to the size_t parameter of functions
6776 /// such as memcmp, strncat, etc and warns if it's a comparison.
6777 ///
6778 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6779 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6780                                            IdentifierInfo *FnName,
6781                                            SourceLocation FnLoc,
6782                                            SourceLocation RParenLoc) {
6783   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6784   if (!Size)
6785     return false;
6786 
6787   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6788   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6789     return false;
6790 
6791   SourceRange SizeRange = Size->getSourceRange();
6792   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6793       << SizeRange << FnName;
6794   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6795       << FnName << FixItHint::CreateInsertion(
6796                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6797       << FixItHint::CreateRemoval(RParenLoc);
6798   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6799       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6800       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6801                                     ")");
6802 
6803   return true;
6804 }
6805 
6806 /// \brief Determine whether the given type is or contains a dynamic class type
6807 /// (e.g., whether it has a vtable).
6808 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6809                                                      bool &IsContained) {
6810   // Look through array types while ignoring qualifiers.
6811   const Type *Ty = T->getBaseElementTypeUnsafe();
6812   IsContained = false;
6813 
6814   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6815   RD = RD ? RD->getDefinition() : nullptr;
6816   if (!RD || RD->isInvalidDecl())
6817     return nullptr;
6818 
6819   if (RD->isDynamicClass())
6820     return RD;
6821 
6822   // Check all the fields.  If any bases were dynamic, the class is dynamic.
6823   // It's impossible for a class to transitively contain itself by value, so
6824   // infinite recursion is impossible.
6825   for (auto *FD : RD->fields()) {
6826     bool SubContained;
6827     if (const CXXRecordDecl *ContainedRD =
6828             getContainedDynamicClass(FD->getType(), SubContained)) {
6829       IsContained = true;
6830       return ContainedRD;
6831     }
6832   }
6833 
6834   return nullptr;
6835 }
6836 
6837 /// \brief If E is a sizeof expression, returns its argument expression,
6838 /// otherwise returns NULL.
6839 static const Expr *getSizeOfExprArg(const Expr *E) {
6840   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6841       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6842     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6843       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6844 
6845   return nullptr;
6846 }
6847 
6848 /// \brief If E is a sizeof expression, returns its argument type.
6849 static QualType getSizeOfArgType(const Expr *E) {
6850   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6851       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6852     if (SizeOf->getKind() == clang::UETT_SizeOf)
6853       return SizeOf->getTypeOfArgument();
6854 
6855   return QualType();
6856 }
6857 
6858 /// \brief Check for dangerous or invalid arguments to memset().
6859 ///
6860 /// This issues warnings on known problematic, dangerous or unspecified
6861 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6862 /// function calls.
6863 ///
6864 /// \param Call The call expression to diagnose.
6865 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6866                                    unsigned BId,
6867                                    IdentifierInfo *FnName) {
6868   assert(BId != 0);
6869 
6870   // It is possible to have a non-standard definition of memset.  Validate
6871   // we have enough arguments, and if not, abort further checking.
6872   unsigned ExpectedNumArgs =
6873       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6874   if (Call->getNumArgs() < ExpectedNumArgs)
6875     return;
6876 
6877   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6878                       BId == Builtin::BIstrndup ? 1 : 2);
6879   unsigned LenArg =
6880       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6881   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6882 
6883   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6884                                      Call->getLocStart(), Call->getRParenLoc()))
6885     return;
6886 
6887   // We have special checking when the length is a sizeof expression.
6888   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6889   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6890   llvm::FoldingSetNodeID SizeOfArgID;
6891 
6892   // Although widely used, 'bzero' is not a standard function. Be more strict
6893   // with the argument types before allowing diagnostics and only allow the
6894   // form bzero(ptr, sizeof(...)).
6895   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6896   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6897     return;
6898 
6899   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6900     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6901     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6902 
6903     QualType DestTy = Dest->getType();
6904     QualType PointeeTy;
6905     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6906       PointeeTy = DestPtrTy->getPointeeType();
6907 
6908       // Never warn about void type pointers. This can be used to suppress
6909       // false positives.
6910       if (PointeeTy->isVoidType())
6911         continue;
6912 
6913       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6914       // actually comparing the expressions for equality. Because computing the
6915       // expression IDs can be expensive, we only do this if the diagnostic is
6916       // enabled.
6917       if (SizeOfArg &&
6918           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6919                            SizeOfArg->getExprLoc())) {
6920         // We only compute IDs for expressions if the warning is enabled, and
6921         // cache the sizeof arg's ID.
6922         if (SizeOfArgID == llvm::FoldingSetNodeID())
6923           SizeOfArg->Profile(SizeOfArgID, Context, true);
6924         llvm::FoldingSetNodeID DestID;
6925         Dest->Profile(DestID, Context, true);
6926         if (DestID == SizeOfArgID) {
6927           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6928           //       over sizeof(src) as well.
6929           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6930           StringRef ReadableName = FnName->getName();
6931 
6932           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6933             if (UnaryOp->getOpcode() == UO_AddrOf)
6934               ActionIdx = 1; // If its an address-of operator, just remove it.
6935           if (!PointeeTy->isIncompleteType() &&
6936               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6937             ActionIdx = 2; // If the pointee's size is sizeof(char),
6938                            // suggest an explicit length.
6939 
6940           // If the function is defined as a builtin macro, do not show macro
6941           // expansion.
6942           SourceLocation SL = SizeOfArg->getExprLoc();
6943           SourceRange DSR = Dest->getSourceRange();
6944           SourceRange SSR = SizeOfArg->getSourceRange();
6945           SourceManager &SM = getSourceManager();
6946 
6947           if (SM.isMacroArgExpansion(SL)) {
6948             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6949             SL = SM.getSpellingLoc(SL);
6950             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6951                              SM.getSpellingLoc(DSR.getEnd()));
6952             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6953                              SM.getSpellingLoc(SSR.getEnd()));
6954           }
6955 
6956           DiagRuntimeBehavior(SL, SizeOfArg,
6957                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6958                                 << ReadableName
6959                                 << PointeeTy
6960                                 << DestTy
6961                                 << DSR
6962                                 << SSR);
6963           DiagRuntimeBehavior(SL, SizeOfArg,
6964                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6965                                 << ActionIdx
6966                                 << SSR);
6967 
6968           break;
6969         }
6970       }
6971 
6972       // Also check for cases where the sizeof argument is the exact same
6973       // type as the memory argument, and where it points to a user-defined
6974       // record type.
6975       if (SizeOfArgTy != QualType()) {
6976         if (PointeeTy->isRecordType() &&
6977             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6978           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6979                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
6980                                 << FnName << SizeOfArgTy << ArgIdx
6981                                 << PointeeTy << Dest->getSourceRange()
6982                                 << LenExpr->getSourceRange());
6983           break;
6984         }
6985       }
6986     } else if (DestTy->isArrayType()) {
6987       PointeeTy = DestTy;
6988     }
6989 
6990     if (PointeeTy == QualType())
6991       continue;
6992 
6993     // Always complain about dynamic classes.
6994     bool IsContained;
6995     if (const CXXRecordDecl *ContainedRD =
6996             getContainedDynamicClass(PointeeTy, IsContained)) {
6997 
6998       unsigned OperationType = 0;
6999       // "overwritten" if we're warning about the destination for any call
7000       // but memcmp; otherwise a verb appropriate to the call.
7001       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7002         if (BId == Builtin::BImemcpy)
7003           OperationType = 1;
7004         else if(BId == Builtin::BImemmove)
7005           OperationType = 2;
7006         else if (BId == Builtin::BImemcmp)
7007           OperationType = 3;
7008       }
7009 
7010       DiagRuntimeBehavior(
7011         Dest->getExprLoc(), Dest,
7012         PDiag(diag::warn_dyn_class_memaccess)
7013           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7014           << FnName << IsContained << ContainedRD << OperationType
7015           << Call->getCallee()->getSourceRange());
7016     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7017              BId != Builtin::BImemset)
7018       DiagRuntimeBehavior(
7019         Dest->getExprLoc(), Dest,
7020         PDiag(diag::warn_arc_object_memaccess)
7021           << ArgIdx << FnName << PointeeTy
7022           << Call->getCallee()->getSourceRange());
7023     else
7024       continue;
7025 
7026     DiagRuntimeBehavior(
7027       Dest->getExprLoc(), Dest,
7028       PDiag(diag::note_bad_memaccess_silence)
7029         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7030     break;
7031   }
7032 }
7033 
7034 // A little helper routine: ignore addition and subtraction of integer literals.
7035 // This intentionally does not ignore all integer constant expressions because
7036 // we don't want to remove sizeof().
7037 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7038   Ex = Ex->IgnoreParenCasts();
7039 
7040   for (;;) {
7041     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7042     if (!BO || !BO->isAdditiveOp())
7043       break;
7044 
7045     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7046     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7047 
7048     if (isa<IntegerLiteral>(RHS))
7049       Ex = LHS;
7050     else if (isa<IntegerLiteral>(LHS))
7051       Ex = RHS;
7052     else
7053       break;
7054   }
7055 
7056   return Ex;
7057 }
7058 
7059 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7060                                                       ASTContext &Context) {
7061   // Only handle constant-sized or VLAs, but not flexible members.
7062   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7063     // Only issue the FIXIT for arrays of size > 1.
7064     if (CAT->getSize().getSExtValue() <= 1)
7065       return false;
7066   } else if (!Ty->isVariableArrayType()) {
7067     return false;
7068   }
7069   return true;
7070 }
7071 
7072 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7073 // be the size of the source, instead of the destination.
7074 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7075                                     IdentifierInfo *FnName) {
7076 
7077   // Don't crash if the user has the wrong number of arguments
7078   unsigned NumArgs = Call->getNumArgs();
7079   if ((NumArgs != 3) && (NumArgs != 4))
7080     return;
7081 
7082   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7083   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7084   const Expr *CompareWithSrc = nullptr;
7085 
7086   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7087                                      Call->getLocStart(), Call->getRParenLoc()))
7088     return;
7089 
7090   // Look for 'strlcpy(dst, x, sizeof(x))'
7091   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7092     CompareWithSrc = Ex;
7093   else {
7094     // Look for 'strlcpy(dst, x, strlen(x))'
7095     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7096       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7097           SizeCall->getNumArgs() == 1)
7098         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7099     }
7100   }
7101 
7102   if (!CompareWithSrc)
7103     return;
7104 
7105   // Determine if the argument to sizeof/strlen is equal to the source
7106   // argument.  In principle there's all kinds of things you could do
7107   // here, for instance creating an == expression and evaluating it with
7108   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7109   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7110   if (!SrcArgDRE)
7111     return;
7112 
7113   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7114   if (!CompareWithSrcDRE ||
7115       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7116     return;
7117 
7118   const Expr *OriginalSizeArg = Call->getArg(2);
7119   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7120     << OriginalSizeArg->getSourceRange() << FnName;
7121 
7122   // Output a FIXIT hint if the destination is an array (rather than a
7123   // pointer to an array).  This could be enhanced to handle some
7124   // pointers if we know the actual size, like if DstArg is 'array+2'
7125   // we could say 'sizeof(array)-2'.
7126   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7127   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7128     return;
7129 
7130   SmallString<128> sizeString;
7131   llvm::raw_svector_ostream OS(sizeString);
7132   OS << "sizeof(";
7133   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7134   OS << ")";
7135 
7136   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7137     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7138                                     OS.str());
7139 }
7140 
7141 /// Check if two expressions refer to the same declaration.
7142 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7143   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7144     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7145       return D1->getDecl() == D2->getDecl();
7146   return false;
7147 }
7148 
7149 static const Expr *getStrlenExprArg(const Expr *E) {
7150   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7151     const FunctionDecl *FD = CE->getDirectCallee();
7152     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7153       return nullptr;
7154     return CE->getArg(0)->IgnoreParenCasts();
7155   }
7156   return nullptr;
7157 }
7158 
7159 // Warn on anti-patterns as the 'size' argument to strncat.
7160 // The correct size argument should look like following:
7161 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7162 void Sema::CheckStrncatArguments(const CallExpr *CE,
7163                                  IdentifierInfo *FnName) {
7164   // Don't crash if the user has the wrong number of arguments.
7165   if (CE->getNumArgs() < 3)
7166     return;
7167   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7168   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7169   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7170 
7171   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7172                                      CE->getRParenLoc()))
7173     return;
7174 
7175   // Identify common expressions, which are wrongly used as the size argument
7176   // to strncat and may lead to buffer overflows.
7177   unsigned PatternType = 0;
7178   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7179     // - sizeof(dst)
7180     if (referToTheSameDecl(SizeOfArg, DstArg))
7181       PatternType = 1;
7182     // - sizeof(src)
7183     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7184       PatternType = 2;
7185   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7186     if (BE->getOpcode() == BO_Sub) {
7187       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7188       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7189       // - sizeof(dst) - strlen(dst)
7190       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7191           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7192         PatternType = 1;
7193       // - sizeof(src) - (anything)
7194       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7195         PatternType = 2;
7196     }
7197   }
7198 
7199   if (PatternType == 0)
7200     return;
7201 
7202   // Generate the diagnostic.
7203   SourceLocation SL = LenArg->getLocStart();
7204   SourceRange SR = LenArg->getSourceRange();
7205   SourceManager &SM = getSourceManager();
7206 
7207   // If the function is defined as a builtin macro, do not show macro expansion.
7208   if (SM.isMacroArgExpansion(SL)) {
7209     SL = SM.getSpellingLoc(SL);
7210     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7211                      SM.getSpellingLoc(SR.getEnd()));
7212   }
7213 
7214   // Check if the destination is an array (rather than a pointer to an array).
7215   QualType DstTy = DstArg->getType();
7216   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7217                                                                     Context);
7218   if (!isKnownSizeArray) {
7219     if (PatternType == 1)
7220       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7221     else
7222       Diag(SL, diag::warn_strncat_src_size) << SR;
7223     return;
7224   }
7225 
7226   if (PatternType == 1)
7227     Diag(SL, diag::warn_strncat_large_size) << SR;
7228   else
7229     Diag(SL, diag::warn_strncat_src_size) << SR;
7230 
7231   SmallString<128> sizeString;
7232   llvm::raw_svector_ostream OS(sizeString);
7233   OS << "sizeof(";
7234   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7235   OS << ") - ";
7236   OS << "strlen(";
7237   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7238   OS << ") - 1";
7239 
7240   Diag(SL, diag::note_strncat_wrong_size)
7241     << FixItHint::CreateReplacement(SR, OS.str());
7242 }
7243 
7244 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7245 
7246 static const Expr *EvalVal(const Expr *E,
7247                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7248                            const Decl *ParentDecl);
7249 static const Expr *EvalAddr(const Expr *E,
7250                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7251                             const Decl *ParentDecl);
7252 
7253 /// CheckReturnStackAddr - Check if a return statement returns the address
7254 ///   of a stack variable.
7255 static void
7256 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7257                      SourceLocation ReturnLoc) {
7258 
7259   const Expr *stackE = nullptr;
7260   SmallVector<const DeclRefExpr *, 8> refVars;
7261 
7262   // Perform checking for returned stack addresses, local blocks,
7263   // label addresses or references to temporaries.
7264   if (lhsType->isPointerType() ||
7265       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7266     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7267   } else if (lhsType->isReferenceType()) {
7268     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7269   }
7270 
7271   if (!stackE)
7272     return; // Nothing suspicious was found.
7273 
7274   // Parameters are initalized in the calling scope, so taking the address
7275   // of a parameter reference doesn't need a warning.
7276   for (auto *DRE : refVars)
7277     if (isa<ParmVarDecl>(DRE->getDecl()))
7278       return;
7279 
7280   SourceLocation diagLoc;
7281   SourceRange diagRange;
7282   if (refVars.empty()) {
7283     diagLoc = stackE->getLocStart();
7284     diagRange = stackE->getSourceRange();
7285   } else {
7286     // We followed through a reference variable. 'stackE' contains the
7287     // problematic expression but we will warn at the return statement pointing
7288     // at the reference variable. We will later display the "trail" of
7289     // reference variables using notes.
7290     diagLoc = refVars[0]->getLocStart();
7291     diagRange = refVars[0]->getSourceRange();
7292   }
7293 
7294   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7295     // address of local var
7296     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7297      << DR->getDecl()->getDeclName() << diagRange;
7298   } else if (isa<BlockExpr>(stackE)) { // local block.
7299     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7300   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7301     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7302   } else { // local temporary.
7303     // If there is an LValue->RValue conversion, then the value of the
7304     // reference type is used, not the reference.
7305     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7306       if (ICE->getCastKind() == CK_LValueToRValue) {
7307         return;
7308       }
7309     }
7310     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7311      << lhsType->isReferenceType() << diagRange;
7312   }
7313 
7314   // Display the "trail" of reference variables that we followed until we
7315   // found the problematic expression using notes.
7316   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7317     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7318     // If this var binds to another reference var, show the range of the next
7319     // var, otherwise the var binds to the problematic expression, in which case
7320     // show the range of the expression.
7321     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7322                                     : stackE->getSourceRange();
7323     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7324         << VD->getDeclName() << range;
7325   }
7326 }
7327 
7328 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7329 ///  check if the expression in a return statement evaluates to an address
7330 ///  to a location on the stack, a local block, an address of a label, or a
7331 ///  reference to local temporary. The recursion is used to traverse the
7332 ///  AST of the return expression, with recursion backtracking when we
7333 ///  encounter a subexpression that (1) clearly does not lead to one of the
7334 ///  above problematic expressions (2) is something we cannot determine leads to
7335 ///  a problematic expression based on such local checking.
7336 ///
7337 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7338 ///  the expression that they point to. Such variables are added to the
7339 ///  'refVars' vector so that we know what the reference variable "trail" was.
7340 ///
7341 ///  EvalAddr processes expressions that are pointers that are used as
7342 ///  references (and not L-values).  EvalVal handles all other values.
7343 ///  At the base case of the recursion is a check for the above problematic
7344 ///  expressions.
7345 ///
7346 ///  This implementation handles:
7347 ///
7348 ///   * pointer-to-pointer casts
7349 ///   * implicit conversions from array references to pointers
7350 ///   * taking the address of fields
7351 ///   * arbitrary interplay between "&" and "*" operators
7352 ///   * pointer arithmetic from an address of a stack variable
7353 ///   * taking the address of an array element where the array is on the stack
7354 static const Expr *EvalAddr(const Expr *E,
7355                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7356                             const Decl *ParentDecl) {
7357   if (E->isTypeDependent())
7358     return nullptr;
7359 
7360   // We should only be called for evaluating pointer expressions.
7361   assert((E->getType()->isAnyPointerType() ||
7362           E->getType()->isBlockPointerType() ||
7363           E->getType()->isObjCQualifiedIdType()) &&
7364          "EvalAddr only works on pointers");
7365 
7366   E = E->IgnoreParens();
7367 
7368   // Our "symbolic interpreter" is just a dispatch off the currently
7369   // viewed AST node.  We then recursively traverse the AST by calling
7370   // EvalAddr and EvalVal appropriately.
7371   switch (E->getStmtClass()) {
7372   case Stmt::DeclRefExprClass: {
7373     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7374 
7375     // If we leave the immediate function, the lifetime isn't about to end.
7376     if (DR->refersToEnclosingVariableOrCapture())
7377       return nullptr;
7378 
7379     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7380       // If this is a reference variable, follow through to the expression that
7381       // it points to.
7382       if (V->hasLocalStorage() &&
7383           V->getType()->isReferenceType() && V->hasInit()) {
7384         // Add the reference variable to the "trail".
7385         refVars.push_back(DR);
7386         return EvalAddr(V->getInit(), refVars, ParentDecl);
7387       }
7388 
7389     return nullptr;
7390   }
7391 
7392   case Stmt::UnaryOperatorClass: {
7393     // The only unary operator that make sense to handle here
7394     // is AddrOf.  All others don't make sense as pointers.
7395     const UnaryOperator *U = cast<UnaryOperator>(E);
7396 
7397     if (U->getOpcode() == UO_AddrOf)
7398       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7399     return nullptr;
7400   }
7401 
7402   case Stmt::BinaryOperatorClass: {
7403     // Handle pointer arithmetic.  All other binary operators are not valid
7404     // in this context.
7405     const BinaryOperator *B = cast<BinaryOperator>(E);
7406     BinaryOperatorKind op = B->getOpcode();
7407 
7408     if (op != BO_Add && op != BO_Sub)
7409       return nullptr;
7410 
7411     const Expr *Base = B->getLHS();
7412 
7413     // Determine which argument is the real pointer base.  It could be
7414     // the RHS argument instead of the LHS.
7415     if (!Base->getType()->isPointerType())
7416       Base = B->getRHS();
7417 
7418     assert(Base->getType()->isPointerType());
7419     return EvalAddr(Base, refVars, ParentDecl);
7420   }
7421 
7422   // For conditional operators we need to see if either the LHS or RHS are
7423   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7424   case Stmt::ConditionalOperatorClass: {
7425     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7426 
7427     // Handle the GNU extension for missing LHS.
7428     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7429     if (const Expr *LHSExpr = C->getLHS()) {
7430       // In C++, we can have a throw-expression, which has 'void' type.
7431       if (!LHSExpr->getType()->isVoidType())
7432         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7433           return LHS;
7434     }
7435 
7436     // In C++, we can have a throw-expression, which has 'void' type.
7437     if (C->getRHS()->getType()->isVoidType())
7438       return nullptr;
7439 
7440     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7441   }
7442 
7443   case Stmt::BlockExprClass:
7444     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7445       return E; // local block.
7446     return nullptr;
7447 
7448   case Stmt::AddrLabelExprClass:
7449     return E; // address of label.
7450 
7451   case Stmt::ExprWithCleanupsClass:
7452     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7453                     ParentDecl);
7454 
7455   // For casts, we need to handle conversions from arrays to
7456   // pointer values, and pointer-to-pointer conversions.
7457   case Stmt::ImplicitCastExprClass:
7458   case Stmt::CStyleCastExprClass:
7459   case Stmt::CXXFunctionalCastExprClass:
7460   case Stmt::ObjCBridgedCastExprClass:
7461   case Stmt::CXXStaticCastExprClass:
7462   case Stmt::CXXDynamicCastExprClass:
7463   case Stmt::CXXConstCastExprClass:
7464   case Stmt::CXXReinterpretCastExprClass: {
7465     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7466     switch (cast<CastExpr>(E)->getCastKind()) {
7467     case CK_LValueToRValue:
7468     case CK_NoOp:
7469     case CK_BaseToDerived:
7470     case CK_DerivedToBase:
7471     case CK_UncheckedDerivedToBase:
7472     case CK_Dynamic:
7473     case CK_CPointerToObjCPointerCast:
7474     case CK_BlockPointerToObjCPointerCast:
7475     case CK_AnyPointerToBlockPointerCast:
7476       return EvalAddr(SubExpr, refVars, ParentDecl);
7477 
7478     case CK_ArrayToPointerDecay:
7479       return EvalVal(SubExpr, refVars, ParentDecl);
7480 
7481     case CK_BitCast:
7482       if (SubExpr->getType()->isAnyPointerType() ||
7483           SubExpr->getType()->isBlockPointerType() ||
7484           SubExpr->getType()->isObjCQualifiedIdType())
7485         return EvalAddr(SubExpr, refVars, ParentDecl);
7486       else
7487         return nullptr;
7488 
7489     default:
7490       return nullptr;
7491     }
7492   }
7493 
7494   case Stmt::MaterializeTemporaryExprClass:
7495     if (const Expr *Result =
7496             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7497                      refVars, ParentDecl))
7498       return Result;
7499     return E;
7500 
7501   // Everything else: we simply don't reason about them.
7502   default:
7503     return nullptr;
7504   }
7505 }
7506 
7507 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7508 ///   See the comments for EvalAddr for more details.
7509 static const Expr *EvalVal(const Expr *E,
7510                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7511                            const Decl *ParentDecl) {
7512   do {
7513     // We should only be called for evaluating non-pointer expressions, or
7514     // expressions with a pointer type that are not used as references but
7515     // instead
7516     // are l-values (e.g., DeclRefExpr with a pointer type).
7517 
7518     // Our "symbolic interpreter" is just a dispatch off the currently
7519     // viewed AST node.  We then recursively traverse the AST by calling
7520     // EvalAddr and EvalVal appropriately.
7521 
7522     E = E->IgnoreParens();
7523     switch (E->getStmtClass()) {
7524     case Stmt::ImplicitCastExprClass: {
7525       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7526       if (IE->getValueKind() == VK_LValue) {
7527         E = IE->getSubExpr();
7528         continue;
7529       }
7530       return nullptr;
7531     }
7532 
7533     case Stmt::ExprWithCleanupsClass:
7534       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7535                      ParentDecl);
7536 
7537     case Stmt::DeclRefExprClass: {
7538       // When we hit a DeclRefExpr we are looking at code that refers to a
7539       // variable's name. If it's not a reference variable we check if it has
7540       // local storage within the function, and if so, return the expression.
7541       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7542 
7543       // If we leave the immediate function, the lifetime isn't about to end.
7544       if (DR->refersToEnclosingVariableOrCapture())
7545         return nullptr;
7546 
7547       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7548         // Check if it refers to itself, e.g. "int& i = i;".
7549         if (V == ParentDecl)
7550           return DR;
7551 
7552         if (V->hasLocalStorage()) {
7553           if (!V->getType()->isReferenceType())
7554             return DR;
7555 
7556           // Reference variable, follow through to the expression that
7557           // it points to.
7558           if (V->hasInit()) {
7559             // Add the reference variable to the "trail".
7560             refVars.push_back(DR);
7561             return EvalVal(V->getInit(), refVars, V);
7562           }
7563         }
7564       }
7565 
7566       return nullptr;
7567     }
7568 
7569     case Stmt::UnaryOperatorClass: {
7570       // The only unary operator that make sense to handle here
7571       // is Deref.  All others don't resolve to a "name."  This includes
7572       // handling all sorts of rvalues passed to a unary operator.
7573       const UnaryOperator *U = cast<UnaryOperator>(E);
7574 
7575       if (U->getOpcode() == UO_Deref)
7576         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7577 
7578       return nullptr;
7579     }
7580 
7581     case Stmt::ArraySubscriptExprClass: {
7582       // Array subscripts are potential references to data on the stack.  We
7583       // retrieve the DeclRefExpr* for the array variable if it indeed
7584       // has local storage.
7585       const auto *ASE = cast<ArraySubscriptExpr>(E);
7586       if (ASE->isTypeDependent())
7587         return nullptr;
7588       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7589     }
7590 
7591     case Stmt::OMPArraySectionExprClass: {
7592       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7593                       ParentDecl);
7594     }
7595 
7596     case Stmt::ConditionalOperatorClass: {
7597       // For conditional operators we need to see if either the LHS or RHS are
7598       // non-NULL Expr's.  If one is non-NULL, we return it.
7599       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7600 
7601       // Handle the GNU extension for missing LHS.
7602       if (const Expr *LHSExpr = C->getLHS()) {
7603         // In C++, we can have a throw-expression, which has 'void' type.
7604         if (!LHSExpr->getType()->isVoidType())
7605           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7606             return LHS;
7607       }
7608 
7609       // In C++, we can have a throw-expression, which has 'void' type.
7610       if (C->getRHS()->getType()->isVoidType())
7611         return nullptr;
7612 
7613       return EvalVal(C->getRHS(), refVars, ParentDecl);
7614     }
7615 
7616     // Accesses to members are potential references to data on the stack.
7617     case Stmt::MemberExprClass: {
7618       const MemberExpr *M = cast<MemberExpr>(E);
7619 
7620       // Check for indirect access.  We only want direct field accesses.
7621       if (M->isArrow())
7622         return nullptr;
7623 
7624       // Check whether the member type is itself a reference, in which case
7625       // we're not going to refer to the member, but to what the member refers
7626       // to.
7627       if (M->getMemberDecl()->getType()->isReferenceType())
7628         return nullptr;
7629 
7630       return EvalVal(M->getBase(), refVars, ParentDecl);
7631     }
7632 
7633     case Stmt::MaterializeTemporaryExprClass:
7634       if (const Expr *Result =
7635               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7636                       refVars, ParentDecl))
7637         return Result;
7638       return E;
7639 
7640     default:
7641       // Check that we don't return or take the address of a reference to a
7642       // temporary. This is only useful in C++.
7643       if (!E->isTypeDependent() && E->isRValue())
7644         return E;
7645 
7646       // Everything else: we simply don't reason about them.
7647       return nullptr;
7648     }
7649   } while (true);
7650 }
7651 
7652 void
7653 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7654                          SourceLocation ReturnLoc,
7655                          bool isObjCMethod,
7656                          const AttrVec *Attrs,
7657                          const FunctionDecl *FD) {
7658   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7659 
7660   // Check if the return value is null but should not be.
7661   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7662        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7663       CheckNonNullExpr(*this, RetValExp))
7664     Diag(ReturnLoc, diag::warn_null_ret)
7665       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7666 
7667   // C++11 [basic.stc.dynamic.allocation]p4:
7668   //   If an allocation function declared with a non-throwing
7669   //   exception-specification fails to allocate storage, it shall return
7670   //   a null pointer. Any other allocation function that fails to allocate
7671   //   storage shall indicate failure only by throwing an exception [...]
7672   if (FD) {
7673     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7674     if (Op == OO_New || Op == OO_Array_New) {
7675       const FunctionProtoType *Proto
7676         = FD->getType()->castAs<FunctionProtoType>();
7677       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7678           CheckNonNullExpr(*this, RetValExp))
7679         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7680           << FD << getLangOpts().CPlusPlus11;
7681     }
7682   }
7683 }
7684 
7685 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7686 
7687 /// Check for comparisons of floating point operands using != and ==.
7688 /// Issue a warning if these are no self-comparisons, as they are not likely
7689 /// to do what the programmer intended.
7690 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7691   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7692   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7693 
7694   // Special case: check for x == x (which is OK).
7695   // Do not emit warnings for such cases.
7696   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7697     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7698       if (DRL->getDecl() == DRR->getDecl())
7699         return;
7700 
7701   // Special case: check for comparisons against literals that can be exactly
7702   //  represented by APFloat.  In such cases, do not emit a warning.  This
7703   //  is a heuristic: often comparison against such literals are used to
7704   //  detect if a value in a variable has not changed.  This clearly can
7705   //  lead to false negatives.
7706   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7707     if (FLL->isExact())
7708       return;
7709   } else
7710     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7711       if (FLR->isExact())
7712         return;
7713 
7714   // Check for comparisons with builtin types.
7715   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7716     if (CL->getBuiltinCallee())
7717       return;
7718 
7719   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7720     if (CR->getBuiltinCallee())
7721       return;
7722 
7723   // Emit the diagnostic.
7724   Diag(Loc, diag::warn_floatingpoint_eq)
7725     << LHS->getSourceRange() << RHS->getSourceRange();
7726 }
7727 
7728 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7729 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7730 
7731 namespace {
7732 
7733 /// Structure recording the 'active' range of an integer-valued
7734 /// expression.
7735 struct IntRange {
7736   /// The number of bits active in the int.
7737   unsigned Width;
7738 
7739   /// True if the int is known not to have negative values.
7740   bool NonNegative;
7741 
7742   IntRange(unsigned Width, bool NonNegative)
7743     : Width(Width), NonNegative(NonNegative)
7744   {}
7745 
7746   /// Returns the range of the bool type.
7747   static IntRange forBoolType() {
7748     return IntRange(1, true);
7749   }
7750 
7751   /// Returns the range of an opaque value of the given integral type.
7752   static IntRange forValueOfType(ASTContext &C, QualType T) {
7753     return forValueOfCanonicalType(C,
7754                           T->getCanonicalTypeInternal().getTypePtr());
7755   }
7756 
7757   /// Returns the range of an opaque value of a canonical integral type.
7758   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7759     assert(T->isCanonicalUnqualified());
7760 
7761     if (const VectorType *VT = dyn_cast<VectorType>(T))
7762       T = VT->getElementType().getTypePtr();
7763     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7764       T = CT->getElementType().getTypePtr();
7765     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7766       T = AT->getValueType().getTypePtr();
7767 
7768     // For enum types, use the known bit width of the enumerators.
7769     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7770       EnumDecl *Enum = ET->getDecl();
7771       if (!Enum->isCompleteDefinition())
7772         return IntRange(C.getIntWidth(QualType(T, 0)), false);
7773 
7774       unsigned NumPositive = Enum->getNumPositiveBits();
7775       unsigned NumNegative = Enum->getNumNegativeBits();
7776 
7777       if (NumNegative == 0)
7778         return IntRange(NumPositive, true/*NonNegative*/);
7779       else
7780         return IntRange(std::max(NumPositive + 1, NumNegative),
7781                         false/*NonNegative*/);
7782     }
7783 
7784     const BuiltinType *BT = cast<BuiltinType>(T);
7785     assert(BT->isInteger());
7786 
7787     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7788   }
7789 
7790   /// Returns the "target" range of a canonical integral type, i.e.
7791   /// the range of values expressible in the type.
7792   ///
7793   /// This matches forValueOfCanonicalType except that enums have the
7794   /// full range of their type, not the range of their enumerators.
7795   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7796     assert(T->isCanonicalUnqualified());
7797 
7798     if (const VectorType *VT = dyn_cast<VectorType>(T))
7799       T = VT->getElementType().getTypePtr();
7800     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7801       T = CT->getElementType().getTypePtr();
7802     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7803       T = AT->getValueType().getTypePtr();
7804     if (const EnumType *ET = dyn_cast<EnumType>(T))
7805       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7806 
7807     const BuiltinType *BT = cast<BuiltinType>(T);
7808     assert(BT->isInteger());
7809 
7810     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7811   }
7812 
7813   /// Returns the supremum of two ranges: i.e. their conservative merge.
7814   static IntRange join(IntRange L, IntRange R) {
7815     return IntRange(std::max(L.Width, R.Width),
7816                     L.NonNegative && R.NonNegative);
7817   }
7818 
7819   /// Returns the infinum of two ranges: i.e. their aggressive merge.
7820   static IntRange meet(IntRange L, IntRange R) {
7821     return IntRange(std::min(L.Width, R.Width),
7822                     L.NonNegative || R.NonNegative);
7823   }
7824 };
7825 
7826 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7827   if (value.isSigned() && value.isNegative())
7828     return IntRange(value.getMinSignedBits(), false);
7829 
7830   if (value.getBitWidth() > MaxWidth)
7831     value = value.trunc(MaxWidth);
7832 
7833   // isNonNegative() just checks the sign bit without considering
7834   // signedness.
7835   return IntRange(value.getActiveBits(), true);
7836 }
7837 
7838 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7839                        unsigned MaxWidth) {
7840   if (result.isInt())
7841     return GetValueRange(C, result.getInt(), MaxWidth);
7842 
7843   if (result.isVector()) {
7844     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7845     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7846       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7847       R = IntRange::join(R, El);
7848     }
7849     return R;
7850   }
7851 
7852   if (result.isComplexInt()) {
7853     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7854     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7855     return IntRange::join(R, I);
7856   }
7857 
7858   // This can happen with lossless casts to intptr_t of "based" lvalues.
7859   // Assume it might use arbitrary bits.
7860   // FIXME: The only reason we need to pass the type in here is to get
7861   // the sign right on this one case.  It would be nice if APValue
7862   // preserved this.
7863   assert(result.isLValue() || result.isAddrLabelDiff());
7864   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7865 }
7866 
7867 QualType GetExprType(const Expr *E) {
7868   QualType Ty = E->getType();
7869   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7870     Ty = AtomicRHS->getValueType();
7871   return Ty;
7872 }
7873 
7874 /// Pseudo-evaluate the given integer expression, estimating the
7875 /// range of values it might take.
7876 ///
7877 /// \param MaxWidth - the width to which the value will be truncated
7878 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7879   E = E->IgnoreParens();
7880 
7881   // Try a full evaluation first.
7882   Expr::EvalResult result;
7883   if (E->EvaluateAsRValue(result, C))
7884     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7885 
7886   // I think we only want to look through implicit casts here; if the
7887   // user has an explicit widening cast, we should treat the value as
7888   // being of the new, wider type.
7889   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7890     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7891       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7892 
7893     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7894 
7895     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7896                          CE->getCastKind() == CK_BooleanToSignedIntegral;
7897 
7898     // Assume that non-integer casts can span the full range of the type.
7899     if (!isIntegerCast)
7900       return OutputTypeRange;
7901 
7902     IntRange SubRange
7903       = GetExprRange(C, CE->getSubExpr(),
7904                      std::min(MaxWidth, OutputTypeRange.Width));
7905 
7906     // Bail out if the subexpr's range is as wide as the cast type.
7907     if (SubRange.Width >= OutputTypeRange.Width)
7908       return OutputTypeRange;
7909 
7910     // Otherwise, we take the smaller width, and we're non-negative if
7911     // either the output type or the subexpr is.
7912     return IntRange(SubRange.Width,
7913                     SubRange.NonNegative || OutputTypeRange.NonNegative);
7914   }
7915 
7916   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7917     // If we can fold the condition, just take that operand.
7918     bool CondResult;
7919     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7920       return GetExprRange(C, CondResult ? CO->getTrueExpr()
7921                                         : CO->getFalseExpr(),
7922                           MaxWidth);
7923 
7924     // Otherwise, conservatively merge.
7925     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7926     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7927     return IntRange::join(L, R);
7928   }
7929 
7930   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7931     switch (BO->getOpcode()) {
7932 
7933     // Boolean-valued operations are single-bit and positive.
7934     case BO_LAnd:
7935     case BO_LOr:
7936     case BO_LT:
7937     case BO_GT:
7938     case BO_LE:
7939     case BO_GE:
7940     case BO_EQ:
7941     case BO_NE:
7942       return IntRange::forBoolType();
7943 
7944     // The type of the assignments is the type of the LHS, so the RHS
7945     // is not necessarily the same type.
7946     case BO_MulAssign:
7947     case BO_DivAssign:
7948     case BO_RemAssign:
7949     case BO_AddAssign:
7950     case BO_SubAssign:
7951     case BO_XorAssign:
7952     case BO_OrAssign:
7953       // TODO: bitfields?
7954       return IntRange::forValueOfType(C, GetExprType(E));
7955 
7956     // Simple assignments just pass through the RHS, which will have
7957     // been coerced to the LHS type.
7958     case BO_Assign:
7959       // TODO: bitfields?
7960       return GetExprRange(C, BO->getRHS(), MaxWidth);
7961 
7962     // Operations with opaque sources are black-listed.
7963     case BO_PtrMemD:
7964     case BO_PtrMemI:
7965       return IntRange::forValueOfType(C, GetExprType(E));
7966 
7967     // Bitwise-and uses the *infinum* of the two source ranges.
7968     case BO_And:
7969     case BO_AndAssign:
7970       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7971                             GetExprRange(C, BO->getRHS(), MaxWidth));
7972 
7973     // Left shift gets black-listed based on a judgement call.
7974     case BO_Shl:
7975       // ...except that we want to treat '1 << (blah)' as logically
7976       // positive.  It's an important idiom.
7977       if (IntegerLiteral *I
7978             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7979         if (I->getValue() == 1) {
7980           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7981           return IntRange(R.Width, /*NonNegative*/ true);
7982         }
7983       }
7984       // fallthrough
7985 
7986     case BO_ShlAssign:
7987       return IntRange::forValueOfType(C, GetExprType(E));
7988 
7989     // Right shift by a constant can narrow its left argument.
7990     case BO_Shr:
7991     case BO_ShrAssign: {
7992       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7993 
7994       // If the shift amount is a positive constant, drop the width by
7995       // that much.
7996       llvm::APSInt shift;
7997       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7998           shift.isNonNegative()) {
7999         unsigned zext = shift.getZExtValue();
8000         if (zext >= L.Width)
8001           L.Width = (L.NonNegative ? 0 : 1);
8002         else
8003           L.Width -= zext;
8004       }
8005 
8006       return L;
8007     }
8008 
8009     // Comma acts as its right operand.
8010     case BO_Comma:
8011       return GetExprRange(C, BO->getRHS(), MaxWidth);
8012 
8013     // Black-list pointer subtractions.
8014     case BO_Sub:
8015       if (BO->getLHS()->getType()->isPointerType())
8016         return IntRange::forValueOfType(C, GetExprType(E));
8017       break;
8018 
8019     // The width of a division result is mostly determined by the size
8020     // of the LHS.
8021     case BO_Div: {
8022       // Don't 'pre-truncate' the operands.
8023       unsigned opWidth = C.getIntWidth(GetExprType(E));
8024       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8025 
8026       // If the divisor is constant, use that.
8027       llvm::APSInt divisor;
8028       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8029         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8030         if (log2 >= L.Width)
8031           L.Width = (L.NonNegative ? 0 : 1);
8032         else
8033           L.Width = std::min(L.Width - log2, MaxWidth);
8034         return L;
8035       }
8036 
8037       // Otherwise, just use the LHS's width.
8038       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8039       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8040     }
8041 
8042     // The result of a remainder can't be larger than the result of
8043     // either side.
8044     case BO_Rem: {
8045       // Don't 'pre-truncate' the operands.
8046       unsigned opWidth = C.getIntWidth(GetExprType(E));
8047       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8048       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8049 
8050       IntRange meet = IntRange::meet(L, R);
8051       meet.Width = std::min(meet.Width, MaxWidth);
8052       return meet;
8053     }
8054 
8055     // The default behavior is okay for these.
8056     case BO_Mul:
8057     case BO_Add:
8058     case BO_Xor:
8059     case BO_Or:
8060       break;
8061     }
8062 
8063     // The default case is to treat the operation as if it were closed
8064     // on the narrowest type that encompasses both operands.
8065     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8066     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8067     return IntRange::join(L, R);
8068   }
8069 
8070   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8071     switch (UO->getOpcode()) {
8072     // Boolean-valued operations are white-listed.
8073     case UO_LNot:
8074       return IntRange::forBoolType();
8075 
8076     // Operations with opaque sources are black-listed.
8077     case UO_Deref:
8078     case UO_AddrOf: // should be impossible
8079       return IntRange::forValueOfType(C, GetExprType(E));
8080 
8081     default:
8082       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8083     }
8084   }
8085 
8086   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8087     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8088 
8089   if (const auto *BitField = E->getSourceBitField())
8090     return IntRange(BitField->getBitWidthValue(C),
8091                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8092 
8093   return IntRange::forValueOfType(C, GetExprType(E));
8094 }
8095 
8096 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8097   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8098 }
8099 
8100 /// Checks whether the given value, which currently has the given
8101 /// source semantics, has the same value when coerced through the
8102 /// target semantics.
8103 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8104                           const llvm::fltSemantics &Src,
8105                           const llvm::fltSemantics &Tgt) {
8106   llvm::APFloat truncated = value;
8107 
8108   bool ignored;
8109   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8110   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8111 
8112   return truncated.bitwiseIsEqual(value);
8113 }
8114 
8115 /// Checks whether the given value, which currently has the given
8116 /// source semantics, has the same value when coerced through the
8117 /// target semantics.
8118 ///
8119 /// The value might be a vector of floats (or a complex number).
8120 bool IsSameFloatAfterCast(const APValue &value,
8121                           const llvm::fltSemantics &Src,
8122                           const llvm::fltSemantics &Tgt) {
8123   if (value.isFloat())
8124     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8125 
8126   if (value.isVector()) {
8127     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8128       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8129         return false;
8130     return true;
8131   }
8132 
8133   assert(value.isComplexFloat());
8134   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8135           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8136 }
8137 
8138 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8139 
8140 bool IsZero(Sema &S, Expr *E) {
8141   // Suppress cases where we are comparing against an enum constant.
8142   if (const DeclRefExpr *DR =
8143       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8144     if (isa<EnumConstantDecl>(DR->getDecl()))
8145       return false;
8146 
8147   // Suppress cases where the '0' value is expanded from a macro.
8148   if (E->getLocStart().isMacroID())
8149     return false;
8150 
8151   llvm::APSInt Value;
8152   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8153 }
8154 
8155 bool HasEnumType(Expr *E) {
8156   // Strip off implicit integral promotions.
8157   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8158     if (ICE->getCastKind() != CK_IntegralCast &&
8159         ICE->getCastKind() != CK_NoOp)
8160       break;
8161     E = ICE->getSubExpr();
8162   }
8163 
8164   return E->getType()->isEnumeralType();
8165 }
8166 
8167 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8168   // Disable warning in template instantiations.
8169   if (!S.ActiveTemplateInstantiations.empty())
8170     return;
8171 
8172   BinaryOperatorKind op = E->getOpcode();
8173   if (E->isValueDependent())
8174     return;
8175 
8176   if (op == BO_LT && IsZero(S, E->getRHS())) {
8177     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8178       << "< 0" << "false" << HasEnumType(E->getLHS())
8179       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8180   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8181     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8182       << ">= 0" << "true" << HasEnumType(E->getLHS())
8183       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8184   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8185     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8186       << "0 >" << "false" << HasEnumType(E->getRHS())
8187       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8188   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8189     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8190       << "0 <=" << "true" << HasEnumType(E->getRHS())
8191       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8192   }
8193 }
8194 
8195 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8196                                   Expr *Other, const llvm::APSInt &Value,
8197                                   bool RhsConstant) {
8198   // Disable warning in template instantiations.
8199   if (!S.ActiveTemplateInstantiations.empty())
8200     return;
8201 
8202   // TODO: Investigate using GetExprRange() to get tighter bounds
8203   // on the bit ranges.
8204   QualType OtherT = Other->getType();
8205   if (const auto *AT = OtherT->getAs<AtomicType>())
8206     OtherT = AT->getValueType();
8207   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8208   unsigned OtherWidth = OtherRange.Width;
8209 
8210   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8211 
8212   // 0 values are handled later by CheckTrivialUnsignedComparison().
8213   if ((Value == 0) && (!OtherIsBooleanType))
8214     return;
8215 
8216   BinaryOperatorKind op = E->getOpcode();
8217   bool IsTrue = true;
8218 
8219   // Used for diagnostic printout.
8220   enum {
8221     LiteralConstant = 0,
8222     CXXBoolLiteralTrue,
8223     CXXBoolLiteralFalse
8224   } LiteralOrBoolConstant = LiteralConstant;
8225 
8226   if (!OtherIsBooleanType) {
8227     QualType ConstantT = Constant->getType();
8228     QualType CommonT = E->getLHS()->getType();
8229 
8230     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8231       return;
8232     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8233            "comparison with non-integer type");
8234 
8235     bool ConstantSigned = ConstantT->isSignedIntegerType();
8236     bool CommonSigned = CommonT->isSignedIntegerType();
8237 
8238     bool EqualityOnly = false;
8239 
8240     if (CommonSigned) {
8241       // The common type is signed, therefore no signed to unsigned conversion.
8242       if (!OtherRange.NonNegative) {
8243         // Check that the constant is representable in type OtherT.
8244         if (ConstantSigned) {
8245           if (OtherWidth >= Value.getMinSignedBits())
8246             return;
8247         } else { // !ConstantSigned
8248           if (OtherWidth >= Value.getActiveBits() + 1)
8249             return;
8250         }
8251       } else { // !OtherSigned
8252                // Check that the constant is representable in type OtherT.
8253         // Negative values are out of range.
8254         if (ConstantSigned) {
8255           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8256             return;
8257         } else { // !ConstantSigned
8258           if (OtherWidth >= Value.getActiveBits())
8259             return;
8260         }
8261       }
8262     } else { // !CommonSigned
8263       if (OtherRange.NonNegative) {
8264         if (OtherWidth >= Value.getActiveBits())
8265           return;
8266       } else { // OtherSigned
8267         assert(!ConstantSigned &&
8268                "Two signed types converted to unsigned types.");
8269         // Check to see if the constant is representable in OtherT.
8270         if (OtherWidth > Value.getActiveBits())
8271           return;
8272         // Check to see if the constant is equivalent to a negative value
8273         // cast to CommonT.
8274         if (S.Context.getIntWidth(ConstantT) ==
8275                 S.Context.getIntWidth(CommonT) &&
8276             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8277           return;
8278         // The constant value rests between values that OtherT can represent
8279         // after conversion.  Relational comparison still works, but equality
8280         // comparisons will be tautological.
8281         EqualityOnly = true;
8282       }
8283     }
8284 
8285     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8286 
8287     if (op == BO_EQ || op == BO_NE) {
8288       IsTrue = op == BO_NE;
8289     } else if (EqualityOnly) {
8290       return;
8291     } else if (RhsConstant) {
8292       if (op == BO_GT || op == BO_GE)
8293         IsTrue = !PositiveConstant;
8294       else // op == BO_LT || op == BO_LE
8295         IsTrue = PositiveConstant;
8296     } else {
8297       if (op == BO_LT || op == BO_LE)
8298         IsTrue = !PositiveConstant;
8299       else // op == BO_GT || op == BO_GE
8300         IsTrue = PositiveConstant;
8301     }
8302   } else {
8303     // Other isKnownToHaveBooleanValue
8304     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8305     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8306     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8307 
8308     static const struct LinkedConditions {
8309       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8310       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8311       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8312       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8313       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8314       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8315 
8316     } TruthTable = {
8317         // Constant on LHS.              | Constant on RHS.              |
8318         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8319         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8320         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8321         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8322         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8323         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8324         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8325       };
8326 
8327     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8328 
8329     enum ConstantValue ConstVal = Zero;
8330     if (Value.isUnsigned() || Value.isNonNegative()) {
8331       if (Value == 0) {
8332         LiteralOrBoolConstant =
8333             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8334         ConstVal = Zero;
8335       } else if (Value == 1) {
8336         LiteralOrBoolConstant =
8337             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8338         ConstVal = One;
8339       } else {
8340         LiteralOrBoolConstant = LiteralConstant;
8341         ConstVal = GT_One;
8342       }
8343     } else {
8344       ConstVal = LT_Zero;
8345     }
8346 
8347     CompareBoolWithConstantResult CmpRes;
8348 
8349     switch (op) {
8350     case BO_LT:
8351       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8352       break;
8353     case BO_GT:
8354       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8355       break;
8356     case BO_LE:
8357       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8358       break;
8359     case BO_GE:
8360       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8361       break;
8362     case BO_EQ:
8363       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8364       break;
8365     case BO_NE:
8366       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8367       break;
8368     default:
8369       CmpRes = Unkwn;
8370       break;
8371     }
8372 
8373     if (CmpRes == AFals) {
8374       IsTrue = false;
8375     } else if (CmpRes == ATrue) {
8376       IsTrue = true;
8377     } else {
8378       return;
8379     }
8380   }
8381 
8382   // If this is a comparison to an enum constant, include that
8383   // constant in the diagnostic.
8384   const EnumConstantDecl *ED = nullptr;
8385   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8386     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8387 
8388   SmallString<64> PrettySourceValue;
8389   llvm::raw_svector_ostream OS(PrettySourceValue);
8390   if (ED)
8391     OS << '\'' << *ED << "' (" << Value << ")";
8392   else
8393     OS << Value;
8394 
8395   S.DiagRuntimeBehavior(
8396     E->getOperatorLoc(), E,
8397     S.PDiag(diag::warn_out_of_range_compare)
8398         << OS.str() << LiteralOrBoolConstant
8399         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8400         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8401 }
8402 
8403 /// Analyze the operands of the given comparison.  Implements the
8404 /// fallback case from AnalyzeComparison.
8405 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8406   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8407   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8408 }
8409 
8410 /// \brief Implements -Wsign-compare.
8411 ///
8412 /// \param E the binary operator to check for warnings
8413 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8414   // The type the comparison is being performed in.
8415   QualType T = E->getLHS()->getType();
8416 
8417   // Only analyze comparison operators where both sides have been converted to
8418   // the same type.
8419   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8420     return AnalyzeImpConvsInComparison(S, E);
8421 
8422   // Don't analyze value-dependent comparisons directly.
8423   if (E->isValueDependent())
8424     return AnalyzeImpConvsInComparison(S, E);
8425 
8426   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8427   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8428 
8429   bool IsComparisonConstant = false;
8430 
8431   // Check whether an integer constant comparison results in a value
8432   // of 'true' or 'false'.
8433   if (T->isIntegralType(S.Context)) {
8434     llvm::APSInt RHSValue;
8435     bool IsRHSIntegralLiteral =
8436       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8437     llvm::APSInt LHSValue;
8438     bool IsLHSIntegralLiteral =
8439       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8440     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8441         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8442     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8443       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8444     else
8445       IsComparisonConstant =
8446         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8447   } else if (!T->hasUnsignedIntegerRepresentation())
8448       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8449 
8450   // We don't do anything special if this isn't an unsigned integral
8451   // comparison:  we're only interested in integral comparisons, and
8452   // signed comparisons only happen in cases we don't care to warn about.
8453   //
8454   // We also don't care about value-dependent expressions or expressions
8455   // whose result is a constant.
8456   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8457     return AnalyzeImpConvsInComparison(S, E);
8458 
8459   // Check to see if one of the (unmodified) operands is of different
8460   // signedness.
8461   Expr *signedOperand, *unsignedOperand;
8462   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8463     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8464            "unsigned comparison between two signed integer expressions?");
8465     signedOperand = LHS;
8466     unsignedOperand = RHS;
8467   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8468     signedOperand = RHS;
8469     unsignedOperand = LHS;
8470   } else {
8471     CheckTrivialUnsignedComparison(S, E);
8472     return AnalyzeImpConvsInComparison(S, E);
8473   }
8474 
8475   // Otherwise, calculate the effective range of the signed operand.
8476   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8477 
8478   // Go ahead and analyze implicit conversions in the operands.  Note
8479   // that we skip the implicit conversions on both sides.
8480   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8481   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8482 
8483   // If the signed range is non-negative, -Wsign-compare won't fire,
8484   // but we should still check for comparisons which are always true
8485   // or false.
8486   if (signedRange.NonNegative)
8487     return CheckTrivialUnsignedComparison(S, E);
8488 
8489   // For (in)equality comparisons, if the unsigned operand is a
8490   // constant which cannot collide with a overflowed signed operand,
8491   // then reinterpreting the signed operand as unsigned will not
8492   // change the result of the comparison.
8493   if (E->isEqualityOp()) {
8494     unsigned comparisonWidth = S.Context.getIntWidth(T);
8495     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8496 
8497     // We should never be unable to prove that the unsigned operand is
8498     // non-negative.
8499     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8500 
8501     if (unsignedRange.Width < comparisonWidth)
8502       return;
8503   }
8504 
8505   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8506     S.PDiag(diag::warn_mixed_sign_comparison)
8507       << LHS->getType() << RHS->getType()
8508       << LHS->getSourceRange() << RHS->getSourceRange());
8509 }
8510 
8511 /// Analyzes an attempt to assign the given value to a bitfield.
8512 ///
8513 /// Returns true if there was something fishy about the attempt.
8514 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8515                                SourceLocation InitLoc) {
8516   assert(Bitfield->isBitField());
8517   if (Bitfield->isInvalidDecl())
8518     return false;
8519 
8520   // White-list bool bitfields.
8521   if (Bitfield->getType()->isBooleanType())
8522     return false;
8523 
8524   // Ignore value- or type-dependent expressions.
8525   if (Bitfield->getBitWidth()->isValueDependent() ||
8526       Bitfield->getBitWidth()->isTypeDependent() ||
8527       Init->isValueDependent() ||
8528       Init->isTypeDependent())
8529     return false;
8530 
8531   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8532 
8533   llvm::APSInt Value;
8534   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8535     return false;
8536 
8537   unsigned OriginalWidth = Value.getBitWidth();
8538   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8539 
8540   if (!Value.isSigned() || Value.isNegative())
8541     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8542       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8543         OriginalWidth = Value.getMinSignedBits();
8544 
8545   if (OriginalWidth <= FieldWidth)
8546     return false;
8547 
8548   // Compute the value which the bitfield will contain.
8549   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8550   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
8551 
8552   // Check whether the stored value is equal to the original value.
8553   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8554   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8555     return false;
8556 
8557   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8558   // therefore don't strictly fit into a signed bitfield of width 1.
8559   if (FieldWidth == 1 && Value == 1)
8560     return false;
8561 
8562   std::string PrettyValue = Value.toString(10);
8563   std::string PrettyTrunc = TruncatedValue.toString(10);
8564 
8565   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8566     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8567     << Init->getSourceRange();
8568 
8569   return true;
8570 }
8571 
8572 /// Analyze the given simple or compound assignment for warning-worthy
8573 /// operations.
8574 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8575   // Just recurse on the LHS.
8576   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8577 
8578   // We want to recurse on the RHS as normal unless we're assigning to
8579   // a bitfield.
8580   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8581     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8582                                   E->getOperatorLoc())) {
8583       // Recurse, ignoring any implicit conversions on the RHS.
8584       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8585                                         E->getOperatorLoc());
8586     }
8587   }
8588 
8589   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8590 }
8591 
8592 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8593 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8594                      SourceLocation CContext, unsigned diag,
8595                      bool pruneControlFlow = false) {
8596   if (pruneControlFlow) {
8597     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8598                           S.PDiag(diag)
8599                             << SourceType << T << E->getSourceRange()
8600                             << SourceRange(CContext));
8601     return;
8602   }
8603   S.Diag(E->getExprLoc(), diag)
8604     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8605 }
8606 
8607 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8608 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8609                      unsigned diag, bool pruneControlFlow = false) {
8610   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8611 }
8612 
8613 
8614 /// Diagnose an implicit cast from a floating point value to an integer value.
8615 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8616 
8617                              SourceLocation CContext) {
8618   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8619   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8620 
8621   Expr *InnerE = E->IgnoreParenImpCasts();
8622   // We also want to warn on, e.g., "int i = -1.234"
8623   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8624     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8625       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8626 
8627   const bool IsLiteral =
8628       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8629 
8630   llvm::APFloat Value(0.0);
8631   bool IsConstant =
8632     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8633   if (!IsConstant) {
8634     return DiagnoseImpCast(S, E, T, CContext,
8635                            diag::warn_impcast_float_integer, PruneWarnings);
8636   }
8637 
8638   bool isExact = false;
8639 
8640   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8641                             T->hasUnsignedIntegerRepresentation());
8642   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8643                              &isExact) == llvm::APFloat::opOK &&
8644       isExact) {
8645     if (IsLiteral) return;
8646     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8647                            PruneWarnings);
8648   }
8649 
8650   unsigned DiagID = 0;
8651   if (IsLiteral) {
8652     // Warn on floating point literal to integer.
8653     DiagID = diag::warn_impcast_literal_float_to_integer;
8654   } else if (IntegerValue == 0) {
8655     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8656       return DiagnoseImpCast(S, E, T, CContext,
8657                              diag::warn_impcast_float_integer, PruneWarnings);
8658     }
8659     // Warn on non-zero to zero conversion.
8660     DiagID = diag::warn_impcast_float_to_integer_zero;
8661   } else {
8662     if (IntegerValue.isUnsigned()) {
8663       if (!IntegerValue.isMaxValue()) {
8664         return DiagnoseImpCast(S, E, T, CContext,
8665                                diag::warn_impcast_float_integer, PruneWarnings);
8666       }
8667     } else {  // IntegerValue.isSigned()
8668       if (!IntegerValue.isMaxSignedValue() &&
8669           !IntegerValue.isMinSignedValue()) {
8670         return DiagnoseImpCast(S, E, T, CContext,
8671                                diag::warn_impcast_float_integer, PruneWarnings);
8672       }
8673     }
8674     // Warn on evaluatable floating point expression to integer conversion.
8675     DiagID = diag::warn_impcast_float_to_integer;
8676   }
8677 
8678   // FIXME: Force the precision of the source value down so we don't print
8679   // digits which are usually useless (we don't really care here if we
8680   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
8681   // would automatically print the shortest representation, but it's a bit
8682   // tricky to implement.
8683   SmallString<16> PrettySourceValue;
8684   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8685   precision = (precision * 59 + 195) / 196;
8686   Value.toString(PrettySourceValue, precision);
8687 
8688   SmallString<16> PrettyTargetValue;
8689   if (IsBool)
8690     PrettyTargetValue = Value.isZero() ? "false" : "true";
8691   else
8692     IntegerValue.toString(PrettyTargetValue);
8693 
8694   if (PruneWarnings) {
8695     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8696                           S.PDiag(DiagID)
8697                               << E->getType() << T.getUnqualifiedType()
8698                               << PrettySourceValue << PrettyTargetValue
8699                               << E->getSourceRange() << SourceRange(CContext));
8700   } else {
8701     S.Diag(E->getExprLoc(), DiagID)
8702         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8703         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8704   }
8705 }
8706 
8707 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8708   if (!Range.Width) return "0";
8709 
8710   llvm::APSInt ValueInRange = Value;
8711   ValueInRange.setIsSigned(!Range.NonNegative);
8712   ValueInRange = ValueInRange.trunc(Range.Width);
8713   return ValueInRange.toString(10);
8714 }
8715 
8716 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8717   if (!isa<ImplicitCastExpr>(Ex))
8718     return false;
8719 
8720   Expr *InnerE = Ex->IgnoreParenImpCasts();
8721   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8722   const Type *Source =
8723     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8724   if (Target->isDependentType())
8725     return false;
8726 
8727   const BuiltinType *FloatCandidateBT =
8728     dyn_cast<BuiltinType>(ToBool ? Source : Target);
8729   const Type *BoolCandidateType = ToBool ? Target : Source;
8730 
8731   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8732           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8733 }
8734 
8735 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8736                                       SourceLocation CC) {
8737   unsigned NumArgs = TheCall->getNumArgs();
8738   for (unsigned i = 0; i < NumArgs; ++i) {
8739     Expr *CurrA = TheCall->getArg(i);
8740     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8741       continue;
8742 
8743     bool IsSwapped = ((i > 0) &&
8744         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8745     IsSwapped |= ((i < (NumArgs - 1)) &&
8746         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8747     if (IsSwapped) {
8748       // Warn on this floating-point to bool conversion.
8749       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8750                       CurrA->getType(), CC,
8751                       diag::warn_impcast_floating_point_to_bool);
8752     }
8753   }
8754 }
8755 
8756 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8757   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8758                         E->getExprLoc()))
8759     return;
8760 
8761   // Don't warn on functions which have return type nullptr_t.
8762   if (isa<CallExpr>(E))
8763     return;
8764 
8765   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8766   const Expr::NullPointerConstantKind NullKind =
8767       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8768   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8769     return;
8770 
8771   // Return if target type is a safe conversion.
8772   if (T->isAnyPointerType() || T->isBlockPointerType() ||
8773       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8774     return;
8775 
8776   SourceLocation Loc = E->getSourceRange().getBegin();
8777 
8778   // Venture through the macro stacks to get to the source of macro arguments.
8779   // The new location is a better location than the complete location that was
8780   // passed in.
8781   while (S.SourceMgr.isMacroArgExpansion(Loc))
8782     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8783 
8784   while (S.SourceMgr.isMacroArgExpansion(CC))
8785     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8786 
8787   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
8788   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8789     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8790         Loc, S.SourceMgr, S.getLangOpts());
8791     if (MacroName == "NULL")
8792       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8793   }
8794 
8795   // Only warn if the null and context location are in the same macro expansion.
8796   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8797     return;
8798 
8799   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8800       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8801       << FixItHint::CreateReplacement(Loc,
8802                                       S.getFixItZeroLiteralForType(T, Loc));
8803 }
8804 
8805 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8806                            ObjCArrayLiteral *ArrayLiteral);
8807 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8808                                 ObjCDictionaryLiteral *DictionaryLiteral);
8809 
8810 /// Check a single element within a collection literal against the
8811 /// target element type.
8812 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8813                                        Expr *Element, unsigned ElementKind) {
8814   // Skip a bitcast to 'id' or qualified 'id'.
8815   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8816     if (ICE->getCastKind() == CK_BitCast &&
8817         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8818       Element = ICE->getSubExpr();
8819   }
8820 
8821   QualType ElementType = Element->getType();
8822   ExprResult ElementResult(Element);
8823   if (ElementType->getAs<ObjCObjectPointerType>() &&
8824       S.CheckSingleAssignmentConstraints(TargetElementType,
8825                                          ElementResult,
8826                                          false, false)
8827         != Sema::Compatible) {
8828     S.Diag(Element->getLocStart(),
8829            diag::warn_objc_collection_literal_element)
8830       << ElementType << ElementKind << TargetElementType
8831       << Element->getSourceRange();
8832   }
8833 
8834   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8835     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8836   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8837     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8838 }
8839 
8840 /// Check an Objective-C array literal being converted to the given
8841 /// target type.
8842 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8843                            ObjCArrayLiteral *ArrayLiteral) {
8844   if (!S.NSArrayDecl)
8845     return;
8846 
8847   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8848   if (!TargetObjCPtr)
8849     return;
8850 
8851   if (TargetObjCPtr->isUnspecialized() ||
8852       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8853         != S.NSArrayDecl->getCanonicalDecl())
8854     return;
8855 
8856   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8857   if (TypeArgs.size() != 1)
8858     return;
8859 
8860   QualType TargetElementType = TypeArgs[0];
8861   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8862     checkObjCCollectionLiteralElement(S, TargetElementType,
8863                                       ArrayLiteral->getElement(I),
8864                                       0);
8865   }
8866 }
8867 
8868 /// Check an Objective-C dictionary literal being converted to the given
8869 /// target type.
8870 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8871                                 ObjCDictionaryLiteral *DictionaryLiteral) {
8872   if (!S.NSDictionaryDecl)
8873     return;
8874 
8875   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8876   if (!TargetObjCPtr)
8877     return;
8878 
8879   if (TargetObjCPtr->isUnspecialized() ||
8880       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8881         != S.NSDictionaryDecl->getCanonicalDecl())
8882     return;
8883 
8884   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8885   if (TypeArgs.size() != 2)
8886     return;
8887 
8888   QualType TargetKeyType = TypeArgs[0];
8889   QualType TargetObjectType = TypeArgs[1];
8890   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8891     auto Element = DictionaryLiteral->getKeyValueElement(I);
8892     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8893     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8894   }
8895 }
8896 
8897 // Helper function to filter out cases for constant width constant conversion.
8898 // Don't warn on char array initialization or for non-decimal values.
8899 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8900                                    SourceLocation CC) {
8901   // If initializing from a constant, and the constant starts with '0',
8902   // then it is a binary, octal, or hexadecimal.  Allow these constants
8903   // to fill all the bits, even if there is a sign change.
8904   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8905     const char FirstLiteralCharacter =
8906         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8907     if (FirstLiteralCharacter == '0')
8908       return false;
8909   }
8910 
8911   // If the CC location points to a '{', and the type is char, then assume
8912   // assume it is an array initialization.
8913   if (CC.isValid() && T->isCharType()) {
8914     const char FirstContextCharacter =
8915         S.getSourceManager().getCharacterData(CC)[0];
8916     if (FirstContextCharacter == '{')
8917       return false;
8918   }
8919 
8920   return true;
8921 }
8922 
8923 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
8924                              SourceLocation CC, bool *ICContext = nullptr) {
8925   if (E->isTypeDependent() || E->isValueDependent()) return;
8926 
8927   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8928   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8929   if (Source == Target) return;
8930   if (Target->isDependentType()) return;
8931 
8932   // If the conversion context location is invalid don't complain. We also
8933   // don't want to emit a warning if the issue occurs from the expansion of
8934   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8935   // delay this check as long as possible. Once we detect we are in that
8936   // scenario, we just return.
8937   if (CC.isInvalid())
8938     return;
8939 
8940   // Diagnose implicit casts to bool.
8941   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8942     if (isa<StringLiteral>(E))
8943       // Warn on string literal to bool.  Checks for string literals in logical
8944       // and expressions, for instance, assert(0 && "error here"), are
8945       // prevented by a check in AnalyzeImplicitConversions().
8946       return DiagnoseImpCast(S, E, T, CC,
8947                              diag::warn_impcast_string_literal_to_bool);
8948     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8949         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8950       // This covers the literal expressions that evaluate to Objective-C
8951       // objects.
8952       return DiagnoseImpCast(S, E, T, CC,
8953                              diag::warn_impcast_objective_c_literal_to_bool);
8954     }
8955     if (Source->isPointerType() || Source->canDecayToPointerType()) {
8956       // Warn on pointer to bool conversion that is always true.
8957       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8958                                      SourceRange(CC));
8959     }
8960   }
8961 
8962   // Check implicit casts from Objective-C collection literals to specialized
8963   // collection types, e.g., NSArray<NSString *> *.
8964   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8965     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8966   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8967     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8968 
8969   // Strip vector types.
8970   if (isa<VectorType>(Source)) {
8971     if (!isa<VectorType>(Target)) {
8972       if (S.SourceMgr.isInSystemMacro(CC))
8973         return;
8974       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8975     }
8976 
8977     // If the vector cast is cast between two vectors of the same size, it is
8978     // a bitcast, not a conversion.
8979     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8980       return;
8981 
8982     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8983     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8984   }
8985   if (auto VecTy = dyn_cast<VectorType>(Target))
8986     Target = VecTy->getElementType().getTypePtr();
8987 
8988   // Strip complex types.
8989   if (isa<ComplexType>(Source)) {
8990     if (!isa<ComplexType>(Target)) {
8991       if (S.SourceMgr.isInSystemMacro(CC))
8992         return;
8993 
8994       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8995     }
8996 
8997     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8998     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8999   }
9000 
9001   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9002   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9003 
9004   // If the source is floating point...
9005   if (SourceBT && SourceBT->isFloatingPoint()) {
9006     // ...and the target is floating point...
9007     if (TargetBT && TargetBT->isFloatingPoint()) {
9008       // ...then warn if we're dropping FP rank.
9009 
9010       // Builtin FP kinds are ordered by increasing FP rank.
9011       if (SourceBT->getKind() > TargetBT->getKind()) {
9012         // Don't warn about float constants that are precisely
9013         // representable in the target type.
9014         Expr::EvalResult result;
9015         if (E->EvaluateAsRValue(result, S.Context)) {
9016           // Value might be a float, a float vector, or a float complex.
9017           if (IsSameFloatAfterCast(result.Val,
9018                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9019                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9020             return;
9021         }
9022 
9023         if (S.SourceMgr.isInSystemMacro(CC))
9024           return;
9025 
9026         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9027       }
9028       // ... or possibly if we're increasing rank, too
9029       else if (TargetBT->getKind() > SourceBT->getKind()) {
9030         if (S.SourceMgr.isInSystemMacro(CC))
9031           return;
9032 
9033         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9034       }
9035       return;
9036     }
9037 
9038     // If the target is integral, always warn.
9039     if (TargetBT && TargetBT->isInteger()) {
9040       if (S.SourceMgr.isInSystemMacro(CC))
9041         return;
9042 
9043       DiagnoseFloatingImpCast(S, E, T, CC);
9044     }
9045 
9046     // Detect the case where a call result is converted from floating-point to
9047     // to bool, and the final argument to the call is converted from bool, to
9048     // discover this typo:
9049     //
9050     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9051     //
9052     // FIXME: This is an incredibly special case; is there some more general
9053     // way to detect this class of misplaced-parentheses bug?
9054     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9055       // Check last argument of function call to see if it is an
9056       // implicit cast from a type matching the type the result
9057       // is being cast to.
9058       CallExpr *CEx = cast<CallExpr>(E);
9059       if (unsigned NumArgs = CEx->getNumArgs()) {
9060         Expr *LastA = CEx->getArg(NumArgs - 1);
9061         Expr *InnerE = LastA->IgnoreParenImpCasts();
9062         if (isa<ImplicitCastExpr>(LastA) &&
9063             InnerE->getType()->isBooleanType()) {
9064           // Warn on this floating-point to bool conversion
9065           DiagnoseImpCast(S, E, T, CC,
9066                           diag::warn_impcast_floating_point_to_bool);
9067         }
9068       }
9069     }
9070     return;
9071   }
9072 
9073   DiagnoseNullConversion(S, E, T, CC);
9074 
9075   S.DiscardMisalignedMemberAddress(Target, E);
9076 
9077   if (!Source->isIntegerType() || !Target->isIntegerType())
9078     return;
9079 
9080   // TODO: remove this early return once the false positives for constant->bool
9081   // in templates, macros, etc, are reduced or removed.
9082   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9083     return;
9084 
9085   IntRange SourceRange = GetExprRange(S.Context, E);
9086   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9087 
9088   if (SourceRange.Width > TargetRange.Width) {
9089     // If the source is a constant, use a default-on diagnostic.
9090     // TODO: this should happen for bitfield stores, too.
9091     llvm::APSInt Value(32);
9092     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9093       if (S.SourceMgr.isInSystemMacro(CC))
9094         return;
9095 
9096       std::string PrettySourceValue = Value.toString(10);
9097       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9098 
9099       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9100         S.PDiag(diag::warn_impcast_integer_precision_constant)
9101             << PrettySourceValue << PrettyTargetValue
9102             << E->getType() << T << E->getSourceRange()
9103             << clang::SourceRange(CC));
9104       return;
9105     }
9106 
9107     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9108     if (S.SourceMgr.isInSystemMacro(CC))
9109       return;
9110 
9111     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9112       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9113                              /* pruneControlFlow */ true);
9114     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9115   }
9116 
9117   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9118       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9119     // Warn when doing a signed to signed conversion, warn if the positive
9120     // source value is exactly the width of the target type, which will
9121     // cause a negative value to be stored.
9122 
9123     llvm::APSInt Value;
9124     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9125         !S.SourceMgr.isInSystemMacro(CC)) {
9126       if (isSameWidthConstantConversion(S, E, T, CC)) {
9127         std::string PrettySourceValue = Value.toString(10);
9128         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9129 
9130         S.DiagRuntimeBehavior(
9131             E->getExprLoc(), E,
9132             S.PDiag(diag::warn_impcast_integer_precision_constant)
9133                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9134                 << E->getSourceRange() << clang::SourceRange(CC));
9135         return;
9136       }
9137     }
9138 
9139     // Fall through for non-constants to give a sign conversion warning.
9140   }
9141 
9142   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9143       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9144        SourceRange.Width == TargetRange.Width)) {
9145     if (S.SourceMgr.isInSystemMacro(CC))
9146       return;
9147 
9148     unsigned DiagID = diag::warn_impcast_integer_sign;
9149 
9150     // Traditionally, gcc has warned about this under -Wsign-compare.
9151     // We also want to warn about it in -Wconversion.
9152     // So if -Wconversion is off, use a completely identical diagnostic
9153     // in the sign-compare group.
9154     // The conditional-checking code will
9155     if (ICContext) {
9156       DiagID = diag::warn_impcast_integer_sign_conditional;
9157       *ICContext = true;
9158     }
9159 
9160     return DiagnoseImpCast(S, E, T, CC, DiagID);
9161   }
9162 
9163   // Diagnose conversions between different enumeration types.
9164   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9165   // type, to give us better diagnostics.
9166   QualType SourceType = E->getType();
9167   if (!S.getLangOpts().CPlusPlus) {
9168     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9169       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9170         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9171         SourceType = S.Context.getTypeDeclType(Enum);
9172         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9173       }
9174   }
9175 
9176   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9177     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9178       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9179           TargetEnum->getDecl()->hasNameForLinkage() &&
9180           SourceEnum != TargetEnum) {
9181         if (S.SourceMgr.isInSystemMacro(CC))
9182           return;
9183 
9184         return DiagnoseImpCast(S, E, SourceType, T, CC,
9185                                diag::warn_impcast_different_enum_types);
9186       }
9187 }
9188 
9189 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9190                               SourceLocation CC, QualType T);
9191 
9192 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9193                              SourceLocation CC, bool &ICContext) {
9194   E = E->IgnoreParenImpCasts();
9195 
9196   if (isa<ConditionalOperator>(E))
9197     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9198 
9199   AnalyzeImplicitConversions(S, E, CC);
9200   if (E->getType() != T)
9201     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9202 }
9203 
9204 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9205                               SourceLocation CC, QualType T) {
9206   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9207 
9208   bool Suspicious = false;
9209   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9210   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9211 
9212   // If -Wconversion would have warned about either of the candidates
9213   // for a signedness conversion to the context type...
9214   if (!Suspicious) return;
9215 
9216   // ...but it's currently ignored...
9217   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9218     return;
9219 
9220   // ...then check whether it would have warned about either of the
9221   // candidates for a signedness conversion to the condition type.
9222   if (E->getType() == T) return;
9223 
9224   Suspicious = false;
9225   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9226                           E->getType(), CC, &Suspicious);
9227   if (!Suspicious)
9228     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9229                             E->getType(), CC, &Suspicious);
9230 }
9231 
9232 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9233 /// Input argument E is a logical expression.
9234 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9235   if (S.getLangOpts().Bool)
9236     return;
9237   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9238 }
9239 
9240 /// AnalyzeImplicitConversions - Find and report any interesting
9241 /// implicit conversions in the given expression.  There are a couple
9242 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9243 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9244   QualType T = OrigE->getType();
9245   Expr *E = OrigE->IgnoreParenImpCasts();
9246 
9247   if (E->isTypeDependent() || E->isValueDependent())
9248     return;
9249 
9250   // For conditional operators, we analyze the arguments as if they
9251   // were being fed directly into the output.
9252   if (isa<ConditionalOperator>(E)) {
9253     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9254     CheckConditionalOperator(S, CO, CC, T);
9255     return;
9256   }
9257 
9258   // Check implicit argument conversions for function calls.
9259   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9260     CheckImplicitArgumentConversions(S, Call, CC);
9261 
9262   // Go ahead and check any implicit conversions we might have skipped.
9263   // The non-canonical typecheck is just an optimization;
9264   // CheckImplicitConversion will filter out dead implicit conversions.
9265   if (E->getType() != T)
9266     CheckImplicitConversion(S, E, T, CC);
9267 
9268   // Now continue drilling into this expression.
9269 
9270   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9271     // The bound subexpressions in a PseudoObjectExpr are not reachable
9272     // as transitive children.
9273     // FIXME: Use a more uniform representation for this.
9274     for (auto *SE : POE->semantics())
9275       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9276         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9277   }
9278 
9279   // Skip past explicit casts.
9280   if (isa<ExplicitCastExpr>(E)) {
9281     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9282     return AnalyzeImplicitConversions(S, E, CC);
9283   }
9284 
9285   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9286     // Do a somewhat different check with comparison operators.
9287     if (BO->isComparisonOp())
9288       return AnalyzeComparison(S, BO);
9289 
9290     // And with simple assignments.
9291     if (BO->getOpcode() == BO_Assign)
9292       return AnalyzeAssignment(S, BO);
9293   }
9294 
9295   // These break the otherwise-useful invariant below.  Fortunately,
9296   // we don't really need to recurse into them, because any internal
9297   // expressions should have been analyzed already when they were
9298   // built into statements.
9299   if (isa<StmtExpr>(E)) return;
9300 
9301   // Don't descend into unevaluated contexts.
9302   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9303 
9304   // Now just recurse over the expression's children.
9305   CC = E->getExprLoc();
9306   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9307   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9308   for (Stmt *SubStmt : E->children()) {
9309     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9310     if (!ChildExpr)
9311       continue;
9312 
9313     if (IsLogicalAndOperator &&
9314         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9315       // Ignore checking string literals that are in logical and operators.
9316       // This is a common pattern for asserts.
9317       continue;
9318     AnalyzeImplicitConversions(S, ChildExpr, CC);
9319   }
9320 
9321   if (BO && BO->isLogicalOp()) {
9322     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9323     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9324       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9325 
9326     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9327     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9328       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9329   }
9330 
9331   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9332     if (U->getOpcode() == UO_LNot)
9333       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9334 }
9335 
9336 } // end anonymous namespace
9337 
9338 /// Diagnose integer type and any valid implicit convertion to it.
9339 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9340   // Taking into account implicit conversions,
9341   // allow any integer.
9342   if (!E->getType()->isIntegerType()) {
9343     S.Diag(E->getLocStart(),
9344            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9345     return true;
9346   }
9347   // Potentially emit standard warnings for implicit conversions if enabled
9348   // using -Wconversion.
9349   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9350   return false;
9351 }
9352 
9353 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9354 // Returns true when emitting a warning about taking the address of a reference.
9355 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9356                               const PartialDiagnostic &PD) {
9357   E = E->IgnoreParenImpCasts();
9358 
9359   const FunctionDecl *FD = nullptr;
9360 
9361   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9362     if (!DRE->getDecl()->getType()->isReferenceType())
9363       return false;
9364   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9365     if (!M->getMemberDecl()->getType()->isReferenceType())
9366       return false;
9367   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9368     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9369       return false;
9370     FD = Call->getDirectCallee();
9371   } else {
9372     return false;
9373   }
9374 
9375   SemaRef.Diag(E->getExprLoc(), PD);
9376 
9377   // If possible, point to location of function.
9378   if (FD) {
9379     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9380   }
9381 
9382   return true;
9383 }
9384 
9385 // Returns true if the SourceLocation is expanded from any macro body.
9386 // Returns false if the SourceLocation is invalid, is from not in a macro
9387 // expansion, or is from expanded from a top-level macro argument.
9388 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9389   if (Loc.isInvalid())
9390     return false;
9391 
9392   while (Loc.isMacroID()) {
9393     if (SM.isMacroBodyExpansion(Loc))
9394       return true;
9395     Loc = SM.getImmediateMacroCallerLoc(Loc);
9396   }
9397 
9398   return false;
9399 }
9400 
9401 /// \brief Diagnose pointers that are always non-null.
9402 /// \param E the expression containing the pointer
9403 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9404 /// compared to a null pointer
9405 /// \param IsEqual True when the comparison is equal to a null pointer
9406 /// \param Range Extra SourceRange to highlight in the diagnostic
9407 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9408                                         Expr::NullPointerConstantKind NullKind,
9409                                         bool IsEqual, SourceRange Range) {
9410   if (!E)
9411     return;
9412 
9413   // Don't warn inside macros.
9414   if (E->getExprLoc().isMacroID()) {
9415     const SourceManager &SM = getSourceManager();
9416     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9417         IsInAnyMacroBody(SM, Range.getBegin()))
9418       return;
9419   }
9420   E = E->IgnoreImpCasts();
9421 
9422   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9423 
9424   if (isa<CXXThisExpr>(E)) {
9425     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9426                                 : diag::warn_this_bool_conversion;
9427     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9428     return;
9429   }
9430 
9431   bool IsAddressOf = false;
9432 
9433   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9434     if (UO->getOpcode() != UO_AddrOf)
9435       return;
9436     IsAddressOf = true;
9437     E = UO->getSubExpr();
9438   }
9439 
9440   if (IsAddressOf) {
9441     unsigned DiagID = IsCompare
9442                           ? diag::warn_address_of_reference_null_compare
9443                           : diag::warn_address_of_reference_bool_conversion;
9444     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9445                                          << IsEqual;
9446     if (CheckForReference(*this, E, PD)) {
9447       return;
9448     }
9449   }
9450 
9451   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9452     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9453     std::string Str;
9454     llvm::raw_string_ostream S(Str);
9455     E->printPretty(S, nullptr, getPrintingPolicy());
9456     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9457                                 : diag::warn_cast_nonnull_to_bool;
9458     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9459       << E->getSourceRange() << Range << IsEqual;
9460     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9461   };
9462 
9463   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9464   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9465     if (auto *Callee = Call->getDirectCallee()) {
9466       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9467         ComplainAboutNonnullParamOrCall(A);
9468         return;
9469       }
9470     }
9471   }
9472 
9473   // Expect to find a single Decl.  Skip anything more complicated.
9474   ValueDecl *D = nullptr;
9475   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9476     D = R->getDecl();
9477   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9478     D = M->getMemberDecl();
9479   }
9480 
9481   // Weak Decls can be null.
9482   if (!D || D->isWeak())
9483     return;
9484 
9485   // Check for parameter decl with nonnull attribute
9486   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9487     if (getCurFunction() &&
9488         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9489       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9490         ComplainAboutNonnullParamOrCall(A);
9491         return;
9492       }
9493 
9494       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9495         auto ParamIter = llvm::find(FD->parameters(), PV);
9496         assert(ParamIter != FD->param_end());
9497         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9498 
9499         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9500           if (!NonNull->args_size()) {
9501               ComplainAboutNonnullParamOrCall(NonNull);
9502               return;
9503           }
9504 
9505           for (unsigned ArgNo : NonNull->args()) {
9506             if (ArgNo == ParamNo) {
9507               ComplainAboutNonnullParamOrCall(NonNull);
9508               return;
9509             }
9510           }
9511         }
9512       }
9513     }
9514   }
9515 
9516   QualType T = D->getType();
9517   const bool IsArray = T->isArrayType();
9518   const bool IsFunction = T->isFunctionType();
9519 
9520   // Address of function is used to silence the function warning.
9521   if (IsAddressOf && IsFunction) {
9522     return;
9523   }
9524 
9525   // Found nothing.
9526   if (!IsAddressOf && !IsFunction && !IsArray)
9527     return;
9528 
9529   // Pretty print the expression for the diagnostic.
9530   std::string Str;
9531   llvm::raw_string_ostream S(Str);
9532   E->printPretty(S, nullptr, getPrintingPolicy());
9533 
9534   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9535                               : diag::warn_impcast_pointer_to_bool;
9536   enum {
9537     AddressOf,
9538     FunctionPointer,
9539     ArrayPointer
9540   } DiagType;
9541   if (IsAddressOf)
9542     DiagType = AddressOf;
9543   else if (IsFunction)
9544     DiagType = FunctionPointer;
9545   else if (IsArray)
9546     DiagType = ArrayPointer;
9547   else
9548     llvm_unreachable("Could not determine diagnostic.");
9549   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9550                                 << Range << IsEqual;
9551 
9552   if (!IsFunction)
9553     return;
9554 
9555   // Suggest '&' to silence the function warning.
9556   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9557       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9558 
9559   // Check to see if '()' fixit should be emitted.
9560   QualType ReturnType;
9561   UnresolvedSet<4> NonTemplateOverloads;
9562   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9563   if (ReturnType.isNull())
9564     return;
9565 
9566   if (IsCompare) {
9567     // There are two cases here.  If there is null constant, the only suggest
9568     // for a pointer return type.  If the null is 0, then suggest if the return
9569     // type is a pointer or an integer type.
9570     if (!ReturnType->isPointerType()) {
9571       if (NullKind == Expr::NPCK_ZeroExpression ||
9572           NullKind == Expr::NPCK_ZeroLiteral) {
9573         if (!ReturnType->isIntegerType())
9574           return;
9575       } else {
9576         return;
9577       }
9578     }
9579   } else { // !IsCompare
9580     // For function to bool, only suggest if the function pointer has bool
9581     // return type.
9582     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9583       return;
9584   }
9585   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9586       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9587 }
9588 
9589 /// Diagnoses "dangerous" implicit conversions within the given
9590 /// expression (which is a full expression).  Implements -Wconversion
9591 /// and -Wsign-compare.
9592 ///
9593 /// \param CC the "context" location of the implicit conversion, i.e.
9594 ///   the most location of the syntactic entity requiring the implicit
9595 ///   conversion
9596 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9597   // Don't diagnose in unevaluated contexts.
9598   if (isUnevaluatedContext())
9599     return;
9600 
9601   // Don't diagnose for value- or type-dependent expressions.
9602   if (E->isTypeDependent() || E->isValueDependent())
9603     return;
9604 
9605   // Check for array bounds violations in cases where the check isn't triggered
9606   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9607   // ArraySubscriptExpr is on the RHS of a variable initialization.
9608   CheckArrayAccess(E);
9609 
9610   // This is not the right CC for (e.g.) a variable initialization.
9611   AnalyzeImplicitConversions(*this, E, CC);
9612 }
9613 
9614 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9615 /// Input argument E is a logical expression.
9616 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9617   ::CheckBoolLikeConversion(*this, E, CC);
9618 }
9619 
9620 /// Diagnose when expression is an integer constant expression and its evaluation
9621 /// results in integer overflow
9622 void Sema::CheckForIntOverflow (Expr *E) {
9623   // Use a work list to deal with nested struct initializers.
9624   SmallVector<Expr *, 2> Exprs(1, E);
9625 
9626   do {
9627     Expr *E = Exprs.pop_back_val();
9628 
9629     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9630       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9631       continue;
9632     }
9633 
9634     if (auto InitList = dyn_cast<InitListExpr>(E))
9635       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9636   } while (!Exprs.empty());
9637 }
9638 
9639 namespace {
9640 /// \brief Visitor for expressions which looks for unsequenced operations on the
9641 /// same object.
9642 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9643   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9644 
9645   /// \brief A tree of sequenced regions within an expression. Two regions are
9646   /// unsequenced if one is an ancestor or a descendent of the other. When we
9647   /// finish processing an expression with sequencing, such as a comma
9648   /// expression, we fold its tree nodes into its parent, since they are
9649   /// unsequenced with respect to nodes we will visit later.
9650   class SequenceTree {
9651     struct Value {
9652       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9653       unsigned Parent : 31;
9654       unsigned Merged : 1;
9655     };
9656     SmallVector<Value, 8> Values;
9657 
9658   public:
9659     /// \brief A region within an expression which may be sequenced with respect
9660     /// to some other region.
9661     class Seq {
9662       explicit Seq(unsigned N) : Index(N) {}
9663       unsigned Index;
9664       friend class SequenceTree;
9665     public:
9666       Seq() : Index(0) {}
9667     };
9668 
9669     SequenceTree() { Values.push_back(Value(0)); }
9670     Seq root() const { return Seq(0); }
9671 
9672     /// \brief Create a new sequence of operations, which is an unsequenced
9673     /// subset of \p Parent. This sequence of operations is sequenced with
9674     /// respect to other children of \p Parent.
9675     Seq allocate(Seq Parent) {
9676       Values.push_back(Value(Parent.Index));
9677       return Seq(Values.size() - 1);
9678     }
9679 
9680     /// \brief Merge a sequence of operations into its parent.
9681     void merge(Seq S) {
9682       Values[S.Index].Merged = true;
9683     }
9684 
9685     /// \brief Determine whether two operations are unsequenced. This operation
9686     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9687     /// should have been merged into its parent as appropriate.
9688     bool isUnsequenced(Seq Cur, Seq Old) {
9689       unsigned C = representative(Cur.Index);
9690       unsigned Target = representative(Old.Index);
9691       while (C >= Target) {
9692         if (C == Target)
9693           return true;
9694         C = Values[C].Parent;
9695       }
9696       return false;
9697     }
9698 
9699   private:
9700     /// \brief Pick a representative for a sequence.
9701     unsigned representative(unsigned K) {
9702       if (Values[K].Merged)
9703         // Perform path compression as we go.
9704         return Values[K].Parent = representative(Values[K].Parent);
9705       return K;
9706     }
9707   };
9708 
9709   /// An object for which we can track unsequenced uses.
9710   typedef NamedDecl *Object;
9711 
9712   /// Different flavors of object usage which we track. We only track the
9713   /// least-sequenced usage of each kind.
9714   enum UsageKind {
9715     /// A read of an object. Multiple unsequenced reads are OK.
9716     UK_Use,
9717     /// A modification of an object which is sequenced before the value
9718     /// computation of the expression, such as ++n in C++.
9719     UK_ModAsValue,
9720     /// A modification of an object which is not sequenced before the value
9721     /// computation of the expression, such as n++.
9722     UK_ModAsSideEffect,
9723 
9724     UK_Count = UK_ModAsSideEffect + 1
9725   };
9726 
9727   struct Usage {
9728     Usage() : Use(nullptr), Seq() {}
9729     Expr *Use;
9730     SequenceTree::Seq Seq;
9731   };
9732 
9733   struct UsageInfo {
9734     UsageInfo() : Diagnosed(false) {}
9735     Usage Uses[UK_Count];
9736     /// Have we issued a diagnostic for this variable already?
9737     bool Diagnosed;
9738   };
9739   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9740 
9741   Sema &SemaRef;
9742   /// Sequenced regions within the expression.
9743   SequenceTree Tree;
9744   /// Declaration modifications and references which we have seen.
9745   UsageInfoMap UsageMap;
9746   /// The region we are currently within.
9747   SequenceTree::Seq Region;
9748   /// Filled in with declarations which were modified as a side-effect
9749   /// (that is, post-increment operations).
9750   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9751   /// Expressions to check later. We defer checking these to reduce
9752   /// stack usage.
9753   SmallVectorImpl<Expr *> &WorkList;
9754 
9755   /// RAII object wrapping the visitation of a sequenced subexpression of an
9756   /// expression. At the end of this process, the side-effects of the evaluation
9757   /// become sequenced with respect to the value computation of the result, so
9758   /// we downgrade any UK_ModAsSideEffect within the evaluation to
9759   /// UK_ModAsValue.
9760   struct SequencedSubexpression {
9761     SequencedSubexpression(SequenceChecker &Self)
9762       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9763       Self.ModAsSideEffect = &ModAsSideEffect;
9764     }
9765     ~SequencedSubexpression() {
9766       for (auto &M : llvm::reverse(ModAsSideEffect)) {
9767         UsageInfo &U = Self.UsageMap[M.first];
9768         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9769         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9770         SideEffectUsage = M.second;
9771       }
9772       Self.ModAsSideEffect = OldModAsSideEffect;
9773     }
9774 
9775     SequenceChecker &Self;
9776     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9777     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9778   };
9779 
9780   /// RAII object wrapping the visitation of a subexpression which we might
9781   /// choose to evaluate as a constant. If any subexpression is evaluated and
9782   /// found to be non-constant, this allows us to suppress the evaluation of
9783   /// the outer expression.
9784   class EvaluationTracker {
9785   public:
9786     EvaluationTracker(SequenceChecker &Self)
9787         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9788       Self.EvalTracker = this;
9789     }
9790     ~EvaluationTracker() {
9791       Self.EvalTracker = Prev;
9792       if (Prev)
9793         Prev->EvalOK &= EvalOK;
9794     }
9795 
9796     bool evaluate(const Expr *E, bool &Result) {
9797       if (!EvalOK || E->isValueDependent())
9798         return false;
9799       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9800       return EvalOK;
9801     }
9802 
9803   private:
9804     SequenceChecker &Self;
9805     EvaluationTracker *Prev;
9806     bool EvalOK;
9807   } *EvalTracker;
9808 
9809   /// \brief Find the object which is produced by the specified expression,
9810   /// if any.
9811   Object getObject(Expr *E, bool Mod) const {
9812     E = E->IgnoreParenCasts();
9813     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9814       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9815         return getObject(UO->getSubExpr(), Mod);
9816     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9817       if (BO->getOpcode() == BO_Comma)
9818         return getObject(BO->getRHS(), Mod);
9819       if (Mod && BO->isAssignmentOp())
9820         return getObject(BO->getLHS(), Mod);
9821     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9822       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9823       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9824         return ME->getMemberDecl();
9825     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9826       // FIXME: If this is a reference, map through to its value.
9827       return DRE->getDecl();
9828     return nullptr;
9829   }
9830 
9831   /// \brief Note that an object was modified or used by an expression.
9832   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9833     Usage &U = UI.Uses[UK];
9834     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9835       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9836         ModAsSideEffect->push_back(std::make_pair(O, U));
9837       U.Use = Ref;
9838       U.Seq = Region;
9839     }
9840   }
9841   /// \brief Check whether a modification or use conflicts with a prior usage.
9842   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9843                   bool IsModMod) {
9844     if (UI.Diagnosed)
9845       return;
9846 
9847     const Usage &U = UI.Uses[OtherKind];
9848     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9849       return;
9850 
9851     Expr *Mod = U.Use;
9852     Expr *ModOrUse = Ref;
9853     if (OtherKind == UK_Use)
9854       std::swap(Mod, ModOrUse);
9855 
9856     SemaRef.Diag(Mod->getExprLoc(),
9857                  IsModMod ? diag::warn_unsequenced_mod_mod
9858                           : diag::warn_unsequenced_mod_use)
9859       << O << SourceRange(ModOrUse->getExprLoc());
9860     UI.Diagnosed = true;
9861   }
9862 
9863   void notePreUse(Object O, Expr *Use) {
9864     UsageInfo &U = UsageMap[O];
9865     // Uses conflict with other modifications.
9866     checkUsage(O, U, Use, UK_ModAsValue, false);
9867   }
9868   void notePostUse(Object O, Expr *Use) {
9869     UsageInfo &U = UsageMap[O];
9870     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9871     addUsage(U, O, Use, UK_Use);
9872   }
9873 
9874   void notePreMod(Object O, Expr *Mod) {
9875     UsageInfo &U = UsageMap[O];
9876     // Modifications conflict with other modifications and with uses.
9877     checkUsage(O, U, Mod, UK_ModAsValue, true);
9878     checkUsage(O, U, Mod, UK_Use, false);
9879   }
9880   void notePostMod(Object O, Expr *Use, UsageKind UK) {
9881     UsageInfo &U = UsageMap[O];
9882     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9883     addUsage(U, O, Use, UK);
9884   }
9885 
9886 public:
9887   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9888       : Base(S.Context), SemaRef(S), Region(Tree.root()),
9889         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9890     Visit(E);
9891   }
9892 
9893   void VisitStmt(Stmt *S) {
9894     // Skip all statements which aren't expressions for now.
9895   }
9896 
9897   void VisitExpr(Expr *E) {
9898     // By default, just recurse to evaluated subexpressions.
9899     Base::VisitStmt(E);
9900   }
9901 
9902   void VisitCastExpr(CastExpr *E) {
9903     Object O = Object();
9904     if (E->getCastKind() == CK_LValueToRValue)
9905       O = getObject(E->getSubExpr(), false);
9906 
9907     if (O)
9908       notePreUse(O, E);
9909     VisitExpr(E);
9910     if (O)
9911       notePostUse(O, E);
9912   }
9913 
9914   void VisitBinComma(BinaryOperator *BO) {
9915     // C++11 [expr.comma]p1:
9916     //   Every value computation and side effect associated with the left
9917     //   expression is sequenced before every value computation and side
9918     //   effect associated with the right expression.
9919     SequenceTree::Seq LHS = Tree.allocate(Region);
9920     SequenceTree::Seq RHS = Tree.allocate(Region);
9921     SequenceTree::Seq OldRegion = Region;
9922 
9923     {
9924       SequencedSubexpression SeqLHS(*this);
9925       Region = LHS;
9926       Visit(BO->getLHS());
9927     }
9928 
9929     Region = RHS;
9930     Visit(BO->getRHS());
9931 
9932     Region = OldRegion;
9933 
9934     // Forget that LHS and RHS are sequenced. They are both unsequenced
9935     // with respect to other stuff.
9936     Tree.merge(LHS);
9937     Tree.merge(RHS);
9938   }
9939 
9940   void VisitBinAssign(BinaryOperator *BO) {
9941     // The modification is sequenced after the value computation of the LHS
9942     // and RHS, so check it before inspecting the operands and update the
9943     // map afterwards.
9944     Object O = getObject(BO->getLHS(), true);
9945     if (!O)
9946       return VisitExpr(BO);
9947 
9948     notePreMod(O, BO);
9949 
9950     // C++11 [expr.ass]p7:
9951     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9952     //   only once.
9953     //
9954     // Therefore, for a compound assignment operator, O is considered used
9955     // everywhere except within the evaluation of E1 itself.
9956     if (isa<CompoundAssignOperator>(BO))
9957       notePreUse(O, BO);
9958 
9959     Visit(BO->getLHS());
9960 
9961     if (isa<CompoundAssignOperator>(BO))
9962       notePostUse(O, BO);
9963 
9964     Visit(BO->getRHS());
9965 
9966     // C++11 [expr.ass]p1:
9967     //   the assignment is sequenced [...] before the value computation of the
9968     //   assignment expression.
9969     // C11 6.5.16/3 has no such rule.
9970     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9971                                                        : UK_ModAsSideEffect);
9972   }
9973 
9974   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9975     VisitBinAssign(CAO);
9976   }
9977 
9978   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9979   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9980   void VisitUnaryPreIncDec(UnaryOperator *UO) {
9981     Object O = getObject(UO->getSubExpr(), true);
9982     if (!O)
9983       return VisitExpr(UO);
9984 
9985     notePreMod(O, UO);
9986     Visit(UO->getSubExpr());
9987     // C++11 [expr.pre.incr]p1:
9988     //   the expression ++x is equivalent to x+=1
9989     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9990                                                        : UK_ModAsSideEffect);
9991   }
9992 
9993   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9994   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9995   void VisitUnaryPostIncDec(UnaryOperator *UO) {
9996     Object O = getObject(UO->getSubExpr(), true);
9997     if (!O)
9998       return VisitExpr(UO);
9999 
10000     notePreMod(O, UO);
10001     Visit(UO->getSubExpr());
10002     notePostMod(O, UO, UK_ModAsSideEffect);
10003   }
10004 
10005   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10006   void VisitBinLOr(BinaryOperator *BO) {
10007     // The side-effects of the LHS of an '&&' are sequenced before the
10008     // value computation of the RHS, and hence before the value computation
10009     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10010     // as if they were unconditionally sequenced.
10011     EvaluationTracker Eval(*this);
10012     {
10013       SequencedSubexpression Sequenced(*this);
10014       Visit(BO->getLHS());
10015     }
10016 
10017     bool Result;
10018     if (Eval.evaluate(BO->getLHS(), Result)) {
10019       if (!Result)
10020         Visit(BO->getRHS());
10021     } else {
10022       // Check for unsequenced operations in the RHS, treating it as an
10023       // entirely separate evaluation.
10024       //
10025       // FIXME: If there are operations in the RHS which are unsequenced
10026       // with respect to operations outside the RHS, and those operations
10027       // are unconditionally evaluated, diagnose them.
10028       WorkList.push_back(BO->getRHS());
10029     }
10030   }
10031   void VisitBinLAnd(BinaryOperator *BO) {
10032     EvaluationTracker Eval(*this);
10033     {
10034       SequencedSubexpression Sequenced(*this);
10035       Visit(BO->getLHS());
10036     }
10037 
10038     bool Result;
10039     if (Eval.evaluate(BO->getLHS(), Result)) {
10040       if (Result)
10041         Visit(BO->getRHS());
10042     } else {
10043       WorkList.push_back(BO->getRHS());
10044     }
10045   }
10046 
10047   // Only visit the condition, unless we can be sure which subexpression will
10048   // be chosen.
10049   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10050     EvaluationTracker Eval(*this);
10051     {
10052       SequencedSubexpression Sequenced(*this);
10053       Visit(CO->getCond());
10054     }
10055 
10056     bool Result;
10057     if (Eval.evaluate(CO->getCond(), Result))
10058       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10059     else {
10060       WorkList.push_back(CO->getTrueExpr());
10061       WorkList.push_back(CO->getFalseExpr());
10062     }
10063   }
10064 
10065   void VisitCallExpr(CallExpr *CE) {
10066     // C++11 [intro.execution]p15:
10067     //   When calling a function [...], every value computation and side effect
10068     //   associated with any argument expression, or with the postfix expression
10069     //   designating the called function, is sequenced before execution of every
10070     //   expression or statement in the body of the function [and thus before
10071     //   the value computation of its result].
10072     SequencedSubexpression Sequenced(*this);
10073     Base::VisitCallExpr(CE);
10074 
10075     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10076   }
10077 
10078   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10079     // This is a call, so all subexpressions are sequenced before the result.
10080     SequencedSubexpression Sequenced(*this);
10081 
10082     if (!CCE->isListInitialization())
10083       return VisitExpr(CCE);
10084 
10085     // In C++11, list initializations are sequenced.
10086     SmallVector<SequenceTree::Seq, 32> Elts;
10087     SequenceTree::Seq Parent = Region;
10088     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10089                                         E = CCE->arg_end();
10090          I != E; ++I) {
10091       Region = Tree.allocate(Parent);
10092       Elts.push_back(Region);
10093       Visit(*I);
10094     }
10095 
10096     // Forget that the initializers are sequenced.
10097     Region = Parent;
10098     for (unsigned I = 0; I < Elts.size(); ++I)
10099       Tree.merge(Elts[I]);
10100   }
10101 
10102   void VisitInitListExpr(InitListExpr *ILE) {
10103     if (!SemaRef.getLangOpts().CPlusPlus11)
10104       return VisitExpr(ILE);
10105 
10106     // In C++11, list initializations are sequenced.
10107     SmallVector<SequenceTree::Seq, 32> Elts;
10108     SequenceTree::Seq Parent = Region;
10109     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10110       Expr *E = ILE->getInit(I);
10111       if (!E) continue;
10112       Region = Tree.allocate(Parent);
10113       Elts.push_back(Region);
10114       Visit(E);
10115     }
10116 
10117     // Forget that the initializers are sequenced.
10118     Region = Parent;
10119     for (unsigned I = 0; I < Elts.size(); ++I)
10120       Tree.merge(Elts[I]);
10121   }
10122 };
10123 } // end anonymous namespace
10124 
10125 void Sema::CheckUnsequencedOperations(Expr *E) {
10126   SmallVector<Expr *, 8> WorkList;
10127   WorkList.push_back(E);
10128   while (!WorkList.empty()) {
10129     Expr *Item = WorkList.pop_back_val();
10130     SequenceChecker(*this, Item, WorkList);
10131   }
10132 }
10133 
10134 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10135                               bool IsConstexpr) {
10136   CheckImplicitConversions(E, CheckLoc);
10137   if (!E->isInstantiationDependent())
10138     CheckUnsequencedOperations(E);
10139   if (!IsConstexpr && !E->isValueDependent())
10140     CheckForIntOverflow(E);
10141   DiagnoseMisalignedMembers();
10142 }
10143 
10144 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10145                                        FieldDecl *BitField,
10146                                        Expr *Init) {
10147   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10148 }
10149 
10150 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10151                                          SourceLocation Loc) {
10152   if (!PType->isVariablyModifiedType())
10153     return;
10154   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10155     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10156     return;
10157   }
10158   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10159     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10160     return;
10161   }
10162   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10163     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10164     return;
10165   }
10166 
10167   const ArrayType *AT = S.Context.getAsArrayType(PType);
10168   if (!AT)
10169     return;
10170 
10171   if (AT->getSizeModifier() != ArrayType::Star) {
10172     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10173     return;
10174   }
10175 
10176   S.Diag(Loc, diag::err_array_star_in_function_definition);
10177 }
10178 
10179 /// CheckParmsForFunctionDef - Check that the parameters of the given
10180 /// function are appropriate for the definition of a function. This
10181 /// takes care of any checks that cannot be performed on the
10182 /// declaration itself, e.g., that the types of each of the function
10183 /// parameters are complete.
10184 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10185                                     bool CheckParameterNames) {
10186   bool HasInvalidParm = false;
10187   for (ParmVarDecl *Param : Parameters) {
10188     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10189     // function declarator that is part of a function definition of
10190     // that function shall not have incomplete type.
10191     //
10192     // This is also C++ [dcl.fct]p6.
10193     if (!Param->isInvalidDecl() &&
10194         RequireCompleteType(Param->getLocation(), Param->getType(),
10195                             diag::err_typecheck_decl_incomplete_type)) {
10196       Param->setInvalidDecl();
10197       HasInvalidParm = true;
10198     }
10199 
10200     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10201     // declaration of each parameter shall include an identifier.
10202     if (CheckParameterNames &&
10203         Param->getIdentifier() == nullptr &&
10204         !Param->isImplicit() &&
10205         !getLangOpts().CPlusPlus)
10206       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10207 
10208     // C99 6.7.5.3p12:
10209     //   If the function declarator is not part of a definition of that
10210     //   function, parameters may have incomplete type and may use the [*]
10211     //   notation in their sequences of declarator specifiers to specify
10212     //   variable length array types.
10213     QualType PType = Param->getOriginalType();
10214     // FIXME: This diagnostic should point the '[*]' if source-location
10215     // information is added for it.
10216     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10217 
10218     // MSVC destroys objects passed by value in the callee.  Therefore a
10219     // function definition which takes such a parameter must be able to call the
10220     // object's destructor.  However, we don't perform any direct access check
10221     // on the dtor.
10222     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10223                                        .getCXXABI()
10224                                        .areArgsDestroyedLeftToRightInCallee()) {
10225       if (!Param->isInvalidDecl()) {
10226         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10227           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10228           if (!ClassDecl->isInvalidDecl() &&
10229               !ClassDecl->hasIrrelevantDestructor() &&
10230               !ClassDecl->isDependentContext()) {
10231             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10232             MarkFunctionReferenced(Param->getLocation(), Destructor);
10233             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10234           }
10235         }
10236       }
10237     }
10238 
10239     // Parameters with the pass_object_size attribute only need to be marked
10240     // constant at function definitions. Because we lack information about
10241     // whether we're on a declaration or definition when we're instantiating the
10242     // attribute, we need to check for constness here.
10243     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10244       if (!Param->getType().isConstQualified())
10245         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10246             << Attr->getSpelling() << 1;
10247   }
10248 
10249   return HasInvalidParm;
10250 }
10251 
10252 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10253 /// pointer cast increases the alignment requirements.
10254 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10255   // This is actually a lot of work to potentially be doing on every
10256   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10257   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10258     return;
10259 
10260   // Ignore dependent types.
10261   if (T->isDependentType() || Op->getType()->isDependentType())
10262     return;
10263 
10264   // Require that the destination be a pointer type.
10265   const PointerType *DestPtr = T->getAs<PointerType>();
10266   if (!DestPtr) return;
10267 
10268   // If the destination has alignment 1, we're done.
10269   QualType DestPointee = DestPtr->getPointeeType();
10270   if (DestPointee->isIncompleteType()) return;
10271   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10272   if (DestAlign.isOne()) return;
10273 
10274   // Require that the source be a pointer type.
10275   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10276   if (!SrcPtr) return;
10277   QualType SrcPointee = SrcPtr->getPointeeType();
10278 
10279   // Whitelist casts from cv void*.  We already implicitly
10280   // whitelisted casts to cv void*, since they have alignment 1.
10281   // Also whitelist casts involving incomplete types, which implicitly
10282   // includes 'void'.
10283   if (SrcPointee->isIncompleteType()) return;
10284 
10285   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10286   if (SrcAlign >= DestAlign) return;
10287 
10288   Diag(TRange.getBegin(), diag::warn_cast_align)
10289     << Op->getType() << T
10290     << static_cast<unsigned>(SrcAlign.getQuantity())
10291     << static_cast<unsigned>(DestAlign.getQuantity())
10292     << TRange << Op->getSourceRange();
10293 }
10294 
10295 /// \brief Check whether this array fits the idiom of a size-one tail padded
10296 /// array member of a struct.
10297 ///
10298 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10299 /// commonly used to emulate flexible arrays in C89 code.
10300 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10301                                     const NamedDecl *ND) {
10302   if (Size != 1 || !ND) return false;
10303 
10304   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10305   if (!FD) return false;
10306 
10307   // Don't consider sizes resulting from macro expansions or template argument
10308   // substitution to form C89 tail-padded arrays.
10309 
10310   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10311   while (TInfo) {
10312     TypeLoc TL = TInfo->getTypeLoc();
10313     // Look through typedefs.
10314     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10315       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10316       TInfo = TDL->getTypeSourceInfo();
10317       continue;
10318     }
10319     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10320       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10321       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10322         return false;
10323     }
10324     break;
10325   }
10326 
10327   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10328   if (!RD) return false;
10329   if (RD->isUnion()) return false;
10330   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10331     if (!CRD->isStandardLayout()) return false;
10332   }
10333 
10334   // See if this is the last field decl in the record.
10335   const Decl *D = FD;
10336   while ((D = D->getNextDeclInContext()))
10337     if (isa<FieldDecl>(D))
10338       return false;
10339   return true;
10340 }
10341 
10342 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10343                             const ArraySubscriptExpr *ASE,
10344                             bool AllowOnePastEnd, bool IndexNegated) {
10345   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10346   if (IndexExpr->isValueDependent())
10347     return;
10348 
10349   const Type *EffectiveType =
10350       BaseExpr->getType()->getPointeeOrArrayElementType();
10351   BaseExpr = BaseExpr->IgnoreParenCasts();
10352   const ConstantArrayType *ArrayTy =
10353     Context.getAsConstantArrayType(BaseExpr->getType());
10354   if (!ArrayTy)
10355     return;
10356 
10357   llvm::APSInt index;
10358   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10359     return;
10360   if (IndexNegated)
10361     index = -index;
10362 
10363   const NamedDecl *ND = nullptr;
10364   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10365     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10366   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10367     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10368 
10369   if (index.isUnsigned() || !index.isNegative()) {
10370     llvm::APInt size = ArrayTy->getSize();
10371     if (!size.isStrictlyPositive())
10372       return;
10373 
10374     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10375     if (BaseType != EffectiveType) {
10376       // Make sure we're comparing apples to apples when comparing index to size
10377       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10378       uint64_t array_typesize = Context.getTypeSize(BaseType);
10379       // Handle ptrarith_typesize being zero, such as when casting to void*
10380       if (!ptrarith_typesize) ptrarith_typesize = 1;
10381       if (ptrarith_typesize != array_typesize) {
10382         // There's a cast to a different size type involved
10383         uint64_t ratio = array_typesize / ptrarith_typesize;
10384         // TODO: Be smarter about handling cases where array_typesize is not a
10385         // multiple of ptrarith_typesize
10386         if (ptrarith_typesize * ratio == array_typesize)
10387           size *= llvm::APInt(size.getBitWidth(), ratio);
10388       }
10389     }
10390 
10391     if (size.getBitWidth() > index.getBitWidth())
10392       index = index.zext(size.getBitWidth());
10393     else if (size.getBitWidth() < index.getBitWidth())
10394       size = size.zext(index.getBitWidth());
10395 
10396     // For array subscripting the index must be less than size, but for pointer
10397     // arithmetic also allow the index (offset) to be equal to size since
10398     // computing the next address after the end of the array is legal and
10399     // commonly done e.g. in C++ iterators and range-based for loops.
10400     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10401       return;
10402 
10403     // Also don't warn for arrays of size 1 which are members of some
10404     // structure. These are often used to approximate flexible arrays in C89
10405     // code.
10406     if (IsTailPaddedMemberArray(*this, size, ND))
10407       return;
10408 
10409     // Suppress the warning if the subscript expression (as identified by the
10410     // ']' location) and the index expression are both from macro expansions
10411     // within a system header.
10412     if (ASE) {
10413       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10414           ASE->getRBracketLoc());
10415       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10416         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10417             IndexExpr->getLocStart());
10418         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10419           return;
10420       }
10421     }
10422 
10423     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10424     if (ASE)
10425       DiagID = diag::warn_array_index_exceeds_bounds;
10426 
10427     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10428                         PDiag(DiagID) << index.toString(10, true)
10429                           << size.toString(10, true)
10430                           << (unsigned)size.getLimitedValue(~0U)
10431                           << IndexExpr->getSourceRange());
10432   } else {
10433     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10434     if (!ASE) {
10435       DiagID = diag::warn_ptr_arith_precedes_bounds;
10436       if (index.isNegative()) index = -index;
10437     }
10438 
10439     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10440                         PDiag(DiagID) << index.toString(10, true)
10441                           << IndexExpr->getSourceRange());
10442   }
10443 
10444   if (!ND) {
10445     // Try harder to find a NamedDecl to point at in the note.
10446     while (const ArraySubscriptExpr *ASE =
10447            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10448       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10449     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10450       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10451     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10452       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10453   }
10454 
10455   if (ND)
10456     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10457                         PDiag(diag::note_array_index_out_of_bounds)
10458                           << ND->getDeclName());
10459 }
10460 
10461 void Sema::CheckArrayAccess(const Expr *expr) {
10462   int AllowOnePastEnd = 0;
10463   while (expr) {
10464     expr = expr->IgnoreParenImpCasts();
10465     switch (expr->getStmtClass()) {
10466       case Stmt::ArraySubscriptExprClass: {
10467         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10468         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10469                          AllowOnePastEnd > 0);
10470         return;
10471       }
10472       case Stmt::OMPArraySectionExprClass: {
10473         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10474         if (ASE->getLowerBound())
10475           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10476                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
10477         return;
10478       }
10479       case Stmt::UnaryOperatorClass: {
10480         // Only unwrap the * and & unary operators
10481         const UnaryOperator *UO = cast<UnaryOperator>(expr);
10482         expr = UO->getSubExpr();
10483         switch (UO->getOpcode()) {
10484           case UO_AddrOf:
10485             AllowOnePastEnd++;
10486             break;
10487           case UO_Deref:
10488             AllowOnePastEnd--;
10489             break;
10490           default:
10491             return;
10492         }
10493         break;
10494       }
10495       case Stmt::ConditionalOperatorClass: {
10496         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10497         if (const Expr *lhs = cond->getLHS())
10498           CheckArrayAccess(lhs);
10499         if (const Expr *rhs = cond->getRHS())
10500           CheckArrayAccess(rhs);
10501         return;
10502       }
10503       default:
10504         return;
10505     }
10506   }
10507 }
10508 
10509 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10510 
10511 namespace {
10512   struct RetainCycleOwner {
10513     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10514     VarDecl *Variable;
10515     SourceRange Range;
10516     SourceLocation Loc;
10517     bool Indirect;
10518 
10519     void setLocsFrom(Expr *e) {
10520       Loc = e->getExprLoc();
10521       Range = e->getSourceRange();
10522     }
10523   };
10524 } // end anonymous namespace
10525 
10526 /// Consider whether capturing the given variable can possibly lead to
10527 /// a retain cycle.
10528 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10529   // In ARC, it's captured strongly iff the variable has __strong
10530   // lifetime.  In MRR, it's captured strongly if the variable is
10531   // __block and has an appropriate type.
10532   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10533     return false;
10534 
10535   owner.Variable = var;
10536   if (ref)
10537     owner.setLocsFrom(ref);
10538   return true;
10539 }
10540 
10541 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10542   while (true) {
10543     e = e->IgnoreParens();
10544     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10545       switch (cast->getCastKind()) {
10546       case CK_BitCast:
10547       case CK_LValueBitCast:
10548       case CK_LValueToRValue:
10549       case CK_ARCReclaimReturnedObject:
10550         e = cast->getSubExpr();
10551         continue;
10552 
10553       default:
10554         return false;
10555       }
10556     }
10557 
10558     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10559       ObjCIvarDecl *ivar = ref->getDecl();
10560       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10561         return false;
10562 
10563       // Try to find a retain cycle in the base.
10564       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10565         return false;
10566 
10567       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10568       owner.Indirect = true;
10569       return true;
10570     }
10571 
10572     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10573       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10574       if (!var) return false;
10575       return considerVariable(var, ref, owner);
10576     }
10577 
10578     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10579       if (member->isArrow()) return false;
10580 
10581       // Don't count this as an indirect ownership.
10582       e = member->getBase();
10583       continue;
10584     }
10585 
10586     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10587       // Only pay attention to pseudo-objects on property references.
10588       ObjCPropertyRefExpr *pre
10589         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10590                                               ->IgnoreParens());
10591       if (!pre) return false;
10592       if (pre->isImplicitProperty()) return false;
10593       ObjCPropertyDecl *property = pre->getExplicitProperty();
10594       if (!property->isRetaining() &&
10595           !(property->getPropertyIvarDecl() &&
10596             property->getPropertyIvarDecl()->getType()
10597               .getObjCLifetime() == Qualifiers::OCL_Strong))
10598           return false;
10599 
10600       owner.Indirect = true;
10601       if (pre->isSuperReceiver()) {
10602         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10603         if (!owner.Variable)
10604           return false;
10605         owner.Loc = pre->getLocation();
10606         owner.Range = pre->getSourceRange();
10607         return true;
10608       }
10609       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10610                               ->getSourceExpr());
10611       continue;
10612     }
10613 
10614     // Array ivars?
10615 
10616     return false;
10617   }
10618 }
10619 
10620 namespace {
10621   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10622     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10623       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10624         Context(Context), Variable(variable), Capturer(nullptr),
10625         VarWillBeReased(false) {}
10626     ASTContext &Context;
10627     VarDecl *Variable;
10628     Expr *Capturer;
10629     bool VarWillBeReased;
10630 
10631     void VisitDeclRefExpr(DeclRefExpr *ref) {
10632       if (ref->getDecl() == Variable && !Capturer)
10633         Capturer = ref;
10634     }
10635 
10636     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10637       if (Capturer) return;
10638       Visit(ref->getBase());
10639       if (Capturer && ref->isFreeIvar())
10640         Capturer = ref;
10641     }
10642 
10643     void VisitBlockExpr(BlockExpr *block) {
10644       // Look inside nested blocks
10645       if (block->getBlockDecl()->capturesVariable(Variable))
10646         Visit(block->getBlockDecl()->getBody());
10647     }
10648 
10649     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10650       if (Capturer) return;
10651       if (OVE->getSourceExpr())
10652         Visit(OVE->getSourceExpr());
10653     }
10654     void VisitBinaryOperator(BinaryOperator *BinOp) {
10655       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10656         return;
10657       Expr *LHS = BinOp->getLHS();
10658       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10659         if (DRE->getDecl() != Variable)
10660           return;
10661         if (Expr *RHS = BinOp->getRHS()) {
10662           RHS = RHS->IgnoreParenCasts();
10663           llvm::APSInt Value;
10664           VarWillBeReased =
10665             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10666         }
10667       }
10668     }
10669   };
10670 } // end anonymous namespace
10671 
10672 /// Check whether the given argument is a block which captures a
10673 /// variable.
10674 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10675   assert(owner.Variable && owner.Loc.isValid());
10676 
10677   e = e->IgnoreParenCasts();
10678 
10679   // Look through [^{...} copy] and Block_copy(^{...}).
10680   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10681     Selector Cmd = ME->getSelector();
10682     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10683       e = ME->getInstanceReceiver();
10684       if (!e)
10685         return nullptr;
10686       e = e->IgnoreParenCasts();
10687     }
10688   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10689     if (CE->getNumArgs() == 1) {
10690       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10691       if (Fn) {
10692         const IdentifierInfo *FnI = Fn->getIdentifier();
10693         if (FnI && FnI->isStr("_Block_copy")) {
10694           e = CE->getArg(0)->IgnoreParenCasts();
10695         }
10696       }
10697     }
10698   }
10699 
10700   BlockExpr *block = dyn_cast<BlockExpr>(e);
10701   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10702     return nullptr;
10703 
10704   FindCaptureVisitor visitor(S.Context, owner.Variable);
10705   visitor.Visit(block->getBlockDecl()->getBody());
10706   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10707 }
10708 
10709 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10710                                 RetainCycleOwner &owner) {
10711   assert(capturer);
10712   assert(owner.Variable && owner.Loc.isValid());
10713 
10714   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10715     << owner.Variable << capturer->getSourceRange();
10716   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10717     << owner.Indirect << owner.Range;
10718 }
10719 
10720 /// Check for a keyword selector that starts with the word 'add' or
10721 /// 'set'.
10722 static bool isSetterLikeSelector(Selector sel) {
10723   if (sel.isUnarySelector()) return false;
10724 
10725   StringRef str = sel.getNameForSlot(0);
10726   while (!str.empty() && str.front() == '_') str = str.substr(1);
10727   if (str.startswith("set"))
10728     str = str.substr(3);
10729   else if (str.startswith("add")) {
10730     // Specially whitelist 'addOperationWithBlock:'.
10731     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10732       return false;
10733     str = str.substr(3);
10734   }
10735   else
10736     return false;
10737 
10738   if (str.empty()) return true;
10739   return !isLowercase(str.front());
10740 }
10741 
10742 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10743                                                     ObjCMessageExpr *Message) {
10744   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10745                                                 Message->getReceiverInterface(),
10746                                                 NSAPI::ClassId_NSMutableArray);
10747   if (!IsMutableArray) {
10748     return None;
10749   }
10750 
10751   Selector Sel = Message->getSelector();
10752 
10753   Optional<NSAPI::NSArrayMethodKind> MKOpt =
10754     S.NSAPIObj->getNSArrayMethodKind(Sel);
10755   if (!MKOpt) {
10756     return None;
10757   }
10758 
10759   NSAPI::NSArrayMethodKind MK = *MKOpt;
10760 
10761   switch (MK) {
10762     case NSAPI::NSMutableArr_addObject:
10763     case NSAPI::NSMutableArr_insertObjectAtIndex:
10764     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10765       return 0;
10766     case NSAPI::NSMutableArr_replaceObjectAtIndex:
10767       return 1;
10768 
10769     default:
10770       return None;
10771   }
10772 
10773   return None;
10774 }
10775 
10776 static
10777 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10778                                                   ObjCMessageExpr *Message) {
10779   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10780                                             Message->getReceiverInterface(),
10781                                             NSAPI::ClassId_NSMutableDictionary);
10782   if (!IsMutableDictionary) {
10783     return None;
10784   }
10785 
10786   Selector Sel = Message->getSelector();
10787 
10788   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10789     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10790   if (!MKOpt) {
10791     return None;
10792   }
10793 
10794   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10795 
10796   switch (MK) {
10797     case NSAPI::NSMutableDict_setObjectForKey:
10798     case NSAPI::NSMutableDict_setValueForKey:
10799     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10800       return 0;
10801 
10802     default:
10803       return None;
10804   }
10805 
10806   return None;
10807 }
10808 
10809 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10810   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10811                                                 Message->getReceiverInterface(),
10812                                                 NSAPI::ClassId_NSMutableSet);
10813 
10814   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10815                                             Message->getReceiverInterface(),
10816                                             NSAPI::ClassId_NSMutableOrderedSet);
10817   if (!IsMutableSet && !IsMutableOrderedSet) {
10818     return None;
10819   }
10820 
10821   Selector Sel = Message->getSelector();
10822 
10823   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10824   if (!MKOpt) {
10825     return None;
10826   }
10827 
10828   NSAPI::NSSetMethodKind MK = *MKOpt;
10829 
10830   switch (MK) {
10831     case NSAPI::NSMutableSet_addObject:
10832     case NSAPI::NSOrderedSet_setObjectAtIndex:
10833     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10834     case NSAPI::NSOrderedSet_insertObjectAtIndex:
10835       return 0;
10836     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10837       return 1;
10838   }
10839 
10840   return None;
10841 }
10842 
10843 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10844   if (!Message->isInstanceMessage()) {
10845     return;
10846   }
10847 
10848   Optional<int> ArgOpt;
10849 
10850   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10851       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10852       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10853     return;
10854   }
10855 
10856   int ArgIndex = *ArgOpt;
10857 
10858   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10859   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10860     Arg = OE->getSourceExpr()->IgnoreImpCasts();
10861   }
10862 
10863   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10864     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10865       if (ArgRE->isObjCSelfExpr()) {
10866         Diag(Message->getSourceRange().getBegin(),
10867              diag::warn_objc_circular_container)
10868           << ArgRE->getDecl()->getName() << StringRef("super");
10869       }
10870     }
10871   } else {
10872     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10873 
10874     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10875       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10876     }
10877 
10878     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10879       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10880         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10881           ValueDecl *Decl = ReceiverRE->getDecl();
10882           Diag(Message->getSourceRange().getBegin(),
10883                diag::warn_objc_circular_container)
10884             << Decl->getName() << Decl->getName();
10885           if (!ArgRE->isObjCSelfExpr()) {
10886             Diag(Decl->getLocation(),
10887                  diag::note_objc_circular_container_declared_here)
10888               << Decl->getName();
10889           }
10890         }
10891       }
10892     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10893       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10894         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10895           ObjCIvarDecl *Decl = IvarRE->getDecl();
10896           Diag(Message->getSourceRange().getBegin(),
10897                diag::warn_objc_circular_container)
10898             << Decl->getName() << Decl->getName();
10899           Diag(Decl->getLocation(),
10900                diag::note_objc_circular_container_declared_here)
10901             << Decl->getName();
10902         }
10903       }
10904     }
10905   }
10906 }
10907 
10908 /// Check a message send to see if it's likely to cause a retain cycle.
10909 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10910   // Only check instance methods whose selector looks like a setter.
10911   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10912     return;
10913 
10914   // Try to find a variable that the receiver is strongly owned by.
10915   RetainCycleOwner owner;
10916   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
10917     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
10918       return;
10919   } else {
10920     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10921     owner.Variable = getCurMethodDecl()->getSelfDecl();
10922     owner.Loc = msg->getSuperLoc();
10923     owner.Range = msg->getSuperLoc();
10924   }
10925 
10926   // Check whether the receiver is captured by any of the arguments.
10927   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10928     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10929       return diagnoseRetainCycle(*this, capturer, owner);
10930 }
10931 
10932 /// Check a property assign to see if it's likely to cause a retain cycle.
10933 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10934   RetainCycleOwner owner;
10935   if (!findRetainCycleOwner(*this, receiver, owner))
10936     return;
10937 
10938   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10939     diagnoseRetainCycle(*this, capturer, owner);
10940 }
10941 
10942 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10943   RetainCycleOwner Owner;
10944   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
10945     return;
10946 
10947   // Because we don't have an expression for the variable, we have to set the
10948   // location explicitly here.
10949   Owner.Loc = Var->getLocation();
10950   Owner.Range = Var->getSourceRange();
10951 
10952   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10953     diagnoseRetainCycle(*this, Capturer, Owner);
10954 }
10955 
10956 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10957                                      Expr *RHS, bool isProperty) {
10958   // Check if RHS is an Objective-C object literal, which also can get
10959   // immediately zapped in a weak reference.  Note that we explicitly
10960   // allow ObjCStringLiterals, since those are designed to never really die.
10961   RHS = RHS->IgnoreParenImpCasts();
10962 
10963   // This enum needs to match with the 'select' in
10964   // warn_objc_arc_literal_assign (off-by-1).
10965   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10966   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10967     return false;
10968 
10969   S.Diag(Loc, diag::warn_arc_literal_assign)
10970     << (unsigned) Kind
10971     << (isProperty ? 0 : 1)
10972     << RHS->getSourceRange();
10973 
10974   return true;
10975 }
10976 
10977 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10978                                     Qualifiers::ObjCLifetime LT,
10979                                     Expr *RHS, bool isProperty) {
10980   // Strip off any implicit cast added to get to the one ARC-specific.
10981   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10982     if (cast->getCastKind() == CK_ARCConsumeObject) {
10983       S.Diag(Loc, diag::warn_arc_retained_assign)
10984         << (LT == Qualifiers::OCL_ExplicitNone)
10985         << (isProperty ? 0 : 1)
10986         << RHS->getSourceRange();
10987       return true;
10988     }
10989     RHS = cast->getSubExpr();
10990   }
10991 
10992   if (LT == Qualifiers::OCL_Weak &&
10993       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10994     return true;
10995 
10996   return false;
10997 }
10998 
10999 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11000                               QualType LHS, Expr *RHS) {
11001   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11002 
11003   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11004     return false;
11005 
11006   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11007     return true;
11008 
11009   return false;
11010 }
11011 
11012 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11013                               Expr *LHS, Expr *RHS) {
11014   QualType LHSType;
11015   // PropertyRef on LHS type need be directly obtained from
11016   // its declaration as it has a PseudoType.
11017   ObjCPropertyRefExpr *PRE
11018     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11019   if (PRE && !PRE->isImplicitProperty()) {
11020     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11021     if (PD)
11022       LHSType = PD->getType();
11023   }
11024 
11025   if (LHSType.isNull())
11026     LHSType = LHS->getType();
11027 
11028   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11029 
11030   if (LT == Qualifiers::OCL_Weak) {
11031     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11032       getCurFunction()->markSafeWeakUse(LHS);
11033   }
11034 
11035   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11036     return;
11037 
11038   // FIXME. Check for other life times.
11039   if (LT != Qualifiers::OCL_None)
11040     return;
11041 
11042   if (PRE) {
11043     if (PRE->isImplicitProperty())
11044       return;
11045     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11046     if (!PD)
11047       return;
11048 
11049     unsigned Attributes = PD->getPropertyAttributes();
11050     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11051       // when 'assign' attribute was not explicitly specified
11052       // by user, ignore it and rely on property type itself
11053       // for lifetime info.
11054       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11055       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11056           LHSType->isObjCRetainableType())
11057         return;
11058 
11059       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11060         if (cast->getCastKind() == CK_ARCConsumeObject) {
11061           Diag(Loc, diag::warn_arc_retained_property_assign)
11062           << RHS->getSourceRange();
11063           return;
11064         }
11065         RHS = cast->getSubExpr();
11066       }
11067     }
11068     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11069       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11070         return;
11071     }
11072   }
11073 }
11074 
11075 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11076 
11077 namespace {
11078 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11079                                  SourceLocation StmtLoc,
11080                                  const NullStmt *Body) {
11081   // Do not warn if the body is a macro that expands to nothing, e.g:
11082   //
11083   // #define CALL(x)
11084   // if (condition)
11085   //   CALL(0);
11086   //
11087   if (Body->hasLeadingEmptyMacro())
11088     return false;
11089 
11090   // Get line numbers of statement and body.
11091   bool StmtLineInvalid;
11092   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11093                                                       &StmtLineInvalid);
11094   if (StmtLineInvalid)
11095     return false;
11096 
11097   bool BodyLineInvalid;
11098   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11099                                                       &BodyLineInvalid);
11100   if (BodyLineInvalid)
11101     return false;
11102 
11103   // Warn if null statement and body are on the same line.
11104   if (StmtLine != BodyLine)
11105     return false;
11106 
11107   return true;
11108 }
11109 } // end anonymous namespace
11110 
11111 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11112                                  const Stmt *Body,
11113                                  unsigned DiagID) {
11114   // Since this is a syntactic check, don't emit diagnostic for template
11115   // instantiations, this just adds noise.
11116   if (CurrentInstantiationScope)
11117     return;
11118 
11119   // The body should be a null statement.
11120   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11121   if (!NBody)
11122     return;
11123 
11124   // Do the usual checks.
11125   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11126     return;
11127 
11128   Diag(NBody->getSemiLoc(), DiagID);
11129   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11130 }
11131 
11132 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11133                                  const Stmt *PossibleBody) {
11134   assert(!CurrentInstantiationScope); // Ensured by caller
11135 
11136   SourceLocation StmtLoc;
11137   const Stmt *Body;
11138   unsigned DiagID;
11139   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11140     StmtLoc = FS->getRParenLoc();
11141     Body = FS->getBody();
11142     DiagID = diag::warn_empty_for_body;
11143   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11144     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11145     Body = WS->getBody();
11146     DiagID = diag::warn_empty_while_body;
11147   } else
11148     return; // Neither `for' nor `while'.
11149 
11150   // The body should be a null statement.
11151   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11152   if (!NBody)
11153     return;
11154 
11155   // Skip expensive checks if diagnostic is disabled.
11156   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11157     return;
11158 
11159   // Do the usual checks.
11160   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11161     return;
11162 
11163   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11164   // noise level low, emit diagnostics only if for/while is followed by a
11165   // CompoundStmt, e.g.:
11166   //    for (int i = 0; i < n; i++);
11167   //    {
11168   //      a(i);
11169   //    }
11170   // or if for/while is followed by a statement with more indentation
11171   // than for/while itself:
11172   //    for (int i = 0; i < n; i++);
11173   //      a(i);
11174   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11175   if (!ProbableTypo) {
11176     bool BodyColInvalid;
11177     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11178                              PossibleBody->getLocStart(),
11179                              &BodyColInvalid);
11180     if (BodyColInvalid)
11181       return;
11182 
11183     bool StmtColInvalid;
11184     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11185                              S->getLocStart(),
11186                              &StmtColInvalid);
11187     if (StmtColInvalid)
11188       return;
11189 
11190     if (BodyCol > StmtCol)
11191       ProbableTypo = true;
11192   }
11193 
11194   if (ProbableTypo) {
11195     Diag(NBody->getSemiLoc(), DiagID);
11196     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11197   }
11198 }
11199 
11200 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11201 
11202 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11203 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11204                              SourceLocation OpLoc) {
11205   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11206     return;
11207 
11208   if (!ActiveTemplateInstantiations.empty())
11209     return;
11210 
11211   // Strip parens and casts away.
11212   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11213   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11214 
11215   // Check for a call expression
11216   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11217   if (!CE || CE->getNumArgs() != 1)
11218     return;
11219 
11220   // Check for a call to std::move
11221   const FunctionDecl *FD = CE->getDirectCallee();
11222   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11223       !FD->getIdentifier()->isStr("move"))
11224     return;
11225 
11226   // Get argument from std::move
11227   RHSExpr = CE->getArg(0);
11228 
11229   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11230   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11231 
11232   // Two DeclRefExpr's, check that the decls are the same.
11233   if (LHSDeclRef && RHSDeclRef) {
11234     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11235       return;
11236     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11237         RHSDeclRef->getDecl()->getCanonicalDecl())
11238       return;
11239 
11240     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11241                                         << LHSExpr->getSourceRange()
11242                                         << RHSExpr->getSourceRange();
11243     return;
11244   }
11245 
11246   // Member variables require a different approach to check for self moves.
11247   // MemberExpr's are the same if every nested MemberExpr refers to the same
11248   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11249   // the base Expr's are CXXThisExpr's.
11250   const Expr *LHSBase = LHSExpr;
11251   const Expr *RHSBase = RHSExpr;
11252   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11253   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11254   if (!LHSME || !RHSME)
11255     return;
11256 
11257   while (LHSME && RHSME) {
11258     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11259         RHSME->getMemberDecl()->getCanonicalDecl())
11260       return;
11261 
11262     LHSBase = LHSME->getBase();
11263     RHSBase = RHSME->getBase();
11264     LHSME = dyn_cast<MemberExpr>(LHSBase);
11265     RHSME = dyn_cast<MemberExpr>(RHSBase);
11266   }
11267 
11268   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11269   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11270   if (LHSDeclRef && RHSDeclRef) {
11271     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11272       return;
11273     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11274         RHSDeclRef->getDecl()->getCanonicalDecl())
11275       return;
11276 
11277     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11278                                         << LHSExpr->getSourceRange()
11279                                         << RHSExpr->getSourceRange();
11280     return;
11281   }
11282 
11283   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11284     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11285                                         << LHSExpr->getSourceRange()
11286                                         << RHSExpr->getSourceRange();
11287 }
11288 
11289 //===--- Layout compatibility ----------------------------------------------//
11290 
11291 namespace {
11292 
11293 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11294 
11295 /// \brief Check if two enumeration types are layout-compatible.
11296 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11297   // C++11 [dcl.enum] p8:
11298   // Two enumeration types are layout-compatible if they have the same
11299   // underlying type.
11300   return ED1->isComplete() && ED2->isComplete() &&
11301          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11302 }
11303 
11304 /// \brief Check if two fields are layout-compatible.
11305 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11306   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11307     return false;
11308 
11309   if (Field1->isBitField() != Field2->isBitField())
11310     return false;
11311 
11312   if (Field1->isBitField()) {
11313     // Make sure that the bit-fields are the same length.
11314     unsigned Bits1 = Field1->getBitWidthValue(C);
11315     unsigned Bits2 = Field2->getBitWidthValue(C);
11316 
11317     if (Bits1 != Bits2)
11318       return false;
11319   }
11320 
11321   return true;
11322 }
11323 
11324 /// \brief Check if two standard-layout structs are layout-compatible.
11325 /// (C++11 [class.mem] p17)
11326 bool isLayoutCompatibleStruct(ASTContext &C,
11327                               RecordDecl *RD1,
11328                               RecordDecl *RD2) {
11329   // If both records are C++ classes, check that base classes match.
11330   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11331     // If one of records is a CXXRecordDecl we are in C++ mode,
11332     // thus the other one is a CXXRecordDecl, too.
11333     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11334     // Check number of base classes.
11335     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11336       return false;
11337 
11338     // Check the base classes.
11339     for (CXXRecordDecl::base_class_const_iterator
11340                Base1 = D1CXX->bases_begin(),
11341            BaseEnd1 = D1CXX->bases_end(),
11342               Base2 = D2CXX->bases_begin();
11343          Base1 != BaseEnd1;
11344          ++Base1, ++Base2) {
11345       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11346         return false;
11347     }
11348   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11349     // If only RD2 is a C++ class, it should have zero base classes.
11350     if (D2CXX->getNumBases() > 0)
11351       return false;
11352   }
11353 
11354   // Check the fields.
11355   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11356                              Field2End = RD2->field_end(),
11357                              Field1 = RD1->field_begin(),
11358                              Field1End = RD1->field_end();
11359   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11360     if (!isLayoutCompatible(C, *Field1, *Field2))
11361       return false;
11362   }
11363   if (Field1 != Field1End || Field2 != Field2End)
11364     return false;
11365 
11366   return true;
11367 }
11368 
11369 /// \brief Check if two standard-layout unions are layout-compatible.
11370 /// (C++11 [class.mem] p18)
11371 bool isLayoutCompatibleUnion(ASTContext &C,
11372                              RecordDecl *RD1,
11373                              RecordDecl *RD2) {
11374   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11375   for (auto *Field2 : RD2->fields())
11376     UnmatchedFields.insert(Field2);
11377 
11378   for (auto *Field1 : RD1->fields()) {
11379     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11380         I = UnmatchedFields.begin(),
11381         E = UnmatchedFields.end();
11382 
11383     for ( ; I != E; ++I) {
11384       if (isLayoutCompatible(C, Field1, *I)) {
11385         bool Result = UnmatchedFields.erase(*I);
11386         (void) Result;
11387         assert(Result);
11388         break;
11389       }
11390     }
11391     if (I == E)
11392       return false;
11393   }
11394 
11395   return UnmatchedFields.empty();
11396 }
11397 
11398 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11399   if (RD1->isUnion() != RD2->isUnion())
11400     return false;
11401 
11402   if (RD1->isUnion())
11403     return isLayoutCompatibleUnion(C, RD1, RD2);
11404   else
11405     return isLayoutCompatibleStruct(C, RD1, RD2);
11406 }
11407 
11408 /// \brief Check if two types are layout-compatible in C++11 sense.
11409 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11410   if (T1.isNull() || T2.isNull())
11411     return false;
11412 
11413   // C++11 [basic.types] p11:
11414   // If two types T1 and T2 are the same type, then T1 and T2 are
11415   // layout-compatible types.
11416   if (C.hasSameType(T1, T2))
11417     return true;
11418 
11419   T1 = T1.getCanonicalType().getUnqualifiedType();
11420   T2 = T2.getCanonicalType().getUnqualifiedType();
11421 
11422   const Type::TypeClass TC1 = T1->getTypeClass();
11423   const Type::TypeClass TC2 = T2->getTypeClass();
11424 
11425   if (TC1 != TC2)
11426     return false;
11427 
11428   if (TC1 == Type::Enum) {
11429     return isLayoutCompatible(C,
11430                               cast<EnumType>(T1)->getDecl(),
11431                               cast<EnumType>(T2)->getDecl());
11432   } else if (TC1 == Type::Record) {
11433     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11434       return false;
11435 
11436     return isLayoutCompatible(C,
11437                               cast<RecordType>(T1)->getDecl(),
11438                               cast<RecordType>(T2)->getDecl());
11439   }
11440 
11441   return false;
11442 }
11443 } // end anonymous namespace
11444 
11445 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11446 
11447 namespace {
11448 /// \brief Given a type tag expression find the type tag itself.
11449 ///
11450 /// \param TypeExpr Type tag expression, as it appears in user's code.
11451 ///
11452 /// \param VD Declaration of an identifier that appears in a type tag.
11453 ///
11454 /// \param MagicValue Type tag magic value.
11455 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11456                      const ValueDecl **VD, uint64_t *MagicValue) {
11457   while(true) {
11458     if (!TypeExpr)
11459       return false;
11460 
11461     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11462 
11463     switch (TypeExpr->getStmtClass()) {
11464     case Stmt::UnaryOperatorClass: {
11465       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11466       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11467         TypeExpr = UO->getSubExpr();
11468         continue;
11469       }
11470       return false;
11471     }
11472 
11473     case Stmt::DeclRefExprClass: {
11474       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11475       *VD = DRE->getDecl();
11476       return true;
11477     }
11478 
11479     case Stmt::IntegerLiteralClass: {
11480       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11481       llvm::APInt MagicValueAPInt = IL->getValue();
11482       if (MagicValueAPInt.getActiveBits() <= 64) {
11483         *MagicValue = MagicValueAPInt.getZExtValue();
11484         return true;
11485       } else
11486         return false;
11487     }
11488 
11489     case Stmt::BinaryConditionalOperatorClass:
11490     case Stmt::ConditionalOperatorClass: {
11491       const AbstractConditionalOperator *ACO =
11492           cast<AbstractConditionalOperator>(TypeExpr);
11493       bool Result;
11494       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11495         if (Result)
11496           TypeExpr = ACO->getTrueExpr();
11497         else
11498           TypeExpr = ACO->getFalseExpr();
11499         continue;
11500       }
11501       return false;
11502     }
11503 
11504     case Stmt::BinaryOperatorClass: {
11505       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11506       if (BO->getOpcode() == BO_Comma) {
11507         TypeExpr = BO->getRHS();
11508         continue;
11509       }
11510       return false;
11511     }
11512 
11513     default:
11514       return false;
11515     }
11516   }
11517 }
11518 
11519 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11520 ///
11521 /// \param TypeExpr Expression that specifies a type tag.
11522 ///
11523 /// \param MagicValues Registered magic values.
11524 ///
11525 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11526 ///        kind.
11527 ///
11528 /// \param TypeInfo Information about the corresponding C type.
11529 ///
11530 /// \returns true if the corresponding C type was found.
11531 bool GetMatchingCType(
11532         const IdentifierInfo *ArgumentKind,
11533         const Expr *TypeExpr, const ASTContext &Ctx,
11534         const llvm::DenseMap<Sema::TypeTagMagicValue,
11535                              Sema::TypeTagData> *MagicValues,
11536         bool &FoundWrongKind,
11537         Sema::TypeTagData &TypeInfo) {
11538   FoundWrongKind = false;
11539 
11540   // Variable declaration that has type_tag_for_datatype attribute.
11541   const ValueDecl *VD = nullptr;
11542 
11543   uint64_t MagicValue;
11544 
11545   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11546     return false;
11547 
11548   if (VD) {
11549     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11550       if (I->getArgumentKind() != ArgumentKind) {
11551         FoundWrongKind = true;
11552         return false;
11553       }
11554       TypeInfo.Type = I->getMatchingCType();
11555       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11556       TypeInfo.MustBeNull = I->getMustBeNull();
11557       return true;
11558     }
11559     return false;
11560   }
11561 
11562   if (!MagicValues)
11563     return false;
11564 
11565   llvm::DenseMap<Sema::TypeTagMagicValue,
11566                  Sema::TypeTagData>::const_iterator I =
11567       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11568   if (I == MagicValues->end())
11569     return false;
11570 
11571   TypeInfo = I->second;
11572   return true;
11573 }
11574 } // end anonymous namespace
11575 
11576 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11577                                       uint64_t MagicValue, QualType Type,
11578                                       bool LayoutCompatible,
11579                                       bool MustBeNull) {
11580   if (!TypeTagForDatatypeMagicValues)
11581     TypeTagForDatatypeMagicValues.reset(
11582         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11583 
11584   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11585   (*TypeTagForDatatypeMagicValues)[Magic] =
11586       TypeTagData(Type, LayoutCompatible, MustBeNull);
11587 }
11588 
11589 namespace {
11590 bool IsSameCharType(QualType T1, QualType T2) {
11591   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11592   if (!BT1)
11593     return false;
11594 
11595   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11596   if (!BT2)
11597     return false;
11598 
11599   BuiltinType::Kind T1Kind = BT1->getKind();
11600   BuiltinType::Kind T2Kind = BT2->getKind();
11601 
11602   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11603          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11604          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11605          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11606 }
11607 } // end anonymous namespace
11608 
11609 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11610                                     const Expr * const *ExprArgs) {
11611   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11612   bool IsPointerAttr = Attr->getIsPointer();
11613 
11614   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11615   bool FoundWrongKind;
11616   TypeTagData TypeInfo;
11617   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11618                         TypeTagForDatatypeMagicValues.get(),
11619                         FoundWrongKind, TypeInfo)) {
11620     if (FoundWrongKind)
11621       Diag(TypeTagExpr->getExprLoc(),
11622            diag::warn_type_tag_for_datatype_wrong_kind)
11623         << TypeTagExpr->getSourceRange();
11624     return;
11625   }
11626 
11627   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11628   if (IsPointerAttr) {
11629     // Skip implicit cast of pointer to `void *' (as a function argument).
11630     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11631       if (ICE->getType()->isVoidPointerType() &&
11632           ICE->getCastKind() == CK_BitCast)
11633         ArgumentExpr = ICE->getSubExpr();
11634   }
11635   QualType ArgumentType = ArgumentExpr->getType();
11636 
11637   // Passing a `void*' pointer shouldn't trigger a warning.
11638   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11639     return;
11640 
11641   if (TypeInfo.MustBeNull) {
11642     // Type tag with matching void type requires a null pointer.
11643     if (!ArgumentExpr->isNullPointerConstant(Context,
11644                                              Expr::NPC_ValueDependentIsNotNull)) {
11645       Diag(ArgumentExpr->getExprLoc(),
11646            diag::warn_type_safety_null_pointer_required)
11647           << ArgumentKind->getName()
11648           << ArgumentExpr->getSourceRange()
11649           << TypeTagExpr->getSourceRange();
11650     }
11651     return;
11652   }
11653 
11654   QualType RequiredType = TypeInfo.Type;
11655   if (IsPointerAttr)
11656     RequiredType = Context.getPointerType(RequiredType);
11657 
11658   bool mismatch = false;
11659   if (!TypeInfo.LayoutCompatible) {
11660     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11661 
11662     // C++11 [basic.fundamental] p1:
11663     // Plain char, signed char, and unsigned char are three distinct types.
11664     //
11665     // But we treat plain `char' as equivalent to `signed char' or `unsigned
11666     // char' depending on the current char signedness mode.
11667     if (mismatch)
11668       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11669                                            RequiredType->getPointeeType())) ||
11670           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11671         mismatch = false;
11672   } else
11673     if (IsPointerAttr)
11674       mismatch = !isLayoutCompatible(Context,
11675                                      ArgumentType->getPointeeType(),
11676                                      RequiredType->getPointeeType());
11677     else
11678       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11679 
11680   if (mismatch)
11681     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11682         << ArgumentType << ArgumentKind
11683         << TypeInfo.LayoutCompatible << RequiredType
11684         << ArgumentExpr->getSourceRange()
11685         << TypeTagExpr->getSourceRange();
11686 }
11687 
11688 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11689                                          CharUnits Alignment) {
11690   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11691 }
11692 
11693 void Sema::DiagnoseMisalignedMembers() {
11694   for (MisalignedMember &m : MisalignedMembers) {
11695     const NamedDecl *ND = m.RD;
11696     if (ND->getName().empty()) {
11697       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11698         ND = TD;
11699     }
11700     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11701         << m.MD << ND << m.E->getSourceRange();
11702   }
11703   MisalignedMembers.clear();
11704 }
11705 
11706 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11707   E = E->IgnoreParens();
11708   if (!T->isPointerType() && !T->isIntegerType())
11709     return;
11710   if (isa<UnaryOperator>(E) &&
11711       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11712     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11713     if (isa<MemberExpr>(Op)) {
11714       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11715                           MisalignedMember(Op));
11716       if (MA != MisalignedMembers.end() &&
11717           (T->isIntegerType() ||
11718            (T->isPointerType() &&
11719             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
11720         MisalignedMembers.erase(MA);
11721     }
11722   }
11723 }
11724 
11725 void Sema::RefersToMemberWithReducedAlignment(
11726     Expr *E,
11727     std::function<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action) {
11728   const auto *ME = dyn_cast<MemberExpr>(E);
11729   if (!ME)
11730     return;
11731 
11732   // For a chain of MemberExpr like "a.b.c.d" this list
11733   // will keep FieldDecl's like [d, c, b].
11734   SmallVector<FieldDecl *, 4> ReverseMemberChain;
11735   const MemberExpr *TopME = nullptr;
11736   bool AnyIsPacked = false;
11737   do {
11738     QualType BaseType = ME->getBase()->getType();
11739     if (ME->isArrow())
11740       BaseType = BaseType->getPointeeType();
11741     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11742 
11743     ValueDecl *MD = ME->getMemberDecl();
11744     auto *FD = dyn_cast<FieldDecl>(MD);
11745     // We do not care about non-data members.
11746     if (!FD || FD->isInvalidDecl())
11747       return;
11748 
11749     AnyIsPacked =
11750         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11751     ReverseMemberChain.push_back(FD);
11752 
11753     TopME = ME;
11754     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11755   } while (ME);
11756   assert(TopME && "We did not compute a topmost MemberExpr!");
11757 
11758   // Not the scope of this diagnostic.
11759   if (!AnyIsPacked)
11760     return;
11761 
11762   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11763   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11764   // TODO: The innermost base of the member expression may be too complicated.
11765   // For now, just disregard these cases. This is left for future
11766   // improvement.
11767   if (!DRE && !isa<CXXThisExpr>(TopBase))
11768       return;
11769 
11770   // Alignment expected by the whole expression.
11771   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11772 
11773   // No need to do anything else with this case.
11774   if (ExpectedAlignment.isOne())
11775     return;
11776 
11777   // Synthesize offset of the whole access.
11778   CharUnits Offset;
11779   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11780        I++) {
11781     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11782   }
11783 
11784   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11785   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11786       ReverseMemberChain.back()->getParent()->getTypeForDecl());
11787 
11788   // The base expression of the innermost MemberExpr may give
11789   // stronger guarantees than the class containing the member.
11790   if (DRE && !TopME->isArrow()) {
11791     const ValueDecl *VD = DRE->getDecl();
11792     if (!VD->getType()->isReferenceType())
11793       CompleteObjectAlignment =
11794           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11795   }
11796 
11797   // Check if the synthesized offset fulfills the alignment.
11798   if (Offset % ExpectedAlignment != 0 ||
11799       // It may fulfill the offset it but the effective alignment may still be
11800       // lower than the expected expression alignment.
11801       CompleteObjectAlignment < ExpectedAlignment) {
11802     // If this happens, we want to determine a sensible culprit of this.
11803     // Intuitively, watching the chain of member expressions from right to
11804     // left, we start with the required alignment (as required by the field
11805     // type) but some packed attribute in that chain has reduced the alignment.
11806     // It may happen that another packed structure increases it again. But if
11807     // we are here such increase has not been enough. So pointing the first
11808     // FieldDecl that either is packed or else its RecordDecl is,
11809     // seems reasonable.
11810     FieldDecl *FD = nullptr;
11811     CharUnits Alignment;
11812     for (FieldDecl *FDI : ReverseMemberChain) {
11813       if (FDI->hasAttr<PackedAttr>() ||
11814           FDI->getParent()->hasAttr<PackedAttr>()) {
11815         FD = FDI;
11816         Alignment = std::min(
11817             Context.getTypeAlignInChars(FD->getType()),
11818             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11819         break;
11820       }
11821     }
11822     assert(FD && "We did not find a packed FieldDecl!");
11823     Action(E, FD->getParent(), FD, Alignment);
11824   }
11825 }
11826 
11827 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11828   using namespace std::placeholders;
11829   RefersToMemberWithReducedAlignment(
11830       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11831                      _2, _3, _4));
11832 }
11833 
11834