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/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.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 "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <limits>
41 using namespace clang;
42 using namespace sema;
43 
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                     unsigned ByteNo) const {
46   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47                                Context.getTargetInfo());
48 }
49 
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking.  Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53   unsigned argCount = call->getNumArgs();
54   if (argCount == desiredArgCount) return false;
55 
56   if (argCount < desiredArgCount)
57     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58         << 0 /*function call*/ << desiredArgCount << argCount
59         << call->getSourceRange();
60 
61   // Highlight all the excess arguments.
62   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                     call->getArg(argCount - 1)->getLocEnd());
64 
65   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66     << 0 /*function call*/ << desiredArgCount << argCount
67     << call->getArg(1)->getSourceRange();
68 }
69 
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73   if (checkArgCount(S, TheCall, 2))
74     return true;
75 
76   // First argument should be an integer.
77   Expr *ValArg = TheCall->getArg(0);
78   QualType Ty = ValArg->getType();
79   if (!Ty->isIntegerType()) {
80     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81       << ValArg->getSourceRange();
82     return true;
83   }
84 
85   // Second argument should be a constant string.
86   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88   if (!Literal || !Literal->isAscii()) {
89     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90       << StrArg->getSourceRange();
91     return true;
92   }
93 
94   TheCall->setType(Ty);
95   return false;
96 }
97 
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101   if (checkArgCount(S, TheCall, 1))
102     return true;
103 
104   ExprResult Arg(TheCall->getArg(0));
105   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106   if (ResultType.isNull())
107     return true;
108 
109   TheCall->setArg(0, Arg.get());
110   TheCall->setType(ResultType);
111   return false;
112 }
113 
114 ExprResult
115 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
116   ExprResult TheCallResult(TheCall);
117 
118   // Find out if any arguments are required to be integer constant expressions.
119   unsigned ICEArguments = 0;
120   ASTContext::GetBuiltinTypeError Error;
121   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122   if (Error != ASTContext::GE_None)
123     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
124 
125   // If any arguments are required to be ICE's, check and diagnose.
126   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127     // Skip arguments not required to be ICE's.
128     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129 
130     llvm::APSInt Result;
131     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132       return true;
133     ICEArguments &= ~(1 << ArgNo);
134   }
135 
136   switch (BuiltinID) {
137   case Builtin::BI__builtin___CFStringMakeConstantString:
138     assert(TheCall->getNumArgs() == 1 &&
139            "Wrong # arguments to builtin CFStringMakeConstantString");
140     if (CheckObjCString(TheCall->getArg(0)))
141       return ExprError();
142     break;
143   case Builtin::BI__builtin_stdarg_start:
144   case Builtin::BI__builtin_va_start:
145   case Builtin::BI__va_start:
146     if (SemaBuiltinVAStart(TheCall))
147       return ExprError();
148     break;
149   case Builtin::BI__builtin_isgreater:
150   case Builtin::BI__builtin_isgreaterequal:
151   case Builtin::BI__builtin_isless:
152   case Builtin::BI__builtin_islessequal:
153   case Builtin::BI__builtin_islessgreater:
154   case Builtin::BI__builtin_isunordered:
155     if (SemaBuiltinUnorderedCompare(TheCall))
156       return ExprError();
157     break;
158   case Builtin::BI__builtin_fpclassify:
159     if (SemaBuiltinFPClassification(TheCall, 6))
160       return ExprError();
161     break;
162   case Builtin::BI__builtin_isfinite:
163   case Builtin::BI__builtin_isinf:
164   case Builtin::BI__builtin_isinf_sign:
165   case Builtin::BI__builtin_isnan:
166   case Builtin::BI__builtin_isnormal:
167     if (SemaBuiltinFPClassification(TheCall, 1))
168       return ExprError();
169     break;
170   case Builtin::BI__builtin_shufflevector:
171     return SemaBuiltinShuffleVector(TheCall);
172     // TheCall will be freed by the smart pointer here, but that's fine, since
173     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
174   case Builtin::BI__builtin_prefetch:
175     if (SemaBuiltinPrefetch(TheCall))
176       return ExprError();
177     break;
178   case Builtin::BI__builtin_object_size:
179     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
180       return ExprError();
181     break;
182   case Builtin::BI__builtin_longjmp:
183     if (SemaBuiltinLongjmp(TheCall))
184       return ExprError();
185     break;
186 
187   case Builtin::BI__builtin_classify_type:
188     if (checkArgCount(*this, TheCall, 1)) return true;
189     TheCall->setType(Context.IntTy);
190     break;
191   case Builtin::BI__builtin_constant_p:
192     if (checkArgCount(*this, TheCall, 1)) return true;
193     TheCall->setType(Context.IntTy);
194     break;
195   case Builtin::BI__sync_fetch_and_add:
196   case Builtin::BI__sync_fetch_and_add_1:
197   case Builtin::BI__sync_fetch_and_add_2:
198   case Builtin::BI__sync_fetch_and_add_4:
199   case Builtin::BI__sync_fetch_and_add_8:
200   case Builtin::BI__sync_fetch_and_add_16:
201   case Builtin::BI__sync_fetch_and_sub:
202   case Builtin::BI__sync_fetch_and_sub_1:
203   case Builtin::BI__sync_fetch_and_sub_2:
204   case Builtin::BI__sync_fetch_and_sub_4:
205   case Builtin::BI__sync_fetch_and_sub_8:
206   case Builtin::BI__sync_fetch_and_sub_16:
207   case Builtin::BI__sync_fetch_and_or:
208   case Builtin::BI__sync_fetch_and_or_1:
209   case Builtin::BI__sync_fetch_and_or_2:
210   case Builtin::BI__sync_fetch_and_or_4:
211   case Builtin::BI__sync_fetch_and_or_8:
212   case Builtin::BI__sync_fetch_and_or_16:
213   case Builtin::BI__sync_fetch_and_and:
214   case Builtin::BI__sync_fetch_and_and_1:
215   case Builtin::BI__sync_fetch_and_and_2:
216   case Builtin::BI__sync_fetch_and_and_4:
217   case Builtin::BI__sync_fetch_and_and_8:
218   case Builtin::BI__sync_fetch_and_and_16:
219   case Builtin::BI__sync_fetch_and_xor:
220   case Builtin::BI__sync_fetch_and_xor_1:
221   case Builtin::BI__sync_fetch_and_xor_2:
222   case Builtin::BI__sync_fetch_and_xor_4:
223   case Builtin::BI__sync_fetch_and_xor_8:
224   case Builtin::BI__sync_fetch_and_xor_16:
225   case Builtin::BI__sync_add_and_fetch:
226   case Builtin::BI__sync_add_and_fetch_1:
227   case Builtin::BI__sync_add_and_fetch_2:
228   case Builtin::BI__sync_add_and_fetch_4:
229   case Builtin::BI__sync_add_and_fetch_8:
230   case Builtin::BI__sync_add_and_fetch_16:
231   case Builtin::BI__sync_sub_and_fetch:
232   case Builtin::BI__sync_sub_and_fetch_1:
233   case Builtin::BI__sync_sub_and_fetch_2:
234   case Builtin::BI__sync_sub_and_fetch_4:
235   case Builtin::BI__sync_sub_and_fetch_8:
236   case Builtin::BI__sync_sub_and_fetch_16:
237   case Builtin::BI__sync_and_and_fetch:
238   case Builtin::BI__sync_and_and_fetch_1:
239   case Builtin::BI__sync_and_and_fetch_2:
240   case Builtin::BI__sync_and_and_fetch_4:
241   case Builtin::BI__sync_and_and_fetch_8:
242   case Builtin::BI__sync_and_and_fetch_16:
243   case Builtin::BI__sync_or_and_fetch:
244   case Builtin::BI__sync_or_and_fetch_1:
245   case Builtin::BI__sync_or_and_fetch_2:
246   case Builtin::BI__sync_or_and_fetch_4:
247   case Builtin::BI__sync_or_and_fetch_8:
248   case Builtin::BI__sync_or_and_fetch_16:
249   case Builtin::BI__sync_xor_and_fetch:
250   case Builtin::BI__sync_xor_and_fetch_1:
251   case Builtin::BI__sync_xor_and_fetch_2:
252   case Builtin::BI__sync_xor_and_fetch_4:
253   case Builtin::BI__sync_xor_and_fetch_8:
254   case Builtin::BI__sync_xor_and_fetch_16:
255   case Builtin::BI__sync_val_compare_and_swap:
256   case Builtin::BI__sync_val_compare_and_swap_1:
257   case Builtin::BI__sync_val_compare_and_swap_2:
258   case Builtin::BI__sync_val_compare_and_swap_4:
259   case Builtin::BI__sync_val_compare_and_swap_8:
260   case Builtin::BI__sync_val_compare_and_swap_16:
261   case Builtin::BI__sync_bool_compare_and_swap:
262   case Builtin::BI__sync_bool_compare_and_swap_1:
263   case Builtin::BI__sync_bool_compare_and_swap_2:
264   case Builtin::BI__sync_bool_compare_and_swap_4:
265   case Builtin::BI__sync_bool_compare_and_swap_8:
266   case Builtin::BI__sync_bool_compare_and_swap_16:
267   case Builtin::BI__sync_lock_test_and_set:
268   case Builtin::BI__sync_lock_test_and_set_1:
269   case Builtin::BI__sync_lock_test_and_set_2:
270   case Builtin::BI__sync_lock_test_and_set_4:
271   case Builtin::BI__sync_lock_test_and_set_8:
272   case Builtin::BI__sync_lock_test_and_set_16:
273   case Builtin::BI__sync_lock_release:
274   case Builtin::BI__sync_lock_release_1:
275   case Builtin::BI__sync_lock_release_2:
276   case Builtin::BI__sync_lock_release_4:
277   case Builtin::BI__sync_lock_release_8:
278   case Builtin::BI__sync_lock_release_16:
279   case Builtin::BI__sync_swap:
280   case Builtin::BI__sync_swap_1:
281   case Builtin::BI__sync_swap_2:
282   case Builtin::BI__sync_swap_4:
283   case Builtin::BI__sync_swap_8:
284   case Builtin::BI__sync_swap_16:
285     return SemaBuiltinAtomicOverloaded(TheCallResult);
286 #define BUILTIN(ID, TYPE, ATTRS)
287 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
288   case Builtin::BI##ID: \
289     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
290 #include "clang/Basic/Builtins.def"
291   case Builtin::BI__builtin_annotation:
292     if (SemaBuiltinAnnotation(*this, TheCall))
293       return ExprError();
294     break;
295   case Builtin::BI__builtin_addressof:
296     if (SemaBuiltinAddressof(*this, TheCall))
297       return ExprError();
298     break;
299   case Builtin::BI__builtin_operator_new:
300   case Builtin::BI__builtin_operator_delete:
301     if (!getLangOpts().CPlusPlus) {
302       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
303         << (BuiltinID == Builtin::BI__builtin_operator_new
304                 ? "__builtin_operator_new"
305                 : "__builtin_operator_delete")
306         << "C++";
307       return ExprError();
308     }
309     // CodeGen assumes it can find the global new and delete to call,
310     // so ensure that they are declared.
311     DeclareGlobalNewDelete();
312     break;
313   }
314 
315   // Since the target specific builtins for each arch overlap, only check those
316   // of the arch we are compiling for.
317   if (BuiltinID >= Builtin::FirstTSBuiltin) {
318     switch (Context.getTargetInfo().getTriple().getArch()) {
319       case llvm::Triple::arm:
320       case llvm::Triple::armeb:
321       case llvm::Triple::thumb:
322       case llvm::Triple::thumbeb:
323         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
324           return ExprError();
325         break;
326       case llvm::Triple::aarch64:
327       case llvm::Triple::aarch64_be:
328       case llvm::Triple::arm64:
329       case llvm::Triple::arm64_be:
330         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
331           return ExprError();
332         break;
333       case llvm::Triple::mips:
334       case llvm::Triple::mipsel:
335       case llvm::Triple::mips64:
336       case llvm::Triple::mips64el:
337         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
338           return ExprError();
339         break;
340       case llvm::Triple::x86:
341       case llvm::Triple::x86_64:
342         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
343           return ExprError();
344         break;
345       default:
346         break;
347     }
348   }
349 
350   return TheCallResult;
351 }
352 
353 // Get the valid immediate range for the specified NEON type code.
354 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
355   NeonTypeFlags Type(t);
356   int IsQuad = ForceQuad ? true : Type.isQuad();
357   switch (Type.getEltType()) {
358   case NeonTypeFlags::Int8:
359   case NeonTypeFlags::Poly8:
360     return shift ? 7 : (8 << IsQuad) - 1;
361   case NeonTypeFlags::Int16:
362   case NeonTypeFlags::Poly16:
363     return shift ? 15 : (4 << IsQuad) - 1;
364   case NeonTypeFlags::Int32:
365     return shift ? 31 : (2 << IsQuad) - 1;
366   case NeonTypeFlags::Int64:
367   case NeonTypeFlags::Poly64:
368     return shift ? 63 : (1 << IsQuad) - 1;
369   case NeonTypeFlags::Poly128:
370     return shift ? 127 : (1 << IsQuad) - 1;
371   case NeonTypeFlags::Float16:
372     assert(!shift && "cannot shift float types!");
373     return (4 << IsQuad) - 1;
374   case NeonTypeFlags::Float32:
375     assert(!shift && "cannot shift float types!");
376     return (2 << IsQuad) - 1;
377   case NeonTypeFlags::Float64:
378     assert(!shift && "cannot shift float types!");
379     return (1 << IsQuad) - 1;
380   }
381   llvm_unreachable("Invalid NeonTypeFlag!");
382 }
383 
384 /// getNeonEltType - Return the QualType corresponding to the elements of
385 /// the vector type specified by the NeonTypeFlags.  This is used to check
386 /// the pointer arguments for Neon load/store intrinsics.
387 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
388                                bool IsPolyUnsigned, bool IsInt64Long) {
389   switch (Flags.getEltType()) {
390   case NeonTypeFlags::Int8:
391     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
392   case NeonTypeFlags::Int16:
393     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
394   case NeonTypeFlags::Int32:
395     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
396   case NeonTypeFlags::Int64:
397     if (IsInt64Long)
398       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
399     else
400       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
401                                 : Context.LongLongTy;
402   case NeonTypeFlags::Poly8:
403     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
404   case NeonTypeFlags::Poly16:
405     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
406   case NeonTypeFlags::Poly64:
407     return Context.UnsignedLongTy;
408   case NeonTypeFlags::Poly128:
409     break;
410   case NeonTypeFlags::Float16:
411     return Context.HalfTy;
412   case NeonTypeFlags::Float32:
413     return Context.FloatTy;
414   case NeonTypeFlags::Float64:
415     return Context.DoubleTy;
416   }
417   llvm_unreachable("Invalid NeonTypeFlag!");
418 }
419 
420 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
421   llvm::APSInt Result;
422   uint64_t mask = 0;
423   unsigned TV = 0;
424   int PtrArgNum = -1;
425   bool HasConstPtr = false;
426   switch (BuiltinID) {
427 #define GET_NEON_OVERLOAD_CHECK
428 #include "clang/Basic/arm_neon.inc"
429 #undef GET_NEON_OVERLOAD_CHECK
430   }
431 
432   // For NEON intrinsics which are overloaded on vector element type, validate
433   // the immediate which specifies which variant to emit.
434   unsigned ImmArg = TheCall->getNumArgs()-1;
435   if (mask) {
436     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
437       return true;
438 
439     TV = Result.getLimitedValue(64);
440     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
441       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
442         << TheCall->getArg(ImmArg)->getSourceRange();
443   }
444 
445   if (PtrArgNum >= 0) {
446     // Check that pointer arguments have the specified type.
447     Expr *Arg = TheCall->getArg(PtrArgNum);
448     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
449       Arg = ICE->getSubExpr();
450     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
451     QualType RHSTy = RHS.get()->getType();
452 
453     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
454     bool IsPolyUnsigned =
455         Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
456     bool IsInt64Long =
457         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
458     QualType EltTy =
459         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
460     if (HasConstPtr)
461       EltTy = EltTy.withConst();
462     QualType LHSTy = Context.getPointerType(EltTy);
463     AssignConvertType ConvTy;
464     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
465     if (RHS.isInvalid())
466       return true;
467     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
468                                  RHS.get(), AA_Assigning))
469       return true;
470   }
471 
472   // For NEON intrinsics which take an immediate value as part of the
473   // instruction, range check them here.
474   unsigned i = 0, l = 0, u = 0;
475   switch (BuiltinID) {
476   default:
477     return false;
478 #define GET_NEON_IMMEDIATE_CHECK
479 #include "clang/Basic/arm_neon.inc"
480 #undef GET_NEON_IMMEDIATE_CHECK
481   }
482 
483   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
484 }
485 
486 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
487                                         unsigned MaxWidth) {
488   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
489           BuiltinID == ARM::BI__builtin_arm_strex ||
490           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
491           BuiltinID == AArch64::BI__builtin_arm_strex) &&
492          "unexpected ARM builtin");
493   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
494                  BuiltinID == AArch64::BI__builtin_arm_ldrex;
495 
496   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
497 
498   // Ensure that we have the proper number of arguments.
499   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
500     return true;
501 
502   // Inspect the pointer argument of the atomic builtin.  This should always be
503   // a pointer type, whose element is an integral scalar or pointer type.
504   // Because it is a pointer type, we don't have to worry about any implicit
505   // casts here.
506   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
507   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
508   if (PointerArgRes.isInvalid())
509     return true;
510   PointerArg = PointerArgRes.get();
511 
512   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
513   if (!pointerType) {
514     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
515       << PointerArg->getType() << PointerArg->getSourceRange();
516     return true;
517   }
518 
519   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
520   // task is to insert the appropriate casts into the AST. First work out just
521   // what the appropriate type is.
522   QualType ValType = pointerType->getPointeeType();
523   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
524   if (IsLdrex)
525     AddrType.addConst();
526 
527   // Issue a warning if the cast is dodgy.
528   CastKind CastNeeded = CK_NoOp;
529   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
530     CastNeeded = CK_BitCast;
531     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
532       << PointerArg->getType()
533       << Context.getPointerType(AddrType)
534       << AA_Passing << PointerArg->getSourceRange();
535   }
536 
537   // Finally, do the cast and replace the argument with the corrected version.
538   AddrType = Context.getPointerType(AddrType);
539   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
540   if (PointerArgRes.isInvalid())
541     return true;
542   PointerArg = PointerArgRes.get();
543 
544   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
545 
546   // In general, we allow ints, floats and pointers to be loaded and stored.
547   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
548       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
549     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
550       << PointerArg->getType() << PointerArg->getSourceRange();
551     return true;
552   }
553 
554   // But ARM doesn't have instructions to deal with 128-bit versions.
555   if (Context.getTypeSize(ValType) > MaxWidth) {
556     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
557     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
558       << PointerArg->getType() << PointerArg->getSourceRange();
559     return true;
560   }
561 
562   switch (ValType.getObjCLifetime()) {
563   case Qualifiers::OCL_None:
564   case Qualifiers::OCL_ExplicitNone:
565     // okay
566     break;
567 
568   case Qualifiers::OCL_Weak:
569   case Qualifiers::OCL_Strong:
570   case Qualifiers::OCL_Autoreleasing:
571     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
572       << ValType << PointerArg->getSourceRange();
573     return true;
574   }
575 
576 
577   if (IsLdrex) {
578     TheCall->setType(ValType);
579     return false;
580   }
581 
582   // Initialize the argument to be stored.
583   ExprResult ValArg = TheCall->getArg(0);
584   InitializedEntity Entity = InitializedEntity::InitializeParameter(
585       Context, ValType, /*consume*/ false);
586   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
587   if (ValArg.isInvalid())
588     return true;
589   TheCall->setArg(0, ValArg.get());
590 
591   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
592   // but the custom checker bypasses all default analysis.
593   TheCall->setType(Context.IntTy);
594   return false;
595 }
596 
597 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
598   llvm::APSInt Result;
599 
600   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
601       BuiltinID == ARM::BI__builtin_arm_strex) {
602     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
603   }
604 
605   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
606     return true;
607 
608   // For NEON intrinsics which take an immediate value as part of the
609   // instruction, range check them here.
610   unsigned i = 0, l = 0, u = 0;
611   switch (BuiltinID) {
612   default: return false;
613   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
614   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
615   case ARM::BI__builtin_arm_vcvtr_f:
616   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
617   case ARM::BI__builtin_arm_dmb:
618   case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
619   }
620 
621   // FIXME: VFP Intrinsics should error if VFP not present.
622   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
623 }
624 
625 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
626                                          CallExpr *TheCall) {
627   llvm::APSInt Result;
628 
629   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
630       BuiltinID == AArch64::BI__builtin_arm_strex) {
631     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
632   }
633 
634   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
635     return true;
636 
637   return false;
638 }
639 
640 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
641   unsigned i = 0, l = 0, u = 0;
642   switch (BuiltinID) {
643   default: return false;
644   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
645   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
646   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
647   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
648   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
649   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
650   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
651   }
652 
653   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
654 }
655 
656 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
657   switch (BuiltinID) {
658   case X86::BI_mm_prefetch:
659     // This is declared to take (const char*, int)
660     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
661   }
662   return false;
663 }
664 
665 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
666 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
667 /// Returns true when the format fits the function and the FormatStringInfo has
668 /// been populated.
669 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
670                                FormatStringInfo *FSI) {
671   FSI->HasVAListArg = Format->getFirstArg() == 0;
672   FSI->FormatIdx = Format->getFormatIdx() - 1;
673   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
674 
675   // The way the format attribute works in GCC, the implicit this argument
676   // of member functions is counted. However, it doesn't appear in our own
677   // lists, so decrement format_idx in that case.
678   if (IsCXXMember) {
679     if(FSI->FormatIdx == 0)
680       return false;
681     --FSI->FormatIdx;
682     if (FSI->FirstDataArg != 0)
683       --FSI->FirstDataArg;
684   }
685   return true;
686 }
687 
688 /// Checks if a the given expression evaluates to null.
689 ///
690 /// \brief Returns true if the value evaluates to null.
691 static bool CheckNonNullExpr(Sema &S,
692                              const Expr *Expr) {
693   // As a special case, transparent unions initialized with zero are
694   // considered null for the purposes of the nonnull attribute.
695   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
696     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
697       if (const CompoundLiteralExpr *CLE =
698           dyn_cast<CompoundLiteralExpr>(Expr))
699         if (const InitListExpr *ILE =
700             dyn_cast<InitListExpr>(CLE->getInitializer()))
701           Expr = ILE->getInit(0);
702   }
703 
704   bool Result;
705   return (!Expr->isValueDependent() &&
706           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
707           !Result);
708 }
709 
710 static void CheckNonNullArgument(Sema &S,
711                                  const Expr *ArgExpr,
712                                  SourceLocation CallSiteLoc) {
713   if (CheckNonNullExpr(S, ArgExpr))
714     S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
715 }
716 
717 static void CheckNonNullArguments(Sema &S,
718                                   const NamedDecl *FDecl,
719                                   const Expr * const *ExprArgs,
720                                   SourceLocation CallSiteLoc) {
721   // Check the attributes attached to the method/function itself.
722   for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
723     for (const auto &Val : NonNull->args())
724       CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
725   }
726 
727   // Check the attributes on the parameters.
728   ArrayRef<ParmVarDecl*> parms;
729   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
730     parms = FD->parameters();
731   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
732     parms = MD->parameters();
733 
734   unsigned argIndex = 0;
735   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
736        I != E; ++I, ++argIndex) {
737     const ParmVarDecl *PVD = *I;
738     if (PVD->hasAttr<NonNullAttr>())
739       CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
740   }
741 }
742 
743 /// Handles the checks for format strings, non-POD arguments to vararg
744 /// functions, and NULL arguments passed to non-NULL parameters.
745 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
746                      unsigned NumParams, bool IsMemberFunction,
747                      SourceLocation Loc, SourceRange Range,
748                      VariadicCallType CallType) {
749   // FIXME: We should check as much as we can in the template definition.
750   if (CurContext->isDependentContext())
751     return;
752 
753   // Printf and scanf checking.
754   llvm::SmallBitVector CheckedVarArgs;
755   if (FDecl) {
756     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
757       // Only create vector if there are format attributes.
758       CheckedVarArgs.resize(Args.size());
759 
760       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
761                            CheckedVarArgs);
762     }
763   }
764 
765   // Refuse POD arguments that weren't caught by the format string
766   // checks above.
767   if (CallType != VariadicDoesNotApply) {
768     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
769       // Args[ArgIdx] can be null in malformed code.
770       if (const Expr *Arg = Args[ArgIdx]) {
771         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
772           checkVariadicArgument(Arg, CallType);
773       }
774     }
775   }
776 
777   if (FDecl) {
778     CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
779 
780     // Type safety checking.
781     for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
782       CheckArgumentWithTypeTag(I, Args.data());
783   }
784 }
785 
786 /// CheckConstructorCall - Check a constructor call for correctness and safety
787 /// properties not enforced by the C type system.
788 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
789                                 ArrayRef<const Expr *> Args,
790                                 const FunctionProtoType *Proto,
791                                 SourceLocation Loc) {
792   VariadicCallType CallType =
793     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
794   checkCall(FDecl, Args, Proto->getNumParams(),
795             /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
796 }
797 
798 /// CheckFunctionCall - Check a direct function call for various correctness
799 /// and safety properties not strictly enforced by the C type system.
800 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
801                              const FunctionProtoType *Proto) {
802   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
803                               isa<CXXMethodDecl>(FDecl);
804   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
805                           IsMemberOperatorCall;
806   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
807                                                   TheCall->getCallee());
808   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
809   Expr** Args = TheCall->getArgs();
810   unsigned NumArgs = TheCall->getNumArgs();
811   if (IsMemberOperatorCall) {
812     // If this is a call to a member operator, hide the first argument
813     // from checkCall.
814     // FIXME: Our choice of AST representation here is less than ideal.
815     ++Args;
816     --NumArgs;
817   }
818   checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
819             IsMemberFunction, TheCall->getRParenLoc(),
820             TheCall->getCallee()->getSourceRange(), CallType);
821 
822   IdentifierInfo *FnInfo = FDecl->getIdentifier();
823   // None of the checks below are needed for functions that don't have
824   // simple names (e.g., C++ conversion functions).
825   if (!FnInfo)
826     return false;
827 
828   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
829 
830   unsigned CMId = FDecl->getMemoryFunctionKind();
831   if (CMId == 0)
832     return false;
833 
834   // Handle memory setting and copying functions.
835   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
836     CheckStrlcpycatArguments(TheCall, FnInfo);
837   else if (CMId == Builtin::BIstrncat)
838     CheckStrncatArguments(TheCall, FnInfo);
839   else
840     CheckMemaccessArguments(TheCall, CMId, FnInfo);
841 
842   return false;
843 }
844 
845 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
846                                ArrayRef<const Expr *> Args) {
847   VariadicCallType CallType =
848       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
849 
850   checkCall(Method, Args, Method->param_size(),
851             /*IsMemberFunction=*/false,
852             lbrac, Method->getSourceRange(), CallType);
853 
854   return false;
855 }
856 
857 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
858                             const FunctionProtoType *Proto) {
859   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
860   if (!V)
861     return false;
862 
863   QualType Ty = V->getType();
864   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
865     return false;
866 
867   VariadicCallType CallType;
868   if (!Proto || !Proto->isVariadic()) {
869     CallType = VariadicDoesNotApply;
870   } else if (Ty->isBlockPointerType()) {
871     CallType = VariadicBlock;
872   } else { // Ty->isFunctionPointerType()
873     CallType = VariadicFunction;
874   }
875   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
876 
877   checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
878                                                     TheCall->getNumArgs()),
879             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
880             TheCall->getCallee()->getSourceRange(), CallType);
881 
882   return false;
883 }
884 
885 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
886 /// such as function pointers returned from functions.
887 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
888   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
889                                                   TheCall->getCallee());
890   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
891 
892   checkCall(/*FDecl=*/nullptr,
893             llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
894                                              TheCall->getNumArgs()),
895             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
896             TheCall->getCallee()->getSourceRange(), CallType);
897 
898   return false;
899 }
900 
901 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
902   if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
903       Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
904     return false;
905 
906   switch (Op) {
907   case AtomicExpr::AO__c11_atomic_init:
908     llvm_unreachable("There is no ordering argument for an init");
909 
910   case AtomicExpr::AO__c11_atomic_load:
911   case AtomicExpr::AO__atomic_load_n:
912   case AtomicExpr::AO__atomic_load:
913     return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
914            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
915 
916   case AtomicExpr::AO__c11_atomic_store:
917   case AtomicExpr::AO__atomic_store:
918   case AtomicExpr::AO__atomic_store_n:
919     return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
920            Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
921            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
922 
923   default:
924     return true;
925   }
926 }
927 
928 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
929                                          AtomicExpr::AtomicOp Op) {
930   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
931   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
932 
933   // All these operations take one of the following forms:
934   enum {
935     // C    __c11_atomic_init(A *, C)
936     Init,
937     // C    __c11_atomic_load(A *, int)
938     Load,
939     // void __atomic_load(A *, CP, int)
940     Copy,
941     // C    __c11_atomic_add(A *, M, int)
942     Arithmetic,
943     // C    __atomic_exchange_n(A *, CP, int)
944     Xchg,
945     // void __atomic_exchange(A *, C *, CP, int)
946     GNUXchg,
947     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
948     C11CmpXchg,
949     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
950     GNUCmpXchg
951   } Form = Init;
952   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
953   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
954   // where:
955   //   C is an appropriate type,
956   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
957   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
958   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
959   //   the int parameters are for orderings.
960 
961   assert(AtomicExpr::AO__c11_atomic_init == 0 &&
962          AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
963          && "need to update code for modified C11 atomics");
964   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
965                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
966   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
967              Op == AtomicExpr::AO__atomic_store_n ||
968              Op == AtomicExpr::AO__atomic_exchange_n ||
969              Op == AtomicExpr::AO__atomic_compare_exchange_n;
970   bool IsAddSub = false;
971 
972   switch (Op) {
973   case AtomicExpr::AO__c11_atomic_init:
974     Form = Init;
975     break;
976 
977   case AtomicExpr::AO__c11_atomic_load:
978   case AtomicExpr::AO__atomic_load_n:
979     Form = Load;
980     break;
981 
982   case AtomicExpr::AO__c11_atomic_store:
983   case AtomicExpr::AO__atomic_load:
984   case AtomicExpr::AO__atomic_store:
985   case AtomicExpr::AO__atomic_store_n:
986     Form = Copy;
987     break;
988 
989   case AtomicExpr::AO__c11_atomic_fetch_add:
990   case AtomicExpr::AO__c11_atomic_fetch_sub:
991   case AtomicExpr::AO__atomic_fetch_add:
992   case AtomicExpr::AO__atomic_fetch_sub:
993   case AtomicExpr::AO__atomic_add_fetch:
994   case AtomicExpr::AO__atomic_sub_fetch:
995     IsAddSub = true;
996     // Fall through.
997   case AtomicExpr::AO__c11_atomic_fetch_and:
998   case AtomicExpr::AO__c11_atomic_fetch_or:
999   case AtomicExpr::AO__c11_atomic_fetch_xor:
1000   case AtomicExpr::AO__atomic_fetch_and:
1001   case AtomicExpr::AO__atomic_fetch_or:
1002   case AtomicExpr::AO__atomic_fetch_xor:
1003   case AtomicExpr::AO__atomic_fetch_nand:
1004   case AtomicExpr::AO__atomic_and_fetch:
1005   case AtomicExpr::AO__atomic_or_fetch:
1006   case AtomicExpr::AO__atomic_xor_fetch:
1007   case AtomicExpr::AO__atomic_nand_fetch:
1008     Form = Arithmetic;
1009     break;
1010 
1011   case AtomicExpr::AO__c11_atomic_exchange:
1012   case AtomicExpr::AO__atomic_exchange_n:
1013     Form = Xchg;
1014     break;
1015 
1016   case AtomicExpr::AO__atomic_exchange:
1017     Form = GNUXchg;
1018     break;
1019 
1020   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1021   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1022     Form = C11CmpXchg;
1023     break;
1024 
1025   case AtomicExpr::AO__atomic_compare_exchange:
1026   case AtomicExpr::AO__atomic_compare_exchange_n:
1027     Form = GNUCmpXchg;
1028     break;
1029   }
1030 
1031   // Check we have the right number of arguments.
1032   if (TheCall->getNumArgs() < NumArgs[Form]) {
1033     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1034       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1035       << TheCall->getCallee()->getSourceRange();
1036     return ExprError();
1037   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1038     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1039          diag::err_typecheck_call_too_many_args)
1040       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1041       << TheCall->getCallee()->getSourceRange();
1042     return ExprError();
1043   }
1044 
1045   // Inspect the first argument of the atomic operation.
1046   Expr *Ptr = TheCall->getArg(0);
1047   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1048   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1049   if (!pointerType) {
1050     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1051       << Ptr->getType() << Ptr->getSourceRange();
1052     return ExprError();
1053   }
1054 
1055   // For a __c11 builtin, this should be a pointer to an _Atomic type.
1056   QualType AtomTy = pointerType->getPointeeType(); // 'A'
1057   QualType ValType = AtomTy; // 'C'
1058   if (IsC11) {
1059     if (!AtomTy->isAtomicType()) {
1060       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1061         << Ptr->getType() << Ptr->getSourceRange();
1062       return ExprError();
1063     }
1064     if (AtomTy.isConstQualified()) {
1065       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1066         << Ptr->getType() << Ptr->getSourceRange();
1067       return ExprError();
1068     }
1069     ValType = AtomTy->getAs<AtomicType>()->getValueType();
1070   }
1071 
1072   // For an arithmetic operation, the implied arithmetic must be well-formed.
1073   if (Form == Arithmetic) {
1074     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1075     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1076       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1077         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1078       return ExprError();
1079     }
1080     if (!IsAddSub && !ValType->isIntegerType()) {
1081       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1082         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1083       return ExprError();
1084     }
1085   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1086     // For __atomic_*_n operations, the value type must be a scalar integral or
1087     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1088     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1089       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1090     return ExprError();
1091   }
1092 
1093   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1094       !AtomTy->isScalarType()) {
1095     // For GNU atomics, require a trivially-copyable type. This is not part of
1096     // the GNU atomics specification, but we enforce it for sanity.
1097     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1098       << Ptr->getType() << Ptr->getSourceRange();
1099     return ExprError();
1100   }
1101 
1102   // FIXME: For any builtin other than a load, the ValType must not be
1103   // const-qualified.
1104 
1105   switch (ValType.getObjCLifetime()) {
1106   case Qualifiers::OCL_None:
1107   case Qualifiers::OCL_ExplicitNone:
1108     // okay
1109     break;
1110 
1111   case Qualifiers::OCL_Weak:
1112   case Qualifiers::OCL_Strong:
1113   case Qualifiers::OCL_Autoreleasing:
1114     // FIXME: Can this happen? By this point, ValType should be known
1115     // to be trivially copyable.
1116     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1117       << ValType << Ptr->getSourceRange();
1118     return ExprError();
1119   }
1120 
1121   QualType ResultType = ValType;
1122   if (Form == Copy || Form == GNUXchg || Form == Init)
1123     ResultType = Context.VoidTy;
1124   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1125     ResultType = Context.BoolTy;
1126 
1127   // The type of a parameter passed 'by value'. In the GNU atomics, such
1128   // arguments are actually passed as pointers.
1129   QualType ByValType = ValType; // 'CP'
1130   if (!IsC11 && !IsN)
1131     ByValType = Ptr->getType();
1132 
1133   // The first argument --- the pointer --- has a fixed type; we
1134   // deduce the types of the rest of the arguments accordingly.  Walk
1135   // the remaining arguments, converting them to the deduced value type.
1136   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1137     QualType Ty;
1138     if (i < NumVals[Form] + 1) {
1139       switch (i) {
1140       case 1:
1141         // The second argument is the non-atomic operand. For arithmetic, this
1142         // is always passed by value, and for a compare_exchange it is always
1143         // passed by address. For the rest, GNU uses by-address and C11 uses
1144         // by-value.
1145         assert(Form != Load);
1146         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1147           Ty = ValType;
1148         else if (Form == Copy || Form == Xchg)
1149           Ty = ByValType;
1150         else if (Form == Arithmetic)
1151           Ty = Context.getPointerDiffType();
1152         else
1153           Ty = Context.getPointerType(ValType.getUnqualifiedType());
1154         break;
1155       case 2:
1156         // The third argument to compare_exchange / GNU exchange is a
1157         // (pointer to a) desired value.
1158         Ty = ByValType;
1159         break;
1160       case 3:
1161         // The fourth argument to GNU compare_exchange is a 'weak' flag.
1162         Ty = Context.BoolTy;
1163         break;
1164       }
1165     } else {
1166       // The order(s) are always converted to int.
1167       Ty = Context.IntTy;
1168     }
1169 
1170     InitializedEntity Entity =
1171         InitializedEntity::InitializeParameter(Context, Ty, false);
1172     ExprResult Arg = TheCall->getArg(i);
1173     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1174     if (Arg.isInvalid())
1175       return true;
1176     TheCall->setArg(i, Arg.get());
1177   }
1178 
1179   // Permute the arguments into a 'consistent' order.
1180   SmallVector<Expr*, 5> SubExprs;
1181   SubExprs.push_back(Ptr);
1182   switch (Form) {
1183   case Init:
1184     // Note, AtomicExpr::getVal1() has a special case for this atomic.
1185     SubExprs.push_back(TheCall->getArg(1)); // Val1
1186     break;
1187   case Load:
1188     SubExprs.push_back(TheCall->getArg(1)); // Order
1189     break;
1190   case Copy:
1191   case Arithmetic:
1192   case Xchg:
1193     SubExprs.push_back(TheCall->getArg(2)); // Order
1194     SubExprs.push_back(TheCall->getArg(1)); // Val1
1195     break;
1196   case GNUXchg:
1197     // Note, AtomicExpr::getVal2() has a special case for this atomic.
1198     SubExprs.push_back(TheCall->getArg(3)); // Order
1199     SubExprs.push_back(TheCall->getArg(1)); // Val1
1200     SubExprs.push_back(TheCall->getArg(2)); // Val2
1201     break;
1202   case C11CmpXchg:
1203     SubExprs.push_back(TheCall->getArg(3)); // Order
1204     SubExprs.push_back(TheCall->getArg(1)); // Val1
1205     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1206     SubExprs.push_back(TheCall->getArg(2)); // Val2
1207     break;
1208   case GNUCmpXchg:
1209     SubExprs.push_back(TheCall->getArg(4)); // Order
1210     SubExprs.push_back(TheCall->getArg(1)); // Val1
1211     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1212     SubExprs.push_back(TheCall->getArg(2)); // Val2
1213     SubExprs.push_back(TheCall->getArg(3)); // Weak
1214     break;
1215   }
1216 
1217   if (SubExprs.size() >= 2 && Form != Init) {
1218     llvm::APSInt Result(32);
1219     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1220         !isValidOrderingForOp(Result.getSExtValue(), Op))
1221       Diag(SubExprs[1]->getLocStart(),
1222            diag::warn_atomic_op_has_invalid_memory_order)
1223           << SubExprs[1]->getSourceRange();
1224   }
1225 
1226   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1227                                             SubExprs, ResultType, Op,
1228                                             TheCall->getRParenLoc());
1229 
1230   if ((Op == AtomicExpr::AO__c11_atomic_load ||
1231        (Op == AtomicExpr::AO__c11_atomic_store)) &&
1232       Context.AtomicUsesUnsupportedLibcall(AE))
1233     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1234     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1235 
1236   return AE;
1237 }
1238 
1239 
1240 /// checkBuiltinArgument - Given a call to a builtin function, perform
1241 /// normal type-checking on the given argument, updating the call in
1242 /// place.  This is useful when a builtin function requires custom
1243 /// type-checking for some of its arguments but not necessarily all of
1244 /// them.
1245 ///
1246 /// Returns true on error.
1247 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1248   FunctionDecl *Fn = E->getDirectCallee();
1249   assert(Fn && "builtin call without direct callee!");
1250 
1251   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1252   InitializedEntity Entity =
1253     InitializedEntity::InitializeParameter(S.Context, Param);
1254 
1255   ExprResult Arg = E->getArg(0);
1256   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1257   if (Arg.isInvalid())
1258     return true;
1259 
1260   E->setArg(ArgIndex, Arg.get());
1261   return false;
1262 }
1263 
1264 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1265 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1266 /// type of its first argument.  The main ActOnCallExpr routines have already
1267 /// promoted the types of arguments because all of these calls are prototyped as
1268 /// void(...).
1269 ///
1270 /// This function goes through and does final semantic checking for these
1271 /// builtins,
1272 ExprResult
1273 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1274   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1275   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1276   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1277 
1278   // Ensure that we have at least one argument to do type inference from.
1279   if (TheCall->getNumArgs() < 1) {
1280     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1281       << 0 << 1 << TheCall->getNumArgs()
1282       << TheCall->getCallee()->getSourceRange();
1283     return ExprError();
1284   }
1285 
1286   // Inspect the first argument of the atomic builtin.  This should always be
1287   // a pointer type, whose element is an integral scalar or pointer type.
1288   // Because it is a pointer type, we don't have to worry about any implicit
1289   // casts here.
1290   // FIXME: We don't allow floating point scalars as input.
1291   Expr *FirstArg = TheCall->getArg(0);
1292   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1293   if (FirstArgResult.isInvalid())
1294     return ExprError();
1295   FirstArg = FirstArgResult.get();
1296   TheCall->setArg(0, FirstArg);
1297 
1298   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1299   if (!pointerType) {
1300     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1301       << FirstArg->getType() << FirstArg->getSourceRange();
1302     return ExprError();
1303   }
1304 
1305   QualType ValType = pointerType->getPointeeType();
1306   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1307       !ValType->isBlockPointerType()) {
1308     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1309       << FirstArg->getType() << FirstArg->getSourceRange();
1310     return ExprError();
1311   }
1312 
1313   switch (ValType.getObjCLifetime()) {
1314   case Qualifiers::OCL_None:
1315   case Qualifiers::OCL_ExplicitNone:
1316     // okay
1317     break;
1318 
1319   case Qualifiers::OCL_Weak:
1320   case Qualifiers::OCL_Strong:
1321   case Qualifiers::OCL_Autoreleasing:
1322     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1323       << ValType << FirstArg->getSourceRange();
1324     return ExprError();
1325   }
1326 
1327   // Strip any qualifiers off ValType.
1328   ValType = ValType.getUnqualifiedType();
1329 
1330   // The majority of builtins return a value, but a few have special return
1331   // types, so allow them to override appropriately below.
1332   QualType ResultType = ValType;
1333 
1334   // We need to figure out which concrete builtin this maps onto.  For example,
1335   // __sync_fetch_and_add with a 2 byte object turns into
1336   // __sync_fetch_and_add_2.
1337 #define BUILTIN_ROW(x) \
1338   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1339     Builtin::BI##x##_8, Builtin::BI##x##_16 }
1340 
1341   static const unsigned BuiltinIndices[][5] = {
1342     BUILTIN_ROW(__sync_fetch_and_add),
1343     BUILTIN_ROW(__sync_fetch_and_sub),
1344     BUILTIN_ROW(__sync_fetch_and_or),
1345     BUILTIN_ROW(__sync_fetch_and_and),
1346     BUILTIN_ROW(__sync_fetch_and_xor),
1347 
1348     BUILTIN_ROW(__sync_add_and_fetch),
1349     BUILTIN_ROW(__sync_sub_and_fetch),
1350     BUILTIN_ROW(__sync_and_and_fetch),
1351     BUILTIN_ROW(__sync_or_and_fetch),
1352     BUILTIN_ROW(__sync_xor_and_fetch),
1353 
1354     BUILTIN_ROW(__sync_val_compare_and_swap),
1355     BUILTIN_ROW(__sync_bool_compare_and_swap),
1356     BUILTIN_ROW(__sync_lock_test_and_set),
1357     BUILTIN_ROW(__sync_lock_release),
1358     BUILTIN_ROW(__sync_swap)
1359   };
1360 #undef BUILTIN_ROW
1361 
1362   // Determine the index of the size.
1363   unsigned SizeIndex;
1364   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1365   case 1: SizeIndex = 0; break;
1366   case 2: SizeIndex = 1; break;
1367   case 4: SizeIndex = 2; break;
1368   case 8: SizeIndex = 3; break;
1369   case 16: SizeIndex = 4; break;
1370   default:
1371     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1372       << FirstArg->getType() << FirstArg->getSourceRange();
1373     return ExprError();
1374   }
1375 
1376   // Each of these builtins has one pointer argument, followed by some number of
1377   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1378   // that we ignore.  Find out which row of BuiltinIndices to read from as well
1379   // as the number of fixed args.
1380   unsigned BuiltinID = FDecl->getBuiltinID();
1381   unsigned BuiltinIndex, NumFixed = 1;
1382   switch (BuiltinID) {
1383   default: llvm_unreachable("Unknown overloaded atomic builtin!");
1384   case Builtin::BI__sync_fetch_and_add:
1385   case Builtin::BI__sync_fetch_and_add_1:
1386   case Builtin::BI__sync_fetch_and_add_2:
1387   case Builtin::BI__sync_fetch_and_add_4:
1388   case Builtin::BI__sync_fetch_and_add_8:
1389   case Builtin::BI__sync_fetch_and_add_16:
1390     BuiltinIndex = 0;
1391     break;
1392 
1393   case Builtin::BI__sync_fetch_and_sub:
1394   case Builtin::BI__sync_fetch_and_sub_1:
1395   case Builtin::BI__sync_fetch_and_sub_2:
1396   case Builtin::BI__sync_fetch_and_sub_4:
1397   case Builtin::BI__sync_fetch_and_sub_8:
1398   case Builtin::BI__sync_fetch_and_sub_16:
1399     BuiltinIndex = 1;
1400     break;
1401 
1402   case Builtin::BI__sync_fetch_and_or:
1403   case Builtin::BI__sync_fetch_and_or_1:
1404   case Builtin::BI__sync_fetch_and_or_2:
1405   case Builtin::BI__sync_fetch_and_or_4:
1406   case Builtin::BI__sync_fetch_and_or_8:
1407   case Builtin::BI__sync_fetch_and_or_16:
1408     BuiltinIndex = 2;
1409     break;
1410 
1411   case Builtin::BI__sync_fetch_and_and:
1412   case Builtin::BI__sync_fetch_and_and_1:
1413   case Builtin::BI__sync_fetch_and_and_2:
1414   case Builtin::BI__sync_fetch_and_and_4:
1415   case Builtin::BI__sync_fetch_and_and_8:
1416   case Builtin::BI__sync_fetch_and_and_16:
1417     BuiltinIndex = 3;
1418     break;
1419 
1420   case Builtin::BI__sync_fetch_and_xor:
1421   case Builtin::BI__sync_fetch_and_xor_1:
1422   case Builtin::BI__sync_fetch_and_xor_2:
1423   case Builtin::BI__sync_fetch_and_xor_4:
1424   case Builtin::BI__sync_fetch_and_xor_8:
1425   case Builtin::BI__sync_fetch_and_xor_16:
1426     BuiltinIndex = 4;
1427     break;
1428 
1429   case Builtin::BI__sync_add_and_fetch:
1430   case Builtin::BI__sync_add_and_fetch_1:
1431   case Builtin::BI__sync_add_and_fetch_2:
1432   case Builtin::BI__sync_add_and_fetch_4:
1433   case Builtin::BI__sync_add_and_fetch_8:
1434   case Builtin::BI__sync_add_and_fetch_16:
1435     BuiltinIndex = 5;
1436     break;
1437 
1438   case Builtin::BI__sync_sub_and_fetch:
1439   case Builtin::BI__sync_sub_and_fetch_1:
1440   case Builtin::BI__sync_sub_and_fetch_2:
1441   case Builtin::BI__sync_sub_and_fetch_4:
1442   case Builtin::BI__sync_sub_and_fetch_8:
1443   case Builtin::BI__sync_sub_and_fetch_16:
1444     BuiltinIndex = 6;
1445     break;
1446 
1447   case Builtin::BI__sync_and_and_fetch:
1448   case Builtin::BI__sync_and_and_fetch_1:
1449   case Builtin::BI__sync_and_and_fetch_2:
1450   case Builtin::BI__sync_and_and_fetch_4:
1451   case Builtin::BI__sync_and_and_fetch_8:
1452   case Builtin::BI__sync_and_and_fetch_16:
1453     BuiltinIndex = 7;
1454     break;
1455 
1456   case Builtin::BI__sync_or_and_fetch:
1457   case Builtin::BI__sync_or_and_fetch_1:
1458   case Builtin::BI__sync_or_and_fetch_2:
1459   case Builtin::BI__sync_or_and_fetch_4:
1460   case Builtin::BI__sync_or_and_fetch_8:
1461   case Builtin::BI__sync_or_and_fetch_16:
1462     BuiltinIndex = 8;
1463     break;
1464 
1465   case Builtin::BI__sync_xor_and_fetch:
1466   case Builtin::BI__sync_xor_and_fetch_1:
1467   case Builtin::BI__sync_xor_and_fetch_2:
1468   case Builtin::BI__sync_xor_and_fetch_4:
1469   case Builtin::BI__sync_xor_and_fetch_8:
1470   case Builtin::BI__sync_xor_and_fetch_16:
1471     BuiltinIndex = 9;
1472     break;
1473 
1474   case Builtin::BI__sync_val_compare_and_swap:
1475   case Builtin::BI__sync_val_compare_and_swap_1:
1476   case Builtin::BI__sync_val_compare_and_swap_2:
1477   case Builtin::BI__sync_val_compare_and_swap_4:
1478   case Builtin::BI__sync_val_compare_and_swap_8:
1479   case Builtin::BI__sync_val_compare_and_swap_16:
1480     BuiltinIndex = 10;
1481     NumFixed = 2;
1482     break;
1483 
1484   case Builtin::BI__sync_bool_compare_and_swap:
1485   case Builtin::BI__sync_bool_compare_and_swap_1:
1486   case Builtin::BI__sync_bool_compare_and_swap_2:
1487   case Builtin::BI__sync_bool_compare_and_swap_4:
1488   case Builtin::BI__sync_bool_compare_and_swap_8:
1489   case Builtin::BI__sync_bool_compare_and_swap_16:
1490     BuiltinIndex = 11;
1491     NumFixed = 2;
1492     ResultType = Context.BoolTy;
1493     break;
1494 
1495   case Builtin::BI__sync_lock_test_and_set:
1496   case Builtin::BI__sync_lock_test_and_set_1:
1497   case Builtin::BI__sync_lock_test_and_set_2:
1498   case Builtin::BI__sync_lock_test_and_set_4:
1499   case Builtin::BI__sync_lock_test_and_set_8:
1500   case Builtin::BI__sync_lock_test_and_set_16:
1501     BuiltinIndex = 12;
1502     break;
1503 
1504   case Builtin::BI__sync_lock_release:
1505   case Builtin::BI__sync_lock_release_1:
1506   case Builtin::BI__sync_lock_release_2:
1507   case Builtin::BI__sync_lock_release_4:
1508   case Builtin::BI__sync_lock_release_8:
1509   case Builtin::BI__sync_lock_release_16:
1510     BuiltinIndex = 13;
1511     NumFixed = 0;
1512     ResultType = Context.VoidTy;
1513     break;
1514 
1515   case Builtin::BI__sync_swap:
1516   case Builtin::BI__sync_swap_1:
1517   case Builtin::BI__sync_swap_2:
1518   case Builtin::BI__sync_swap_4:
1519   case Builtin::BI__sync_swap_8:
1520   case Builtin::BI__sync_swap_16:
1521     BuiltinIndex = 14;
1522     break;
1523   }
1524 
1525   // Now that we know how many fixed arguments we expect, first check that we
1526   // have at least that many.
1527   if (TheCall->getNumArgs() < 1+NumFixed) {
1528     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1529       << 0 << 1+NumFixed << TheCall->getNumArgs()
1530       << TheCall->getCallee()->getSourceRange();
1531     return ExprError();
1532   }
1533 
1534   // Get the decl for the concrete builtin from this, we can tell what the
1535   // concrete integer type we should convert to is.
1536   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1537   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1538   FunctionDecl *NewBuiltinDecl;
1539   if (NewBuiltinID == BuiltinID)
1540     NewBuiltinDecl = FDecl;
1541   else {
1542     // Perform builtin lookup to avoid redeclaring it.
1543     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1544     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1545     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1546     assert(Res.getFoundDecl());
1547     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1548     if (!NewBuiltinDecl)
1549       return ExprError();
1550   }
1551 
1552   // The first argument --- the pointer --- has a fixed type; we
1553   // deduce the types of the rest of the arguments accordingly.  Walk
1554   // the remaining arguments, converting them to the deduced value type.
1555   for (unsigned i = 0; i != NumFixed; ++i) {
1556     ExprResult Arg = TheCall->getArg(i+1);
1557 
1558     // GCC does an implicit conversion to the pointer or integer ValType.  This
1559     // can fail in some cases (1i -> int**), check for this error case now.
1560     // Initialize the argument.
1561     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1562                                                    ValType, /*consume*/ false);
1563     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1564     if (Arg.isInvalid())
1565       return ExprError();
1566 
1567     // Okay, we have something that *can* be converted to the right type.  Check
1568     // to see if there is a potentially weird extension going on here.  This can
1569     // happen when you do an atomic operation on something like an char* and
1570     // pass in 42.  The 42 gets converted to char.  This is even more strange
1571     // for things like 45.123 -> char, etc.
1572     // FIXME: Do this check.
1573     TheCall->setArg(i+1, Arg.get());
1574   }
1575 
1576   ASTContext& Context = this->getASTContext();
1577 
1578   // Create a new DeclRefExpr to refer to the new decl.
1579   DeclRefExpr* NewDRE = DeclRefExpr::Create(
1580       Context,
1581       DRE->getQualifierLoc(),
1582       SourceLocation(),
1583       NewBuiltinDecl,
1584       /*enclosing*/ false,
1585       DRE->getLocation(),
1586       Context.BuiltinFnTy,
1587       DRE->getValueKind());
1588 
1589   // Set the callee in the CallExpr.
1590   // FIXME: This loses syntactic information.
1591   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1592   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1593                                               CK_BuiltinFnToFnPtr);
1594   TheCall->setCallee(PromotedCall.get());
1595 
1596   // Change the result type of the call to match the original value type. This
1597   // is arbitrary, but the codegen for these builtins ins design to handle it
1598   // gracefully.
1599   TheCall->setType(ResultType);
1600 
1601   return TheCallResult;
1602 }
1603 
1604 /// CheckObjCString - Checks that the argument to the builtin
1605 /// CFString constructor is correct
1606 /// Note: It might also make sense to do the UTF-16 conversion here (would
1607 /// simplify the backend).
1608 bool Sema::CheckObjCString(Expr *Arg) {
1609   Arg = Arg->IgnoreParenCasts();
1610   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1611 
1612   if (!Literal || !Literal->isAscii()) {
1613     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1614       << Arg->getSourceRange();
1615     return true;
1616   }
1617 
1618   if (Literal->containsNonAsciiOrNull()) {
1619     StringRef String = Literal->getString();
1620     unsigned NumBytes = String.size();
1621     SmallVector<UTF16, 128> ToBuf(NumBytes);
1622     const UTF8 *FromPtr = (const UTF8 *)String.data();
1623     UTF16 *ToPtr = &ToBuf[0];
1624 
1625     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1626                                                  &ToPtr, ToPtr + NumBytes,
1627                                                  strictConversion);
1628     // Check for conversion failure.
1629     if (Result != conversionOK)
1630       Diag(Arg->getLocStart(),
1631            diag::warn_cfstring_truncated) << Arg->getSourceRange();
1632   }
1633   return false;
1634 }
1635 
1636 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1637 /// Emit an error and return true on failure, return false on success.
1638 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1639   Expr *Fn = TheCall->getCallee();
1640   if (TheCall->getNumArgs() > 2) {
1641     Diag(TheCall->getArg(2)->getLocStart(),
1642          diag::err_typecheck_call_too_many_args)
1643       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1644       << Fn->getSourceRange()
1645       << SourceRange(TheCall->getArg(2)->getLocStart(),
1646                      (*(TheCall->arg_end()-1))->getLocEnd());
1647     return true;
1648   }
1649 
1650   if (TheCall->getNumArgs() < 2) {
1651     return Diag(TheCall->getLocEnd(),
1652       diag::err_typecheck_call_too_few_args_at_least)
1653       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1654   }
1655 
1656   // Type-check the first argument normally.
1657   if (checkBuiltinArgument(*this, TheCall, 0))
1658     return true;
1659 
1660   // Determine whether the current function is variadic or not.
1661   BlockScopeInfo *CurBlock = getCurBlock();
1662   bool isVariadic;
1663   if (CurBlock)
1664     isVariadic = CurBlock->TheDecl->isVariadic();
1665   else if (FunctionDecl *FD = getCurFunctionDecl())
1666     isVariadic = FD->isVariadic();
1667   else
1668     isVariadic = getCurMethodDecl()->isVariadic();
1669 
1670   if (!isVariadic) {
1671     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1672     return true;
1673   }
1674 
1675   // Verify that the second argument to the builtin is the last argument of the
1676   // current function or method.
1677   bool SecondArgIsLastNamedArgument = false;
1678   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1679 
1680   // These are valid if SecondArgIsLastNamedArgument is false after the next
1681   // block.
1682   QualType Type;
1683   SourceLocation ParamLoc;
1684 
1685   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1686     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1687       // FIXME: This isn't correct for methods (results in bogus warning).
1688       // Get the last formal in the current function.
1689       const ParmVarDecl *LastArg;
1690       if (CurBlock)
1691         LastArg = *(CurBlock->TheDecl->param_end()-1);
1692       else if (FunctionDecl *FD = getCurFunctionDecl())
1693         LastArg = *(FD->param_end()-1);
1694       else
1695         LastArg = *(getCurMethodDecl()->param_end()-1);
1696       SecondArgIsLastNamedArgument = PV == LastArg;
1697 
1698       Type = PV->getType();
1699       ParamLoc = PV->getLocation();
1700     }
1701   }
1702 
1703   if (!SecondArgIsLastNamedArgument)
1704     Diag(TheCall->getArg(1)->getLocStart(),
1705          diag::warn_second_parameter_of_va_start_not_last_named_argument);
1706   else if (Type->isReferenceType()) {
1707     Diag(Arg->getLocStart(),
1708          diag::warn_va_start_of_reference_type_is_undefined);
1709     Diag(ParamLoc, diag::note_parameter_type) << Type;
1710   }
1711 
1712   TheCall->setType(Context.VoidTy);
1713   return false;
1714 }
1715 
1716 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1717 /// friends.  This is declared to take (...), so we have to check everything.
1718 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1719   if (TheCall->getNumArgs() < 2)
1720     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1721       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1722   if (TheCall->getNumArgs() > 2)
1723     return Diag(TheCall->getArg(2)->getLocStart(),
1724                 diag::err_typecheck_call_too_many_args)
1725       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1726       << SourceRange(TheCall->getArg(2)->getLocStart(),
1727                      (*(TheCall->arg_end()-1))->getLocEnd());
1728 
1729   ExprResult OrigArg0 = TheCall->getArg(0);
1730   ExprResult OrigArg1 = TheCall->getArg(1);
1731 
1732   // Do standard promotions between the two arguments, returning their common
1733   // type.
1734   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1735   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1736     return true;
1737 
1738   // Make sure any conversions are pushed back into the call; this is
1739   // type safe since unordered compare builtins are declared as "_Bool
1740   // foo(...)".
1741   TheCall->setArg(0, OrigArg0.get());
1742   TheCall->setArg(1, OrigArg1.get());
1743 
1744   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1745     return false;
1746 
1747   // If the common type isn't a real floating type, then the arguments were
1748   // invalid for this operation.
1749   if (Res.isNull() || !Res->isRealFloatingType())
1750     return Diag(OrigArg0.get()->getLocStart(),
1751                 diag::err_typecheck_call_invalid_ordered_compare)
1752       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1753       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1754 
1755   return false;
1756 }
1757 
1758 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1759 /// __builtin_isnan and friends.  This is declared to take (...), so we have
1760 /// to check everything. We expect the last argument to be a floating point
1761 /// value.
1762 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1763   if (TheCall->getNumArgs() < NumArgs)
1764     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1765       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1766   if (TheCall->getNumArgs() > NumArgs)
1767     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1768                 diag::err_typecheck_call_too_many_args)
1769       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1770       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1771                      (*(TheCall->arg_end()-1))->getLocEnd());
1772 
1773   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1774 
1775   if (OrigArg->isTypeDependent())
1776     return false;
1777 
1778   // This operation requires a non-_Complex floating-point number.
1779   if (!OrigArg->getType()->isRealFloatingType())
1780     return Diag(OrigArg->getLocStart(),
1781                 diag::err_typecheck_call_invalid_unary_fp)
1782       << OrigArg->getType() << OrigArg->getSourceRange();
1783 
1784   // If this is an implicit conversion from float -> double, remove it.
1785   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1786     Expr *CastArg = Cast->getSubExpr();
1787     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1788       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1789              "promotion from float to double is the only expected cast here");
1790       Cast->setSubExpr(nullptr);
1791       TheCall->setArg(NumArgs-1, CastArg);
1792     }
1793   }
1794 
1795   return false;
1796 }
1797 
1798 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1799 // This is declared to take (...), so we have to check everything.
1800 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1801   if (TheCall->getNumArgs() < 2)
1802     return ExprError(Diag(TheCall->getLocEnd(),
1803                           diag::err_typecheck_call_too_few_args_at_least)
1804                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1805                      << TheCall->getSourceRange());
1806 
1807   // Determine which of the following types of shufflevector we're checking:
1808   // 1) unary, vector mask: (lhs, mask)
1809   // 2) binary, vector mask: (lhs, rhs, mask)
1810   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1811   QualType resType = TheCall->getArg(0)->getType();
1812   unsigned numElements = 0;
1813 
1814   if (!TheCall->getArg(0)->isTypeDependent() &&
1815       !TheCall->getArg(1)->isTypeDependent()) {
1816     QualType LHSType = TheCall->getArg(0)->getType();
1817     QualType RHSType = TheCall->getArg(1)->getType();
1818 
1819     if (!LHSType->isVectorType() || !RHSType->isVectorType())
1820       return ExprError(Diag(TheCall->getLocStart(),
1821                             diag::err_shufflevector_non_vector)
1822                        << SourceRange(TheCall->getArg(0)->getLocStart(),
1823                                       TheCall->getArg(1)->getLocEnd()));
1824 
1825     numElements = LHSType->getAs<VectorType>()->getNumElements();
1826     unsigned numResElements = TheCall->getNumArgs() - 2;
1827 
1828     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1829     // with mask.  If so, verify that RHS is an integer vector type with the
1830     // same number of elts as lhs.
1831     if (TheCall->getNumArgs() == 2) {
1832       if (!RHSType->hasIntegerRepresentation() ||
1833           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1834         return ExprError(Diag(TheCall->getLocStart(),
1835                               diag::err_shufflevector_incompatible_vector)
1836                          << SourceRange(TheCall->getArg(1)->getLocStart(),
1837                                         TheCall->getArg(1)->getLocEnd()));
1838     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1839       return ExprError(Diag(TheCall->getLocStart(),
1840                             diag::err_shufflevector_incompatible_vector)
1841                        << SourceRange(TheCall->getArg(0)->getLocStart(),
1842                                       TheCall->getArg(1)->getLocEnd()));
1843     } else if (numElements != numResElements) {
1844       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1845       resType = Context.getVectorType(eltType, numResElements,
1846                                       VectorType::GenericVector);
1847     }
1848   }
1849 
1850   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1851     if (TheCall->getArg(i)->isTypeDependent() ||
1852         TheCall->getArg(i)->isValueDependent())
1853       continue;
1854 
1855     llvm::APSInt Result(32);
1856     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1857       return ExprError(Diag(TheCall->getLocStart(),
1858                             diag::err_shufflevector_nonconstant_argument)
1859                        << TheCall->getArg(i)->getSourceRange());
1860 
1861     // Allow -1 which will be translated to undef in the IR.
1862     if (Result.isSigned() && Result.isAllOnesValue())
1863       continue;
1864 
1865     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1866       return ExprError(Diag(TheCall->getLocStart(),
1867                             diag::err_shufflevector_argument_too_large)
1868                        << TheCall->getArg(i)->getSourceRange());
1869   }
1870 
1871   SmallVector<Expr*, 32> exprs;
1872 
1873   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1874     exprs.push_back(TheCall->getArg(i));
1875     TheCall->setArg(i, nullptr);
1876   }
1877 
1878   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1879                                          TheCall->getCallee()->getLocStart(),
1880                                          TheCall->getRParenLoc());
1881 }
1882 
1883 /// SemaConvertVectorExpr - Handle __builtin_convertvector
1884 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1885                                        SourceLocation BuiltinLoc,
1886                                        SourceLocation RParenLoc) {
1887   ExprValueKind VK = VK_RValue;
1888   ExprObjectKind OK = OK_Ordinary;
1889   QualType DstTy = TInfo->getType();
1890   QualType SrcTy = E->getType();
1891 
1892   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1893     return ExprError(Diag(BuiltinLoc,
1894                           diag::err_convertvector_non_vector)
1895                      << E->getSourceRange());
1896   if (!DstTy->isVectorType() && !DstTy->isDependentType())
1897     return ExprError(Diag(BuiltinLoc,
1898                           diag::err_convertvector_non_vector_type));
1899 
1900   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1901     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1902     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1903     if (SrcElts != DstElts)
1904       return ExprError(Diag(BuiltinLoc,
1905                             diag::err_convertvector_incompatible_vector)
1906                        << E->getSourceRange());
1907   }
1908 
1909   return new (Context)
1910       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
1911 }
1912 
1913 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1914 // This is declared to take (const void*, ...) and can take two
1915 // optional constant int args.
1916 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1917   unsigned NumArgs = TheCall->getNumArgs();
1918 
1919   if (NumArgs > 3)
1920     return Diag(TheCall->getLocEnd(),
1921              diag::err_typecheck_call_too_many_args_at_most)
1922              << 0 /*function call*/ << 3 << NumArgs
1923              << TheCall->getSourceRange();
1924 
1925   // Argument 0 is checked for us and the remaining arguments must be
1926   // constant integers.
1927   for (unsigned i = 1; i != NumArgs; ++i)
1928     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
1929       return true;
1930 
1931   return false;
1932 }
1933 
1934 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1935 /// TheCall is a constant expression.
1936 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1937                                   llvm::APSInt &Result) {
1938   Expr *Arg = TheCall->getArg(ArgNum);
1939   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1940   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1941 
1942   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1943 
1944   if (!Arg->isIntegerConstantExpr(Result, Context))
1945     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1946                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1947 
1948   return false;
1949 }
1950 
1951 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
1952 /// TheCall is a constant expression in the range [Low, High].
1953 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
1954                                        int Low, int High) {
1955   llvm::APSInt Result;
1956 
1957   // We can't check the value of a dependent argument.
1958   Expr *Arg = TheCall->getArg(ArgNum);
1959   if (Arg->isTypeDependent() || Arg->isValueDependent())
1960     return false;
1961 
1962   // Check constant-ness first.
1963   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1964     return true;
1965 
1966   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
1967     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1968       << Low << High << Arg->getSourceRange();
1969 
1970   return false;
1971 }
1972 
1973 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1974 /// This checks that val is a constant 1.
1975 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1976   Expr *Arg = TheCall->getArg(1);
1977   llvm::APSInt Result;
1978 
1979   // TODO: This is less than ideal. Overload this to take a value.
1980   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1981     return true;
1982 
1983   if (Result != 1)
1984     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1985              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1986 
1987   return false;
1988 }
1989 
1990 namespace {
1991 enum StringLiteralCheckType {
1992   SLCT_NotALiteral,
1993   SLCT_UncheckedLiteral,
1994   SLCT_CheckedLiteral
1995 };
1996 }
1997 
1998 // Determine if an expression is a string literal or constant string.
1999 // If this function returns false on the arguments to a function expecting a
2000 // format string, we will usually need to emit a warning.
2001 // True string literals are then checked by CheckFormatString.
2002 static StringLiteralCheckType
2003 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2004                       bool HasVAListArg, unsigned format_idx,
2005                       unsigned firstDataArg, Sema::FormatStringType Type,
2006                       Sema::VariadicCallType CallType, bool InFunctionCall,
2007                       llvm::SmallBitVector &CheckedVarArgs) {
2008  tryAgain:
2009   if (E->isTypeDependent() || E->isValueDependent())
2010     return SLCT_NotALiteral;
2011 
2012   E = E->IgnoreParenCasts();
2013 
2014   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2015     // Technically -Wformat-nonliteral does not warn about this case.
2016     // The behavior of printf and friends in this case is implementation
2017     // dependent.  Ideally if the format string cannot be null then
2018     // it should have a 'nonnull' attribute in the function prototype.
2019     return SLCT_UncheckedLiteral;
2020 
2021   switch (E->getStmtClass()) {
2022   case Stmt::BinaryConditionalOperatorClass:
2023   case Stmt::ConditionalOperatorClass: {
2024     // The expression is a literal if both sub-expressions were, and it was
2025     // completely checked only if both sub-expressions were checked.
2026     const AbstractConditionalOperator *C =
2027         cast<AbstractConditionalOperator>(E);
2028     StringLiteralCheckType Left =
2029         checkFormatStringExpr(S, C->getTrueExpr(), Args,
2030                               HasVAListArg, format_idx, firstDataArg,
2031                               Type, CallType, InFunctionCall, CheckedVarArgs);
2032     if (Left == SLCT_NotALiteral)
2033       return SLCT_NotALiteral;
2034     StringLiteralCheckType Right =
2035         checkFormatStringExpr(S, C->getFalseExpr(), Args,
2036                               HasVAListArg, format_idx, firstDataArg,
2037                               Type, CallType, InFunctionCall, CheckedVarArgs);
2038     return Left < Right ? Left : Right;
2039   }
2040 
2041   case Stmt::ImplicitCastExprClass: {
2042     E = cast<ImplicitCastExpr>(E)->getSubExpr();
2043     goto tryAgain;
2044   }
2045 
2046   case Stmt::OpaqueValueExprClass:
2047     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2048       E = src;
2049       goto tryAgain;
2050     }
2051     return SLCT_NotALiteral;
2052 
2053   case Stmt::PredefinedExprClass:
2054     // While __func__, etc., are technically not string literals, they
2055     // cannot contain format specifiers and thus are not a security
2056     // liability.
2057     return SLCT_UncheckedLiteral;
2058 
2059   case Stmt::DeclRefExprClass: {
2060     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2061 
2062     // As an exception, do not flag errors for variables binding to
2063     // const string literals.
2064     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2065       bool isConstant = false;
2066       QualType T = DR->getType();
2067 
2068       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2069         isConstant = AT->getElementType().isConstant(S.Context);
2070       } else if (const PointerType *PT = T->getAs<PointerType>()) {
2071         isConstant = T.isConstant(S.Context) &&
2072                      PT->getPointeeType().isConstant(S.Context);
2073       } else if (T->isObjCObjectPointerType()) {
2074         // In ObjC, there is usually no "const ObjectPointer" type,
2075         // so don't check if the pointee type is constant.
2076         isConstant = T.isConstant(S.Context);
2077       }
2078 
2079       if (isConstant) {
2080         if (const Expr *Init = VD->getAnyInitializer()) {
2081           // Look through initializers like const char c[] = { "foo" }
2082           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2083             if (InitList->isStringLiteralInit())
2084               Init = InitList->getInit(0)->IgnoreParenImpCasts();
2085           }
2086           return checkFormatStringExpr(S, Init, Args,
2087                                        HasVAListArg, format_idx,
2088                                        firstDataArg, Type, CallType,
2089                                        /*InFunctionCall*/false, CheckedVarArgs);
2090         }
2091       }
2092 
2093       // For vprintf* functions (i.e., HasVAListArg==true), we add a
2094       // special check to see if the format string is a function parameter
2095       // of the function calling the printf function.  If the function
2096       // has an attribute indicating it is a printf-like function, then we
2097       // should suppress warnings concerning non-literals being used in a call
2098       // to a vprintf function.  For example:
2099       //
2100       // void
2101       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2102       //      va_list ap;
2103       //      va_start(ap, fmt);
2104       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
2105       //      ...
2106       // }
2107       if (HasVAListArg) {
2108         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2109           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2110             int PVIndex = PV->getFunctionScopeIndex() + 1;
2111             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2112               // adjust for implicit parameter
2113               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2114                 if (MD->isInstance())
2115                   ++PVIndex;
2116               // We also check if the formats are compatible.
2117               // We can't pass a 'scanf' string to a 'printf' function.
2118               if (PVIndex == PVFormat->getFormatIdx() &&
2119                   Type == S.GetFormatStringType(PVFormat))
2120                 return SLCT_UncheckedLiteral;
2121             }
2122           }
2123         }
2124       }
2125     }
2126 
2127     return SLCT_NotALiteral;
2128   }
2129 
2130   case Stmt::CallExprClass:
2131   case Stmt::CXXMemberCallExprClass: {
2132     const CallExpr *CE = cast<CallExpr>(E);
2133     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2134       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2135         unsigned ArgIndex = FA->getFormatIdx();
2136         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2137           if (MD->isInstance())
2138             --ArgIndex;
2139         const Expr *Arg = CE->getArg(ArgIndex - 1);
2140 
2141         return checkFormatStringExpr(S, Arg, Args,
2142                                      HasVAListArg, format_idx, firstDataArg,
2143                                      Type, CallType, InFunctionCall,
2144                                      CheckedVarArgs);
2145       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2146         unsigned BuiltinID = FD->getBuiltinID();
2147         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2148             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2149           const Expr *Arg = CE->getArg(0);
2150           return checkFormatStringExpr(S, Arg, Args,
2151                                        HasVAListArg, format_idx,
2152                                        firstDataArg, Type, CallType,
2153                                        InFunctionCall, CheckedVarArgs);
2154         }
2155       }
2156     }
2157 
2158     return SLCT_NotALiteral;
2159   }
2160   case Stmt::ObjCStringLiteralClass:
2161   case Stmt::StringLiteralClass: {
2162     const StringLiteral *StrE = nullptr;
2163 
2164     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2165       StrE = ObjCFExpr->getString();
2166     else
2167       StrE = cast<StringLiteral>(E);
2168 
2169     if (StrE) {
2170       S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2171                           Type, InFunctionCall, CallType, CheckedVarArgs);
2172       return SLCT_CheckedLiteral;
2173     }
2174 
2175     return SLCT_NotALiteral;
2176   }
2177 
2178   default:
2179     return SLCT_NotALiteral;
2180   }
2181 }
2182 
2183 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2184   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2185   .Case("scanf", FST_Scanf)
2186   .Cases("printf", "printf0", FST_Printf)
2187   .Cases("NSString", "CFString", FST_NSString)
2188   .Case("strftime", FST_Strftime)
2189   .Case("strfmon", FST_Strfmon)
2190   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2191   .Default(FST_Unknown);
2192 }
2193 
2194 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2195 /// functions) for correct use of format strings.
2196 /// Returns true if a format string has been fully checked.
2197 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2198                                 ArrayRef<const Expr *> Args,
2199                                 bool IsCXXMember,
2200                                 VariadicCallType CallType,
2201                                 SourceLocation Loc, SourceRange Range,
2202                                 llvm::SmallBitVector &CheckedVarArgs) {
2203   FormatStringInfo FSI;
2204   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2205     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2206                                 FSI.FirstDataArg, GetFormatStringType(Format),
2207                                 CallType, Loc, Range, CheckedVarArgs);
2208   return false;
2209 }
2210 
2211 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2212                                 bool HasVAListArg, unsigned format_idx,
2213                                 unsigned firstDataArg, FormatStringType Type,
2214                                 VariadicCallType CallType,
2215                                 SourceLocation Loc, SourceRange Range,
2216                                 llvm::SmallBitVector &CheckedVarArgs) {
2217   // CHECK: printf/scanf-like function is called with no format string.
2218   if (format_idx >= Args.size()) {
2219     Diag(Loc, diag::warn_missing_format_string) << Range;
2220     return false;
2221   }
2222 
2223   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2224 
2225   // CHECK: format string is not a string literal.
2226   //
2227   // Dynamically generated format strings are difficult to
2228   // automatically vet at compile time.  Requiring that format strings
2229   // are string literals: (1) permits the checking of format strings by
2230   // the compiler and thereby (2) can practically remove the source of
2231   // many format string exploits.
2232 
2233   // Format string can be either ObjC string (e.g. @"%d") or
2234   // C string (e.g. "%d")
2235   // ObjC string uses the same format specifiers as C string, so we can use
2236   // the same format string checking logic for both ObjC and C strings.
2237   StringLiteralCheckType CT =
2238       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2239                             format_idx, firstDataArg, Type, CallType,
2240                             /*IsFunctionCall*/true, CheckedVarArgs);
2241   if (CT != SLCT_NotALiteral)
2242     // Literal format string found, check done!
2243     return CT == SLCT_CheckedLiteral;
2244 
2245   // Strftime is particular as it always uses a single 'time' argument,
2246   // so it is safe to pass a non-literal string.
2247   if (Type == FST_Strftime)
2248     return false;
2249 
2250   // Do not emit diag when the string param is a macro expansion and the
2251   // format is either NSString or CFString. This is a hack to prevent
2252   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2253   // which are usually used in place of NS and CF string literals.
2254   if (Type == FST_NSString &&
2255       SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2256     return false;
2257 
2258   // If there are no arguments specified, warn with -Wformat-security, otherwise
2259   // warn only with -Wformat-nonliteral.
2260   if (Args.size() == firstDataArg)
2261     Diag(Args[format_idx]->getLocStart(),
2262          diag::warn_format_nonliteral_noargs)
2263       << OrigFormatExpr->getSourceRange();
2264   else
2265     Diag(Args[format_idx]->getLocStart(),
2266          diag::warn_format_nonliteral)
2267            << OrigFormatExpr->getSourceRange();
2268   return false;
2269 }
2270 
2271 namespace {
2272 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2273 protected:
2274   Sema &S;
2275   const StringLiteral *FExpr;
2276   const Expr *OrigFormatExpr;
2277   const unsigned FirstDataArg;
2278   const unsigned NumDataArgs;
2279   const char *Beg; // Start of format string.
2280   const bool HasVAListArg;
2281   ArrayRef<const Expr *> Args;
2282   unsigned FormatIdx;
2283   llvm::SmallBitVector CoveredArgs;
2284   bool usesPositionalArgs;
2285   bool atFirstArg;
2286   bool inFunctionCall;
2287   Sema::VariadicCallType CallType;
2288   llvm::SmallBitVector &CheckedVarArgs;
2289 public:
2290   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2291                      const Expr *origFormatExpr, unsigned firstDataArg,
2292                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
2293                      ArrayRef<const Expr *> Args,
2294                      unsigned formatIdx, bool inFunctionCall,
2295                      Sema::VariadicCallType callType,
2296                      llvm::SmallBitVector &CheckedVarArgs)
2297     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2298       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2299       Beg(beg), HasVAListArg(hasVAListArg),
2300       Args(Args), FormatIdx(formatIdx),
2301       usesPositionalArgs(false), atFirstArg(true),
2302       inFunctionCall(inFunctionCall), CallType(callType),
2303       CheckedVarArgs(CheckedVarArgs) {
2304     CoveredArgs.resize(numDataArgs);
2305     CoveredArgs.reset();
2306   }
2307 
2308   void DoneProcessing();
2309 
2310   void HandleIncompleteSpecifier(const char *startSpecifier,
2311                                  unsigned specifierLen) override;
2312 
2313   void HandleInvalidLengthModifier(
2314                            const analyze_format_string::FormatSpecifier &FS,
2315                            const analyze_format_string::ConversionSpecifier &CS,
2316                            const char *startSpecifier, unsigned specifierLen,
2317                            unsigned DiagID);
2318 
2319   void HandleNonStandardLengthModifier(
2320                     const analyze_format_string::FormatSpecifier &FS,
2321                     const char *startSpecifier, unsigned specifierLen);
2322 
2323   void HandleNonStandardConversionSpecifier(
2324                     const analyze_format_string::ConversionSpecifier &CS,
2325                     const char *startSpecifier, unsigned specifierLen);
2326 
2327   void HandlePosition(const char *startPos, unsigned posLen) override;
2328 
2329   void HandleInvalidPosition(const char *startSpecifier,
2330                              unsigned specifierLen,
2331                              analyze_format_string::PositionContext p) override;
2332 
2333   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
2334 
2335   void HandleNullChar(const char *nullCharacter) override;
2336 
2337   template <typename Range>
2338   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2339                                    const Expr *ArgumentExpr,
2340                                    PartialDiagnostic PDiag,
2341                                    SourceLocation StringLoc,
2342                                    bool IsStringLocation, Range StringRange,
2343                                    ArrayRef<FixItHint> Fixit = None);
2344 
2345 protected:
2346   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2347                                         const char *startSpec,
2348                                         unsigned specifierLen,
2349                                         const char *csStart, unsigned csLen);
2350 
2351   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2352                                          const char *startSpec,
2353                                          unsigned specifierLen);
2354 
2355   SourceRange getFormatStringRange();
2356   CharSourceRange getSpecifierRange(const char *startSpecifier,
2357                                     unsigned specifierLen);
2358   SourceLocation getLocationOfByte(const char *x);
2359 
2360   const Expr *getDataArg(unsigned i) const;
2361 
2362   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2363                     const analyze_format_string::ConversionSpecifier &CS,
2364                     const char *startSpecifier, unsigned specifierLen,
2365                     unsigned argIndex);
2366 
2367   template <typename Range>
2368   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2369                             bool IsStringLocation, Range StringRange,
2370                             ArrayRef<FixItHint> Fixit = None);
2371 };
2372 }
2373 
2374 SourceRange CheckFormatHandler::getFormatStringRange() {
2375   return OrigFormatExpr->getSourceRange();
2376 }
2377 
2378 CharSourceRange CheckFormatHandler::
2379 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2380   SourceLocation Start = getLocationOfByte(startSpecifier);
2381   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2382 
2383   // Advance the end SourceLocation by one due to half-open ranges.
2384   End = End.getLocWithOffset(1);
2385 
2386   return CharSourceRange::getCharRange(Start, End);
2387 }
2388 
2389 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2390   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2391 }
2392 
2393 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2394                                                    unsigned specifierLen){
2395   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2396                        getLocationOfByte(startSpecifier),
2397                        /*IsStringLocation*/true,
2398                        getSpecifierRange(startSpecifier, specifierLen));
2399 }
2400 
2401 void CheckFormatHandler::HandleInvalidLengthModifier(
2402     const analyze_format_string::FormatSpecifier &FS,
2403     const analyze_format_string::ConversionSpecifier &CS,
2404     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2405   using namespace analyze_format_string;
2406 
2407   const LengthModifier &LM = FS.getLengthModifier();
2408   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2409 
2410   // See if we know how to fix this length modifier.
2411   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2412   if (FixedLM) {
2413     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2414                          getLocationOfByte(LM.getStart()),
2415                          /*IsStringLocation*/true,
2416                          getSpecifierRange(startSpecifier, specifierLen));
2417 
2418     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2419       << FixedLM->toString()
2420       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2421 
2422   } else {
2423     FixItHint Hint;
2424     if (DiagID == diag::warn_format_nonsensical_length)
2425       Hint = FixItHint::CreateRemoval(LMRange);
2426 
2427     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2428                          getLocationOfByte(LM.getStart()),
2429                          /*IsStringLocation*/true,
2430                          getSpecifierRange(startSpecifier, specifierLen),
2431                          Hint);
2432   }
2433 }
2434 
2435 void CheckFormatHandler::HandleNonStandardLengthModifier(
2436     const analyze_format_string::FormatSpecifier &FS,
2437     const char *startSpecifier, unsigned specifierLen) {
2438   using namespace analyze_format_string;
2439 
2440   const LengthModifier &LM = FS.getLengthModifier();
2441   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2442 
2443   // See if we know how to fix this length modifier.
2444   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2445   if (FixedLM) {
2446     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2447                            << LM.toString() << 0,
2448                          getLocationOfByte(LM.getStart()),
2449                          /*IsStringLocation*/true,
2450                          getSpecifierRange(startSpecifier, specifierLen));
2451 
2452     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2453       << FixedLM->toString()
2454       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2455 
2456   } else {
2457     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2458                            << LM.toString() << 0,
2459                          getLocationOfByte(LM.getStart()),
2460                          /*IsStringLocation*/true,
2461                          getSpecifierRange(startSpecifier, specifierLen));
2462   }
2463 }
2464 
2465 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2466     const analyze_format_string::ConversionSpecifier &CS,
2467     const char *startSpecifier, unsigned specifierLen) {
2468   using namespace analyze_format_string;
2469 
2470   // See if we know how to fix this conversion specifier.
2471   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2472   if (FixedCS) {
2473     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2474                           << CS.toString() << /*conversion specifier*/1,
2475                          getLocationOfByte(CS.getStart()),
2476                          /*IsStringLocation*/true,
2477                          getSpecifierRange(startSpecifier, specifierLen));
2478 
2479     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2480     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2481       << FixedCS->toString()
2482       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2483   } else {
2484     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2485                           << CS.toString() << /*conversion specifier*/1,
2486                          getLocationOfByte(CS.getStart()),
2487                          /*IsStringLocation*/true,
2488                          getSpecifierRange(startSpecifier, specifierLen));
2489   }
2490 }
2491 
2492 void CheckFormatHandler::HandlePosition(const char *startPos,
2493                                         unsigned posLen) {
2494   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2495                                getLocationOfByte(startPos),
2496                                /*IsStringLocation*/true,
2497                                getSpecifierRange(startPos, posLen));
2498 }
2499 
2500 void
2501 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2502                                      analyze_format_string::PositionContext p) {
2503   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2504                          << (unsigned) p,
2505                        getLocationOfByte(startPos), /*IsStringLocation*/true,
2506                        getSpecifierRange(startPos, posLen));
2507 }
2508 
2509 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2510                                             unsigned posLen) {
2511   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2512                                getLocationOfByte(startPos),
2513                                /*IsStringLocation*/true,
2514                                getSpecifierRange(startPos, posLen));
2515 }
2516 
2517 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2518   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2519     // The presence of a null character is likely an error.
2520     EmitFormatDiagnostic(
2521       S.PDiag(diag::warn_printf_format_string_contains_null_char),
2522       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2523       getFormatStringRange());
2524   }
2525 }
2526 
2527 // Note that this may return NULL if there was an error parsing or building
2528 // one of the argument expressions.
2529 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2530   return Args[FirstDataArg + i];
2531 }
2532 
2533 void CheckFormatHandler::DoneProcessing() {
2534     // Does the number of data arguments exceed the number of
2535     // format conversions in the format string?
2536   if (!HasVAListArg) {
2537       // Find any arguments that weren't covered.
2538     CoveredArgs.flip();
2539     signed notCoveredArg = CoveredArgs.find_first();
2540     if (notCoveredArg >= 0) {
2541       assert((unsigned)notCoveredArg < NumDataArgs);
2542       if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2543         SourceLocation Loc = E->getLocStart();
2544         if (!S.getSourceManager().isInSystemMacro(Loc)) {
2545           EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2546                                Loc, /*IsStringLocation*/false,
2547                                getFormatStringRange());
2548         }
2549       }
2550     }
2551   }
2552 }
2553 
2554 bool
2555 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2556                                                      SourceLocation Loc,
2557                                                      const char *startSpec,
2558                                                      unsigned specifierLen,
2559                                                      const char *csStart,
2560                                                      unsigned csLen) {
2561 
2562   bool keepGoing = true;
2563   if (argIndex < NumDataArgs) {
2564     // Consider the argument coverered, even though the specifier doesn't
2565     // make sense.
2566     CoveredArgs.set(argIndex);
2567   }
2568   else {
2569     // If argIndex exceeds the number of data arguments we
2570     // don't issue a warning because that is just a cascade of warnings (and
2571     // they may have intended '%%' anyway). We don't want to continue processing
2572     // the format string after this point, however, as we will like just get
2573     // gibberish when trying to match arguments.
2574     keepGoing = false;
2575   }
2576 
2577   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2578                          << StringRef(csStart, csLen),
2579                        Loc, /*IsStringLocation*/true,
2580                        getSpecifierRange(startSpec, specifierLen));
2581 
2582   return keepGoing;
2583 }
2584 
2585 void
2586 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2587                                                       const char *startSpec,
2588                                                       unsigned specifierLen) {
2589   EmitFormatDiagnostic(
2590     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2591     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2592 }
2593 
2594 bool
2595 CheckFormatHandler::CheckNumArgs(
2596   const analyze_format_string::FormatSpecifier &FS,
2597   const analyze_format_string::ConversionSpecifier &CS,
2598   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2599 
2600   if (argIndex >= NumDataArgs) {
2601     PartialDiagnostic PDiag = FS.usesPositionalArg()
2602       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2603            << (argIndex+1) << NumDataArgs)
2604       : S.PDiag(diag::warn_printf_insufficient_data_args);
2605     EmitFormatDiagnostic(
2606       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2607       getSpecifierRange(startSpecifier, specifierLen));
2608     return false;
2609   }
2610   return true;
2611 }
2612 
2613 template<typename Range>
2614 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2615                                               SourceLocation Loc,
2616                                               bool IsStringLocation,
2617                                               Range StringRange,
2618                                               ArrayRef<FixItHint> FixIt) {
2619   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2620                        Loc, IsStringLocation, StringRange, FixIt);
2621 }
2622 
2623 /// \brief If the format string is not within the funcion call, emit a note
2624 /// so that the function call and string are in diagnostic messages.
2625 ///
2626 /// \param InFunctionCall if true, the format string is within the function
2627 /// call and only one diagnostic message will be produced.  Otherwise, an
2628 /// extra note will be emitted pointing to location of the format string.
2629 ///
2630 /// \param ArgumentExpr the expression that is passed as the format string
2631 /// argument in the function call.  Used for getting locations when two
2632 /// diagnostics are emitted.
2633 ///
2634 /// \param PDiag the callee should already have provided any strings for the
2635 /// diagnostic message.  This function only adds locations and fixits
2636 /// to diagnostics.
2637 ///
2638 /// \param Loc primary location for diagnostic.  If two diagnostics are
2639 /// required, one will be at Loc and a new SourceLocation will be created for
2640 /// the other one.
2641 ///
2642 /// \param IsStringLocation if true, Loc points to the format string should be
2643 /// used for the note.  Otherwise, Loc points to the argument list and will
2644 /// be used with PDiag.
2645 ///
2646 /// \param StringRange some or all of the string to highlight.  This is
2647 /// templated so it can accept either a CharSourceRange or a SourceRange.
2648 ///
2649 /// \param FixIt optional fix it hint for the format string.
2650 template<typename Range>
2651 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2652                                               const Expr *ArgumentExpr,
2653                                               PartialDiagnostic PDiag,
2654                                               SourceLocation Loc,
2655                                               bool IsStringLocation,
2656                                               Range StringRange,
2657                                               ArrayRef<FixItHint> FixIt) {
2658   if (InFunctionCall) {
2659     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2660     D << StringRange;
2661     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2662          I != E; ++I) {
2663       D << *I;
2664     }
2665   } else {
2666     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2667       << ArgumentExpr->getSourceRange();
2668 
2669     const Sema::SemaDiagnosticBuilder &Note =
2670       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2671              diag::note_format_string_defined);
2672 
2673     Note << StringRange;
2674     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2675          I != E; ++I) {
2676       Note << *I;
2677     }
2678   }
2679 }
2680 
2681 //===--- CHECK: Printf format string checking ------------------------------===//
2682 
2683 namespace {
2684 class CheckPrintfHandler : public CheckFormatHandler {
2685   bool ObjCContext;
2686 public:
2687   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2688                      const Expr *origFormatExpr, unsigned firstDataArg,
2689                      unsigned numDataArgs, bool isObjC,
2690                      const char *beg, bool hasVAListArg,
2691                      ArrayRef<const Expr *> Args,
2692                      unsigned formatIdx, bool inFunctionCall,
2693                      Sema::VariadicCallType CallType,
2694                      llvm::SmallBitVector &CheckedVarArgs)
2695     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2696                          numDataArgs, beg, hasVAListArg, Args,
2697                          formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2698       ObjCContext(isObjC)
2699   {}
2700 
2701 
2702   bool HandleInvalidPrintfConversionSpecifier(
2703                                       const analyze_printf::PrintfSpecifier &FS,
2704                                       const char *startSpecifier,
2705                                       unsigned specifierLen) override;
2706 
2707   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2708                              const char *startSpecifier,
2709                              unsigned specifierLen) override;
2710   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2711                        const char *StartSpecifier,
2712                        unsigned SpecifierLen,
2713                        const Expr *E);
2714 
2715   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2716                     const char *startSpecifier, unsigned specifierLen);
2717   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2718                            const analyze_printf::OptionalAmount &Amt,
2719                            unsigned type,
2720                            const char *startSpecifier, unsigned specifierLen);
2721   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2722                   const analyze_printf::OptionalFlag &flag,
2723                   const char *startSpecifier, unsigned specifierLen);
2724   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2725                          const analyze_printf::OptionalFlag &ignoredFlag,
2726                          const analyze_printf::OptionalFlag &flag,
2727                          const char *startSpecifier, unsigned specifierLen);
2728   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2729                            const Expr *E);
2730 
2731 };
2732 }
2733 
2734 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2735                                       const analyze_printf::PrintfSpecifier &FS,
2736                                       const char *startSpecifier,
2737                                       unsigned specifierLen) {
2738   const analyze_printf::PrintfConversionSpecifier &CS =
2739     FS.getConversionSpecifier();
2740 
2741   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2742                                           getLocationOfByte(CS.getStart()),
2743                                           startSpecifier, specifierLen,
2744                                           CS.getStart(), CS.getLength());
2745 }
2746 
2747 bool CheckPrintfHandler::HandleAmount(
2748                                const analyze_format_string::OptionalAmount &Amt,
2749                                unsigned k, const char *startSpecifier,
2750                                unsigned specifierLen) {
2751 
2752   if (Amt.hasDataArgument()) {
2753     if (!HasVAListArg) {
2754       unsigned argIndex = Amt.getArgIndex();
2755       if (argIndex >= NumDataArgs) {
2756         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2757                                << k,
2758                              getLocationOfByte(Amt.getStart()),
2759                              /*IsStringLocation*/true,
2760                              getSpecifierRange(startSpecifier, specifierLen));
2761         // Don't do any more checking.  We will just emit
2762         // spurious errors.
2763         return false;
2764       }
2765 
2766       // Type check the data argument.  It should be an 'int'.
2767       // Although not in conformance with C99, we also allow the argument to be
2768       // an 'unsigned int' as that is a reasonably safe case.  GCC also
2769       // doesn't emit a warning for that case.
2770       CoveredArgs.set(argIndex);
2771       const Expr *Arg = getDataArg(argIndex);
2772       if (!Arg)
2773         return false;
2774 
2775       QualType T = Arg->getType();
2776 
2777       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2778       assert(AT.isValid());
2779 
2780       if (!AT.matchesType(S.Context, T)) {
2781         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2782                                << k << AT.getRepresentativeTypeName(S.Context)
2783                                << T << Arg->getSourceRange(),
2784                              getLocationOfByte(Amt.getStart()),
2785                              /*IsStringLocation*/true,
2786                              getSpecifierRange(startSpecifier, specifierLen));
2787         // Don't do any more checking.  We will just emit
2788         // spurious errors.
2789         return false;
2790       }
2791     }
2792   }
2793   return true;
2794 }
2795 
2796 void CheckPrintfHandler::HandleInvalidAmount(
2797                                       const analyze_printf::PrintfSpecifier &FS,
2798                                       const analyze_printf::OptionalAmount &Amt,
2799                                       unsigned type,
2800                                       const char *startSpecifier,
2801                                       unsigned specifierLen) {
2802   const analyze_printf::PrintfConversionSpecifier &CS =
2803     FS.getConversionSpecifier();
2804 
2805   FixItHint fixit =
2806     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2807       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2808                                  Amt.getConstantLength()))
2809       : FixItHint();
2810 
2811   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2812                          << type << CS.toString(),
2813                        getLocationOfByte(Amt.getStart()),
2814                        /*IsStringLocation*/true,
2815                        getSpecifierRange(startSpecifier, specifierLen),
2816                        fixit);
2817 }
2818 
2819 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2820                                     const analyze_printf::OptionalFlag &flag,
2821                                     const char *startSpecifier,
2822                                     unsigned specifierLen) {
2823   // Warn about pointless flag with a fixit removal.
2824   const analyze_printf::PrintfConversionSpecifier &CS =
2825     FS.getConversionSpecifier();
2826   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2827                          << flag.toString() << CS.toString(),
2828                        getLocationOfByte(flag.getPosition()),
2829                        /*IsStringLocation*/true,
2830                        getSpecifierRange(startSpecifier, specifierLen),
2831                        FixItHint::CreateRemoval(
2832                          getSpecifierRange(flag.getPosition(), 1)));
2833 }
2834 
2835 void CheckPrintfHandler::HandleIgnoredFlag(
2836                                 const analyze_printf::PrintfSpecifier &FS,
2837                                 const analyze_printf::OptionalFlag &ignoredFlag,
2838                                 const analyze_printf::OptionalFlag &flag,
2839                                 const char *startSpecifier,
2840                                 unsigned specifierLen) {
2841   // Warn about ignored flag with a fixit removal.
2842   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2843                          << ignoredFlag.toString() << flag.toString(),
2844                        getLocationOfByte(ignoredFlag.getPosition()),
2845                        /*IsStringLocation*/true,
2846                        getSpecifierRange(startSpecifier, specifierLen),
2847                        FixItHint::CreateRemoval(
2848                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
2849 }
2850 
2851 // Determines if the specified is a C++ class or struct containing
2852 // a member with the specified name and kind (e.g. a CXXMethodDecl named
2853 // "c_str()").
2854 template<typename MemberKind>
2855 static llvm::SmallPtrSet<MemberKind*, 1>
2856 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2857   const RecordType *RT = Ty->getAs<RecordType>();
2858   llvm::SmallPtrSet<MemberKind*, 1> Results;
2859 
2860   if (!RT)
2861     return Results;
2862   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2863   if (!RD || !RD->getDefinition())
2864     return Results;
2865 
2866   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
2867                  Sema::LookupMemberName);
2868   R.suppressDiagnostics();
2869 
2870   // We just need to include all members of the right kind turned up by the
2871   // filter, at this point.
2872   if (S.LookupQualifiedName(R, RT->getDecl()))
2873     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2874       NamedDecl *decl = (*I)->getUnderlyingDecl();
2875       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2876         Results.insert(FK);
2877     }
2878   return Results;
2879 }
2880 
2881 /// Check if we could call '.c_str()' on an object.
2882 ///
2883 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2884 /// allow the call, or if it would be ambiguous).
2885 bool Sema::hasCStrMethod(const Expr *E) {
2886   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2887   MethodSet Results =
2888       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2889   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2890        MI != ME; ++MI)
2891     if ((*MI)->getMinRequiredArguments() == 0)
2892       return true;
2893   return false;
2894 }
2895 
2896 // Check if a (w)string was passed when a (w)char* was needed, and offer a
2897 // better diagnostic if so. AT is assumed to be valid.
2898 // Returns true when a c_str() conversion method is found.
2899 bool CheckPrintfHandler::checkForCStrMembers(
2900     const analyze_printf::ArgType &AT, const Expr *E) {
2901   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2902 
2903   MethodSet Results =
2904       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2905 
2906   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2907        MI != ME; ++MI) {
2908     const CXXMethodDecl *Method = *MI;
2909     if (Method->getMinRequiredArguments() == 0 &&
2910         AT.matchesType(S.Context, Method->getReturnType())) {
2911       // FIXME: Suggest parens if the expression needs them.
2912       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
2913       S.Diag(E->getLocStart(), diag::note_printf_c_str)
2914           << "c_str()"
2915           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2916       return true;
2917     }
2918   }
2919 
2920   return false;
2921 }
2922 
2923 bool
2924 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2925                                             &FS,
2926                                           const char *startSpecifier,
2927                                           unsigned specifierLen) {
2928 
2929   using namespace analyze_format_string;
2930   using namespace analyze_printf;
2931   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2932 
2933   if (FS.consumesDataArgument()) {
2934     if (atFirstArg) {
2935         atFirstArg = false;
2936         usesPositionalArgs = FS.usesPositionalArg();
2937     }
2938     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2939       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2940                                         startSpecifier, specifierLen);
2941       return false;
2942     }
2943   }
2944 
2945   // First check if the field width, precision, and conversion specifier
2946   // have matching data arguments.
2947   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2948                     startSpecifier, specifierLen)) {
2949     return false;
2950   }
2951 
2952   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2953                     startSpecifier, specifierLen)) {
2954     return false;
2955   }
2956 
2957   if (!CS.consumesDataArgument()) {
2958     // FIXME: Technically specifying a precision or field width here
2959     // makes no sense.  Worth issuing a warning at some point.
2960     return true;
2961   }
2962 
2963   // Consume the argument.
2964   unsigned argIndex = FS.getArgIndex();
2965   if (argIndex < NumDataArgs) {
2966     // The check to see if the argIndex is valid will come later.
2967     // We set the bit here because we may exit early from this
2968     // function if we encounter some other error.
2969     CoveredArgs.set(argIndex);
2970   }
2971 
2972   // Check for using an Objective-C specific conversion specifier
2973   // in a non-ObjC literal.
2974   if (!ObjCContext && CS.isObjCArg()) {
2975     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2976                                                   specifierLen);
2977   }
2978 
2979   // Check for invalid use of field width
2980   if (!FS.hasValidFieldWidth()) {
2981     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
2982         startSpecifier, specifierLen);
2983   }
2984 
2985   // Check for invalid use of precision
2986   if (!FS.hasValidPrecision()) {
2987     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2988         startSpecifier, specifierLen);
2989   }
2990 
2991   // Check each flag does not conflict with any other component.
2992   if (!FS.hasValidThousandsGroupingPrefix())
2993     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
2994   if (!FS.hasValidLeadingZeros())
2995     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2996   if (!FS.hasValidPlusPrefix())
2997     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
2998   if (!FS.hasValidSpacePrefix())
2999     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3000   if (!FS.hasValidAlternativeForm())
3001     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3002   if (!FS.hasValidLeftJustified())
3003     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3004 
3005   // Check that flags are not ignored by another flag
3006   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3007     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3008         startSpecifier, specifierLen);
3009   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3010     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3011             startSpecifier, specifierLen);
3012 
3013   // Check the length modifier is valid with the given conversion specifier.
3014   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3015     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3016                                 diag::warn_format_nonsensical_length);
3017   else if (!FS.hasStandardLengthModifier())
3018     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3019   else if (!FS.hasStandardLengthConversionCombination())
3020     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3021                                 diag::warn_format_non_standard_conversion_spec);
3022 
3023   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3024     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3025 
3026   // The remaining checks depend on the data arguments.
3027   if (HasVAListArg)
3028     return true;
3029 
3030   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3031     return false;
3032 
3033   const Expr *Arg = getDataArg(argIndex);
3034   if (!Arg)
3035     return true;
3036 
3037   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3038 }
3039 
3040 static bool requiresParensToAddCast(const Expr *E) {
3041   // FIXME: We should have a general way to reason about operator
3042   // precedence and whether parens are actually needed here.
3043   // Take care of a few common cases where they aren't.
3044   const Expr *Inside = E->IgnoreImpCasts();
3045   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3046     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3047 
3048   switch (Inside->getStmtClass()) {
3049   case Stmt::ArraySubscriptExprClass:
3050   case Stmt::CallExprClass:
3051   case Stmt::CharacterLiteralClass:
3052   case Stmt::CXXBoolLiteralExprClass:
3053   case Stmt::DeclRefExprClass:
3054   case Stmt::FloatingLiteralClass:
3055   case Stmt::IntegerLiteralClass:
3056   case Stmt::MemberExprClass:
3057   case Stmt::ObjCArrayLiteralClass:
3058   case Stmt::ObjCBoolLiteralExprClass:
3059   case Stmt::ObjCBoxedExprClass:
3060   case Stmt::ObjCDictionaryLiteralClass:
3061   case Stmt::ObjCEncodeExprClass:
3062   case Stmt::ObjCIvarRefExprClass:
3063   case Stmt::ObjCMessageExprClass:
3064   case Stmt::ObjCPropertyRefExprClass:
3065   case Stmt::ObjCStringLiteralClass:
3066   case Stmt::ObjCSubscriptRefExprClass:
3067   case Stmt::ParenExprClass:
3068   case Stmt::StringLiteralClass:
3069   case Stmt::UnaryOperatorClass:
3070     return false;
3071   default:
3072     return true;
3073   }
3074 }
3075 
3076 bool
3077 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3078                                     const char *StartSpecifier,
3079                                     unsigned SpecifierLen,
3080                                     const Expr *E) {
3081   using namespace analyze_format_string;
3082   using namespace analyze_printf;
3083   // Now type check the data expression that matches the
3084   // format specifier.
3085   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3086                                                     ObjCContext);
3087   if (!AT.isValid())
3088     return true;
3089 
3090   QualType ExprTy = E->getType();
3091   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3092     ExprTy = TET->getUnderlyingExpr()->getType();
3093   }
3094 
3095   if (AT.matchesType(S.Context, ExprTy))
3096     return true;
3097 
3098   // Look through argument promotions for our error message's reported type.
3099   // This includes the integral and floating promotions, but excludes array
3100   // and function pointer decay; seeing that an argument intended to be a
3101   // string has type 'char [6]' is probably more confusing than 'char *'.
3102   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3103     if (ICE->getCastKind() == CK_IntegralCast ||
3104         ICE->getCastKind() == CK_FloatingCast) {
3105       E = ICE->getSubExpr();
3106       ExprTy = E->getType();
3107 
3108       // Check if we didn't match because of an implicit cast from a 'char'
3109       // or 'short' to an 'int'.  This is done because printf is a varargs
3110       // function.
3111       if (ICE->getType() == S.Context.IntTy ||
3112           ICE->getType() == S.Context.UnsignedIntTy) {
3113         // All further checking is done on the subexpression.
3114         if (AT.matchesType(S.Context, ExprTy))
3115           return true;
3116       }
3117     }
3118   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3119     // Special case for 'a', which has type 'int' in C.
3120     // Note, however, that we do /not/ want to treat multibyte constants like
3121     // 'MooV' as characters! This form is deprecated but still exists.
3122     if (ExprTy == S.Context.IntTy)
3123       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3124         ExprTy = S.Context.CharTy;
3125   }
3126 
3127   // Look through enums to their underlying type.
3128   bool IsEnum = false;
3129   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3130     ExprTy = EnumTy->getDecl()->getIntegerType();
3131     IsEnum = true;
3132   }
3133 
3134   // %C in an Objective-C context prints a unichar, not a wchar_t.
3135   // If the argument is an integer of some kind, believe the %C and suggest
3136   // a cast instead of changing the conversion specifier.
3137   QualType IntendedTy = ExprTy;
3138   if (ObjCContext &&
3139       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3140     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3141         !ExprTy->isCharType()) {
3142       // 'unichar' is defined as a typedef of unsigned short, but we should
3143       // prefer using the typedef if it is visible.
3144       IntendedTy = S.Context.UnsignedShortTy;
3145 
3146       // While we are here, check if the value is an IntegerLiteral that happens
3147       // to be within the valid range.
3148       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3149         const llvm::APInt &V = IL->getValue();
3150         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3151           return true;
3152       }
3153 
3154       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3155                           Sema::LookupOrdinaryName);
3156       if (S.LookupName(Result, S.getCurScope())) {
3157         NamedDecl *ND = Result.getFoundDecl();
3158         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3159           if (TD->getUnderlyingType() == IntendedTy)
3160             IntendedTy = S.Context.getTypedefType(TD);
3161       }
3162     }
3163   }
3164 
3165   // Special-case some of Darwin's platform-independence types by suggesting
3166   // casts to primitive types that are known to be large enough.
3167   bool ShouldNotPrintDirectly = false;
3168   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3169     // Use a 'while' to peel off layers of typedefs.
3170     QualType TyTy = IntendedTy;
3171     while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3172       StringRef Name = UserTy->getDecl()->getName();
3173       QualType CastTy = llvm::StringSwitch<QualType>(Name)
3174         .Case("NSInteger", S.Context.LongTy)
3175         .Case("NSUInteger", S.Context.UnsignedLongTy)
3176         .Case("SInt32", S.Context.IntTy)
3177         .Case("UInt32", S.Context.UnsignedIntTy)
3178         .Default(QualType());
3179 
3180       if (!CastTy.isNull()) {
3181         ShouldNotPrintDirectly = true;
3182         IntendedTy = CastTy;
3183         break;
3184       }
3185       TyTy = UserTy->desugar();
3186     }
3187   }
3188 
3189   // We may be able to offer a FixItHint if it is a supported type.
3190   PrintfSpecifier fixedFS = FS;
3191   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3192                                  S.Context, ObjCContext);
3193 
3194   if (success) {
3195     // Get the fix string from the fixed format specifier
3196     SmallString<16> buf;
3197     llvm::raw_svector_ostream os(buf);
3198     fixedFS.toString(os);
3199 
3200     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3201 
3202     if (IntendedTy == ExprTy) {
3203       // In this case, the specifier is wrong and should be changed to match
3204       // the argument.
3205       EmitFormatDiagnostic(
3206         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3207           << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
3208           << E->getSourceRange(),
3209         E->getLocStart(),
3210         /*IsStringLocation*/false,
3211         SpecRange,
3212         FixItHint::CreateReplacement(SpecRange, os.str()));
3213 
3214     } else {
3215       // The canonical type for formatting this value is different from the
3216       // actual type of the expression. (This occurs, for example, with Darwin's
3217       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3218       // should be printed as 'long' for 64-bit compatibility.)
3219       // Rather than emitting a normal format/argument mismatch, we want to
3220       // add a cast to the recommended type (and correct the format string
3221       // if necessary).
3222       SmallString<16> CastBuf;
3223       llvm::raw_svector_ostream CastFix(CastBuf);
3224       CastFix << "(";
3225       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3226       CastFix << ")";
3227 
3228       SmallVector<FixItHint,4> Hints;
3229       if (!AT.matchesType(S.Context, IntendedTy))
3230         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3231 
3232       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3233         // If there's already a cast present, just replace it.
3234         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3235         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3236 
3237       } else if (!requiresParensToAddCast(E)) {
3238         // If the expression has high enough precedence,
3239         // just write the C-style cast.
3240         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3241                                                    CastFix.str()));
3242       } else {
3243         // Otherwise, add parens around the expression as well as the cast.
3244         CastFix << "(";
3245         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3246                                                    CastFix.str()));
3247 
3248         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
3249         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3250       }
3251 
3252       if (ShouldNotPrintDirectly) {
3253         // The expression has a type that should not be printed directly.
3254         // We extract the name from the typedef because we don't want to show
3255         // the underlying type in the diagnostic.
3256         StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
3257 
3258         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3259                                << Name << IntendedTy << IsEnum
3260                                << E->getSourceRange(),
3261                              E->getLocStart(), /*IsStringLocation=*/false,
3262                              SpecRange, Hints);
3263       } else {
3264         // In this case, the expression could be printed using a different
3265         // specifier, but we've decided that the specifier is probably correct
3266         // and we should cast instead. Just use the normal warning message.
3267         EmitFormatDiagnostic(
3268           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3269             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3270             << E->getSourceRange(),
3271           E->getLocStart(), /*IsStringLocation*/false,
3272           SpecRange, Hints);
3273       }
3274     }
3275   } else {
3276     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3277                                                    SpecifierLen);
3278     // Since the warning for passing non-POD types to variadic functions
3279     // was deferred until now, we emit a warning for non-POD
3280     // arguments here.
3281     switch (S.isValidVarArgType(ExprTy)) {
3282     case Sema::VAK_Valid:
3283     case Sema::VAK_ValidInCXX11:
3284       EmitFormatDiagnostic(
3285         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3286           << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3287           << CSR
3288           << E->getSourceRange(),
3289         E->getLocStart(), /*IsStringLocation*/false, CSR);
3290       break;
3291 
3292     case Sema::VAK_Undefined:
3293       EmitFormatDiagnostic(
3294         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3295           << S.getLangOpts().CPlusPlus11
3296           << ExprTy
3297           << CallType
3298           << AT.getRepresentativeTypeName(S.Context)
3299           << CSR
3300           << E->getSourceRange(),
3301         E->getLocStart(), /*IsStringLocation*/false, CSR);
3302       checkForCStrMembers(AT, E);
3303       break;
3304 
3305     case Sema::VAK_Invalid:
3306       if (ExprTy->isObjCObjectType())
3307         EmitFormatDiagnostic(
3308           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3309             << S.getLangOpts().CPlusPlus11
3310             << ExprTy
3311             << CallType
3312             << AT.getRepresentativeTypeName(S.Context)
3313             << CSR
3314             << E->getSourceRange(),
3315           E->getLocStart(), /*IsStringLocation*/false, CSR);
3316       else
3317         // FIXME: If this is an initializer list, suggest removing the braces
3318         // or inserting a cast to the target type.
3319         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3320           << isa<InitListExpr>(E) << ExprTy << CallType
3321           << AT.getRepresentativeTypeName(S.Context)
3322           << E->getSourceRange();
3323       break;
3324     }
3325 
3326     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3327            "format string specifier index out of range");
3328     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3329   }
3330 
3331   return true;
3332 }
3333 
3334 //===--- CHECK: Scanf format string checking ------------------------------===//
3335 
3336 namespace {
3337 class CheckScanfHandler : public CheckFormatHandler {
3338 public:
3339   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3340                     const Expr *origFormatExpr, unsigned firstDataArg,
3341                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
3342                     ArrayRef<const Expr *> Args,
3343                     unsigned formatIdx, bool inFunctionCall,
3344                     Sema::VariadicCallType CallType,
3345                     llvm::SmallBitVector &CheckedVarArgs)
3346     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3347                          numDataArgs, beg, hasVAListArg,
3348                          Args, formatIdx, inFunctionCall, CallType,
3349                          CheckedVarArgs)
3350   {}
3351 
3352   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3353                             const char *startSpecifier,
3354                             unsigned specifierLen) override;
3355 
3356   bool HandleInvalidScanfConversionSpecifier(
3357           const analyze_scanf::ScanfSpecifier &FS,
3358           const char *startSpecifier,
3359           unsigned specifierLen) override;
3360 
3361   void HandleIncompleteScanList(const char *start, const char *end) override;
3362 };
3363 }
3364 
3365 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3366                                                  const char *end) {
3367   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3368                        getLocationOfByte(end), /*IsStringLocation*/true,
3369                        getSpecifierRange(start, end - start));
3370 }
3371 
3372 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3373                                         const analyze_scanf::ScanfSpecifier &FS,
3374                                         const char *startSpecifier,
3375                                         unsigned specifierLen) {
3376 
3377   const analyze_scanf::ScanfConversionSpecifier &CS =
3378     FS.getConversionSpecifier();
3379 
3380   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3381                                           getLocationOfByte(CS.getStart()),
3382                                           startSpecifier, specifierLen,
3383                                           CS.getStart(), CS.getLength());
3384 }
3385 
3386 bool CheckScanfHandler::HandleScanfSpecifier(
3387                                        const analyze_scanf::ScanfSpecifier &FS,
3388                                        const char *startSpecifier,
3389                                        unsigned specifierLen) {
3390 
3391   using namespace analyze_scanf;
3392   using namespace analyze_format_string;
3393 
3394   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3395 
3396   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3397   // be used to decide if we are using positional arguments consistently.
3398   if (FS.consumesDataArgument()) {
3399     if (atFirstArg) {
3400       atFirstArg = false;
3401       usesPositionalArgs = FS.usesPositionalArg();
3402     }
3403     else if (usesPositionalArgs != FS.usesPositionalArg()) {
3404       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3405                                         startSpecifier, specifierLen);
3406       return false;
3407     }
3408   }
3409 
3410   // Check if the field with is non-zero.
3411   const OptionalAmount &Amt = FS.getFieldWidth();
3412   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3413     if (Amt.getConstantAmount() == 0) {
3414       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3415                                                    Amt.getConstantLength());
3416       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3417                            getLocationOfByte(Amt.getStart()),
3418                            /*IsStringLocation*/true, R,
3419                            FixItHint::CreateRemoval(R));
3420     }
3421   }
3422 
3423   if (!FS.consumesDataArgument()) {
3424     // FIXME: Technically specifying a precision or field width here
3425     // makes no sense.  Worth issuing a warning at some point.
3426     return true;
3427   }
3428 
3429   // Consume the argument.
3430   unsigned argIndex = FS.getArgIndex();
3431   if (argIndex < NumDataArgs) {
3432       // The check to see if the argIndex is valid will come later.
3433       // We set the bit here because we may exit early from this
3434       // function if we encounter some other error.
3435     CoveredArgs.set(argIndex);
3436   }
3437 
3438   // Check the length modifier is valid with the given conversion specifier.
3439   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3440     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3441                                 diag::warn_format_nonsensical_length);
3442   else if (!FS.hasStandardLengthModifier())
3443     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3444   else if (!FS.hasStandardLengthConversionCombination())
3445     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3446                                 diag::warn_format_non_standard_conversion_spec);
3447 
3448   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3449     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3450 
3451   // The remaining checks depend on the data arguments.
3452   if (HasVAListArg)
3453     return true;
3454 
3455   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3456     return false;
3457 
3458   // Check that the argument type matches the format specifier.
3459   const Expr *Ex = getDataArg(argIndex);
3460   if (!Ex)
3461     return true;
3462 
3463   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3464   if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3465     ScanfSpecifier fixedFS = FS;
3466     bool success = fixedFS.fixType(Ex->getType(),
3467                                    Ex->IgnoreImpCasts()->getType(),
3468                                    S.getLangOpts(), S.Context);
3469 
3470     if (success) {
3471       // Get the fix string from the fixed format specifier.
3472       SmallString<128> buf;
3473       llvm::raw_svector_ostream os(buf);
3474       fixedFS.toString(os);
3475 
3476       EmitFormatDiagnostic(
3477         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3478           << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
3479           << Ex->getSourceRange(),
3480         Ex->getLocStart(),
3481         /*IsStringLocation*/false,
3482         getSpecifierRange(startSpecifier, specifierLen),
3483         FixItHint::CreateReplacement(
3484           getSpecifierRange(startSpecifier, specifierLen),
3485           os.str()));
3486     } else {
3487       EmitFormatDiagnostic(
3488         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3489           << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
3490           << Ex->getSourceRange(),
3491         Ex->getLocStart(),
3492         /*IsStringLocation*/false,
3493         getSpecifierRange(startSpecifier, specifierLen));
3494     }
3495   }
3496 
3497   return true;
3498 }
3499 
3500 void Sema::CheckFormatString(const StringLiteral *FExpr,
3501                              const Expr *OrigFormatExpr,
3502                              ArrayRef<const Expr *> Args,
3503                              bool HasVAListArg, unsigned format_idx,
3504                              unsigned firstDataArg, FormatStringType Type,
3505                              bool inFunctionCall, VariadicCallType CallType,
3506                              llvm::SmallBitVector &CheckedVarArgs) {
3507 
3508   // CHECK: is the format string a wide literal?
3509   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3510     CheckFormatHandler::EmitFormatDiagnostic(
3511       *this, inFunctionCall, Args[format_idx],
3512       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3513       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3514     return;
3515   }
3516 
3517   // Str - The format string.  NOTE: this is NOT null-terminated!
3518   StringRef StrRef = FExpr->getString();
3519   const char *Str = StrRef.data();
3520   // Account for cases where the string literal is truncated in a declaration.
3521   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3522   assert(T && "String literal not of constant array type!");
3523   size_t TypeSize = T->getSize().getZExtValue();
3524   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3525   const unsigned numDataArgs = Args.size() - firstDataArg;
3526 
3527   // Emit a warning if the string literal is truncated and does not contain an
3528   // embedded null character.
3529   if (TypeSize <= StrRef.size() &&
3530       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3531     CheckFormatHandler::EmitFormatDiagnostic(
3532         *this, inFunctionCall, Args[format_idx],
3533         PDiag(diag::warn_printf_format_string_not_null_terminated),
3534         FExpr->getLocStart(),
3535         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3536     return;
3537   }
3538 
3539   // CHECK: empty format string?
3540   if (StrLen == 0 && numDataArgs > 0) {
3541     CheckFormatHandler::EmitFormatDiagnostic(
3542       *this, inFunctionCall, Args[format_idx],
3543       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3544       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3545     return;
3546   }
3547 
3548   if (Type == FST_Printf || Type == FST_NSString) {
3549     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3550                          numDataArgs, (Type == FST_NSString),
3551                          Str, HasVAListArg, Args, format_idx,
3552                          inFunctionCall, CallType, CheckedVarArgs);
3553 
3554     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3555                                                   getLangOpts(),
3556                                                   Context.getTargetInfo()))
3557       H.DoneProcessing();
3558   } else if (Type == FST_Scanf) {
3559     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3560                         Str, HasVAListArg, Args, format_idx,
3561                         inFunctionCall, CallType, CheckedVarArgs);
3562 
3563     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3564                                                  getLangOpts(),
3565                                                  Context.getTargetInfo()))
3566       H.DoneProcessing();
3567   } // TODO: handle other formats
3568 }
3569 
3570 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3571 
3572 // Returns the related absolute value function that is larger, of 0 if one
3573 // does not exist.
3574 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3575   switch (AbsFunction) {
3576   default:
3577     return 0;
3578 
3579   case Builtin::BI__builtin_abs:
3580     return Builtin::BI__builtin_labs;
3581   case Builtin::BI__builtin_labs:
3582     return Builtin::BI__builtin_llabs;
3583   case Builtin::BI__builtin_llabs:
3584     return 0;
3585 
3586   case Builtin::BI__builtin_fabsf:
3587     return Builtin::BI__builtin_fabs;
3588   case Builtin::BI__builtin_fabs:
3589     return Builtin::BI__builtin_fabsl;
3590   case Builtin::BI__builtin_fabsl:
3591     return 0;
3592 
3593   case Builtin::BI__builtin_cabsf:
3594     return Builtin::BI__builtin_cabs;
3595   case Builtin::BI__builtin_cabs:
3596     return Builtin::BI__builtin_cabsl;
3597   case Builtin::BI__builtin_cabsl:
3598     return 0;
3599 
3600   case Builtin::BIabs:
3601     return Builtin::BIlabs;
3602   case Builtin::BIlabs:
3603     return Builtin::BIllabs;
3604   case Builtin::BIllabs:
3605     return 0;
3606 
3607   case Builtin::BIfabsf:
3608     return Builtin::BIfabs;
3609   case Builtin::BIfabs:
3610     return Builtin::BIfabsl;
3611   case Builtin::BIfabsl:
3612     return 0;
3613 
3614   case Builtin::BIcabsf:
3615    return Builtin::BIcabs;
3616   case Builtin::BIcabs:
3617     return Builtin::BIcabsl;
3618   case Builtin::BIcabsl:
3619     return 0;
3620   }
3621 }
3622 
3623 // Returns the argument type of the absolute value function.
3624 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3625                                              unsigned AbsType) {
3626   if (AbsType == 0)
3627     return QualType();
3628 
3629   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3630   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3631   if (Error != ASTContext::GE_None)
3632     return QualType();
3633 
3634   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3635   if (!FT)
3636     return QualType();
3637 
3638   if (FT->getNumParams() != 1)
3639     return QualType();
3640 
3641   return FT->getParamType(0);
3642 }
3643 
3644 // Returns the best absolute value function, or zero, based on type and
3645 // current absolute value function.
3646 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3647                                    unsigned AbsFunctionKind) {
3648   unsigned BestKind = 0;
3649   uint64_t ArgSize = Context.getTypeSize(ArgType);
3650   for (unsigned Kind = AbsFunctionKind; Kind != 0;
3651        Kind = getLargerAbsoluteValueFunction(Kind)) {
3652     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3653     if (Context.getTypeSize(ParamType) >= ArgSize) {
3654       if (BestKind == 0)
3655         BestKind = Kind;
3656       else if (Context.hasSameType(ParamType, ArgType)) {
3657         BestKind = Kind;
3658         break;
3659       }
3660     }
3661   }
3662   return BestKind;
3663 }
3664 
3665 enum AbsoluteValueKind {
3666   AVK_Integer,
3667   AVK_Floating,
3668   AVK_Complex
3669 };
3670 
3671 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3672   if (T->isIntegralOrEnumerationType())
3673     return AVK_Integer;
3674   if (T->isRealFloatingType())
3675     return AVK_Floating;
3676   if (T->isAnyComplexType())
3677     return AVK_Complex;
3678 
3679   llvm_unreachable("Type not integer, floating, or complex");
3680 }
3681 
3682 // Changes the absolute value function to a different type.  Preserves whether
3683 // the function is a builtin.
3684 static unsigned changeAbsFunction(unsigned AbsKind,
3685                                   AbsoluteValueKind ValueKind) {
3686   switch (ValueKind) {
3687   case AVK_Integer:
3688     switch (AbsKind) {
3689     default:
3690       return 0;
3691     case Builtin::BI__builtin_fabsf:
3692     case Builtin::BI__builtin_fabs:
3693     case Builtin::BI__builtin_fabsl:
3694     case Builtin::BI__builtin_cabsf:
3695     case Builtin::BI__builtin_cabs:
3696     case Builtin::BI__builtin_cabsl:
3697       return Builtin::BI__builtin_abs;
3698     case Builtin::BIfabsf:
3699     case Builtin::BIfabs:
3700     case Builtin::BIfabsl:
3701     case Builtin::BIcabsf:
3702     case Builtin::BIcabs:
3703     case Builtin::BIcabsl:
3704       return Builtin::BIabs;
3705     }
3706   case AVK_Floating:
3707     switch (AbsKind) {
3708     default:
3709       return 0;
3710     case Builtin::BI__builtin_abs:
3711     case Builtin::BI__builtin_labs:
3712     case Builtin::BI__builtin_llabs:
3713     case Builtin::BI__builtin_cabsf:
3714     case Builtin::BI__builtin_cabs:
3715     case Builtin::BI__builtin_cabsl:
3716       return Builtin::BI__builtin_fabsf;
3717     case Builtin::BIabs:
3718     case Builtin::BIlabs:
3719     case Builtin::BIllabs:
3720     case Builtin::BIcabsf:
3721     case Builtin::BIcabs:
3722     case Builtin::BIcabsl:
3723       return Builtin::BIfabsf;
3724     }
3725   case AVK_Complex:
3726     switch (AbsKind) {
3727     default:
3728       return 0;
3729     case Builtin::BI__builtin_abs:
3730     case Builtin::BI__builtin_labs:
3731     case Builtin::BI__builtin_llabs:
3732     case Builtin::BI__builtin_fabsf:
3733     case Builtin::BI__builtin_fabs:
3734     case Builtin::BI__builtin_fabsl:
3735       return Builtin::BI__builtin_cabsf;
3736     case Builtin::BIabs:
3737     case Builtin::BIlabs:
3738     case Builtin::BIllabs:
3739     case Builtin::BIfabsf:
3740     case Builtin::BIfabs:
3741     case Builtin::BIfabsl:
3742       return Builtin::BIcabsf;
3743     }
3744   }
3745   llvm_unreachable("Unable to convert function");
3746 }
3747 
3748 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
3749   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3750   if (!FnInfo)
3751     return 0;
3752 
3753   switch (FDecl->getBuiltinID()) {
3754   default:
3755     return 0;
3756   case Builtin::BI__builtin_abs:
3757   case Builtin::BI__builtin_fabs:
3758   case Builtin::BI__builtin_fabsf:
3759   case Builtin::BI__builtin_fabsl:
3760   case Builtin::BI__builtin_labs:
3761   case Builtin::BI__builtin_llabs:
3762   case Builtin::BI__builtin_cabs:
3763   case Builtin::BI__builtin_cabsf:
3764   case Builtin::BI__builtin_cabsl:
3765   case Builtin::BIabs:
3766   case Builtin::BIlabs:
3767   case Builtin::BIllabs:
3768   case Builtin::BIfabs:
3769   case Builtin::BIfabsf:
3770   case Builtin::BIfabsl:
3771   case Builtin::BIcabs:
3772   case Builtin::BIcabsf:
3773   case Builtin::BIcabsl:
3774     return FDecl->getBuiltinID();
3775   }
3776   llvm_unreachable("Unknown Builtin type");
3777 }
3778 
3779 // If the replacement is valid, emit a note with replacement function.
3780 // Additionally, suggest including the proper header if not already included.
3781 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3782                             unsigned AbsKind, QualType ArgType) {
3783   bool EmitHeaderHint = true;
3784   const char *HeaderName = nullptr;
3785   const char *FunctionName = nullptr;
3786   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3787     FunctionName = "std::abs";
3788     if (ArgType->isIntegralOrEnumerationType()) {
3789       HeaderName = "cstdlib";
3790     } else if (ArgType->isRealFloatingType()) {
3791       HeaderName = "cmath";
3792     } else {
3793       llvm_unreachable("Invalid Type");
3794     }
3795 
3796     // Lookup all std::abs
3797     if (NamespaceDecl *Std = S.getStdNamespace()) {
3798       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
3799       R.suppressDiagnostics();
3800       S.LookupQualifiedName(R, Std);
3801 
3802       for (const auto *I : R) {
3803         const FunctionDecl *FDecl = nullptr;
3804         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3805           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3806         } else {
3807           FDecl = dyn_cast<FunctionDecl>(I);
3808         }
3809         if (!FDecl)
3810           continue;
3811 
3812         // Found std::abs(), check that they are the right ones.
3813         if (FDecl->getNumParams() != 1)
3814           continue;
3815 
3816         // Check that the parameter type can handle the argument.
3817         QualType ParamType = FDecl->getParamDecl(0)->getType();
3818         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3819             S.Context.getTypeSize(ArgType) <=
3820                 S.Context.getTypeSize(ParamType)) {
3821           // Found a function, don't need the header hint.
3822           EmitHeaderHint = false;
3823           break;
3824         }
3825       }
3826     }
3827   } else {
3828     FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3829     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3830 
3831     if (HeaderName) {
3832       DeclarationName DN(&S.Context.Idents.get(FunctionName));
3833       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3834       R.suppressDiagnostics();
3835       S.LookupName(R, S.getCurScope());
3836 
3837       if (R.isSingleResult()) {
3838         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3839         if (FD && FD->getBuiltinID() == AbsKind) {
3840           EmitHeaderHint = false;
3841         } else {
3842           return;
3843         }
3844       } else if (!R.empty()) {
3845         return;
3846       }
3847     }
3848   }
3849 
3850   S.Diag(Loc, diag::note_replace_abs_function)
3851       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
3852 
3853   if (!HeaderName)
3854     return;
3855 
3856   if (!EmitHeaderHint)
3857     return;
3858 
3859   S.Diag(Loc, diag::note_please_include_header) << HeaderName << FunctionName;
3860 }
3861 
3862 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3863   if (!FDecl)
3864     return false;
3865 
3866   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3867     return false;
3868 
3869   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3870 
3871   while (ND && ND->isInlineNamespace()) {
3872     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
3873   }
3874 
3875   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3876     return false;
3877 
3878   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3879     return false;
3880 
3881   return true;
3882 }
3883 
3884 // Warn when using the wrong abs() function.
3885 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3886                                       const FunctionDecl *FDecl,
3887                                       IdentifierInfo *FnInfo) {
3888   if (Call->getNumArgs() != 1)
3889     return;
3890 
3891   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3892   bool IsStdAbs = IsFunctionStdAbs(FDecl);
3893   if (AbsKind == 0 && !IsStdAbs)
3894     return;
3895 
3896   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3897   QualType ParamType = Call->getArg(0)->getType();
3898 
3899   // Unsigned types can not be negative.  Suggest to drop the absolute value
3900   // function.
3901   if (ArgType->isUnsignedIntegerType()) {
3902     const char *FunctionName =
3903         IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
3904     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3905     Diag(Call->getExprLoc(), diag::note_remove_abs)
3906         << FunctionName
3907         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3908     return;
3909   }
3910 
3911   // std::abs has overloads which prevent most of the absolute value problems
3912   // from occurring.
3913   if (IsStdAbs)
3914     return;
3915 
3916   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3917   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3918 
3919   // The argument and parameter are the same kind.  Check if they are the right
3920   // size.
3921   if (ArgValueKind == ParamValueKind) {
3922     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3923       return;
3924 
3925     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3926     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3927         << FDecl << ArgType << ParamType;
3928 
3929     if (NewAbsKind == 0)
3930       return;
3931 
3932     emitReplacement(*this, Call->getExprLoc(),
3933                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
3934     return;
3935   }
3936 
3937   // ArgValueKind != ParamValueKind
3938   // The wrong type of absolute value function was used.  Attempt to find the
3939   // proper one.
3940   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3941   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3942   if (NewAbsKind == 0)
3943     return;
3944 
3945   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3946       << FDecl << ParamValueKind << ArgValueKind;
3947 
3948   emitReplacement(*this, Call->getExprLoc(),
3949                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
3950   return;
3951 }
3952 
3953 //===--- CHECK: Standard memory functions ---------------------------------===//
3954 
3955 /// \brief Takes the expression passed to the size_t parameter of functions
3956 /// such as memcmp, strncat, etc and warns if it's a comparison.
3957 ///
3958 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3959 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3960                                            IdentifierInfo *FnName,
3961                                            SourceLocation FnLoc,
3962                                            SourceLocation RParenLoc) {
3963   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3964   if (!Size)
3965     return false;
3966 
3967   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3968   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3969     return false;
3970 
3971   SourceRange SizeRange = Size->getSourceRange();
3972   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3973       << SizeRange << FnName;
3974   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
3975       << FnName << FixItHint::CreateInsertion(
3976                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
3977       << FixItHint::CreateRemoval(RParenLoc);
3978   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
3979       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3980       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
3981                                     ")");
3982 
3983   return true;
3984 }
3985 
3986 /// \brief Determine whether the given type is a dynamic class type (e.g.,
3987 /// whether it has a vtable).
3988 static bool isDynamicClassType(QualType T) {
3989   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3990     if (CXXRecordDecl *Definition = Record->getDefinition())
3991       if (Definition->isDynamicClass())
3992         return true;
3993 
3994   return false;
3995 }
3996 
3997 /// \brief If E is a sizeof expression, returns its argument expression,
3998 /// otherwise returns NULL.
3999 static const Expr *getSizeOfExprArg(const Expr* E) {
4000   if (const UnaryExprOrTypeTraitExpr *SizeOf =
4001       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4002     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4003       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
4004 
4005   return nullptr;
4006 }
4007 
4008 /// \brief If E is a sizeof expression, returns its argument type.
4009 static QualType getSizeOfArgType(const Expr* E) {
4010   if (const UnaryExprOrTypeTraitExpr *SizeOf =
4011       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4012     if (SizeOf->getKind() == clang::UETT_SizeOf)
4013       return SizeOf->getTypeOfArgument();
4014 
4015   return QualType();
4016 }
4017 
4018 /// \brief Check for dangerous or invalid arguments to memset().
4019 ///
4020 /// This issues warnings on known problematic, dangerous or unspecified
4021 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4022 /// function calls.
4023 ///
4024 /// \param Call The call expression to diagnose.
4025 void Sema::CheckMemaccessArguments(const CallExpr *Call,
4026                                    unsigned BId,
4027                                    IdentifierInfo *FnName) {
4028   assert(BId != 0);
4029 
4030   // It is possible to have a non-standard definition of memset.  Validate
4031   // we have enough arguments, and if not, abort further checking.
4032   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4033   if (Call->getNumArgs() < ExpectedNumArgs)
4034     return;
4035 
4036   unsigned LastArg = (BId == Builtin::BImemset ||
4037                       BId == Builtin::BIstrndup ? 1 : 2);
4038   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
4039   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4040 
4041   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4042                                      Call->getLocStart(), Call->getRParenLoc()))
4043     return;
4044 
4045   // We have special checking when the length is a sizeof expression.
4046   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4047   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4048   llvm::FoldingSetNodeID SizeOfArgID;
4049 
4050   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4051     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4052     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4053 
4054     QualType DestTy = Dest->getType();
4055     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4056       QualType PointeeTy = DestPtrTy->getPointeeType();
4057 
4058       // Never warn about void type pointers. This can be used to suppress
4059       // false positives.
4060       if (PointeeTy->isVoidType())
4061         continue;
4062 
4063       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4064       // actually comparing the expressions for equality. Because computing the
4065       // expression IDs can be expensive, we only do this if the diagnostic is
4066       // enabled.
4067       if (SizeOfArg &&
4068           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4069                            SizeOfArg->getExprLoc())) {
4070         // We only compute IDs for expressions if the warning is enabled, and
4071         // cache the sizeof arg's ID.
4072         if (SizeOfArgID == llvm::FoldingSetNodeID())
4073           SizeOfArg->Profile(SizeOfArgID, Context, true);
4074         llvm::FoldingSetNodeID DestID;
4075         Dest->Profile(DestID, Context, true);
4076         if (DestID == SizeOfArgID) {
4077           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4078           //       over sizeof(src) as well.
4079           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4080           StringRef ReadableName = FnName->getName();
4081 
4082           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4083             if (UnaryOp->getOpcode() == UO_AddrOf)
4084               ActionIdx = 1; // If its an address-of operator, just remove it.
4085           if (!PointeeTy->isIncompleteType() &&
4086               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4087             ActionIdx = 2; // If the pointee's size is sizeof(char),
4088                            // suggest an explicit length.
4089 
4090           // If the function is defined as a builtin macro, do not show macro
4091           // expansion.
4092           SourceLocation SL = SizeOfArg->getExprLoc();
4093           SourceRange DSR = Dest->getSourceRange();
4094           SourceRange SSR = SizeOfArg->getSourceRange();
4095           SourceManager &SM = getSourceManager();
4096 
4097           if (SM.isMacroArgExpansion(SL)) {
4098             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4099             SL = SM.getSpellingLoc(SL);
4100             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4101                              SM.getSpellingLoc(DSR.getEnd()));
4102             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4103                              SM.getSpellingLoc(SSR.getEnd()));
4104           }
4105 
4106           DiagRuntimeBehavior(SL, SizeOfArg,
4107                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4108                                 << ReadableName
4109                                 << PointeeTy
4110                                 << DestTy
4111                                 << DSR
4112                                 << SSR);
4113           DiagRuntimeBehavior(SL, SizeOfArg,
4114                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4115                                 << ActionIdx
4116                                 << SSR);
4117 
4118           break;
4119         }
4120       }
4121 
4122       // Also check for cases where the sizeof argument is the exact same
4123       // type as the memory argument, and where it points to a user-defined
4124       // record type.
4125       if (SizeOfArgTy != QualType()) {
4126         if (PointeeTy->isRecordType() &&
4127             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4128           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4129                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
4130                                 << FnName << SizeOfArgTy << ArgIdx
4131                                 << PointeeTy << Dest->getSourceRange()
4132                                 << LenExpr->getSourceRange());
4133           break;
4134         }
4135       }
4136 
4137       // Always complain about dynamic classes.
4138       if (isDynamicClassType(PointeeTy)) {
4139 
4140         unsigned OperationType = 0;
4141         // "overwritten" if we're warning about the destination for any call
4142         // but memcmp; otherwise a verb appropriate to the call.
4143         if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4144           if (BId == Builtin::BImemcpy)
4145             OperationType = 1;
4146           else if(BId == Builtin::BImemmove)
4147             OperationType = 2;
4148           else if (BId == Builtin::BImemcmp)
4149             OperationType = 3;
4150         }
4151 
4152         DiagRuntimeBehavior(
4153           Dest->getExprLoc(), Dest,
4154           PDiag(diag::warn_dyn_class_memaccess)
4155             << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4156             << FnName << PointeeTy
4157             << OperationType
4158             << Call->getCallee()->getSourceRange());
4159       } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4160                BId != Builtin::BImemset)
4161         DiagRuntimeBehavior(
4162           Dest->getExprLoc(), Dest,
4163           PDiag(diag::warn_arc_object_memaccess)
4164             << ArgIdx << FnName << PointeeTy
4165             << Call->getCallee()->getSourceRange());
4166       else
4167         continue;
4168 
4169       DiagRuntimeBehavior(
4170         Dest->getExprLoc(), Dest,
4171         PDiag(diag::note_bad_memaccess_silence)
4172           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4173       break;
4174     }
4175   }
4176 }
4177 
4178 // A little helper routine: ignore addition and subtraction of integer literals.
4179 // This intentionally does not ignore all integer constant expressions because
4180 // we don't want to remove sizeof().
4181 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4182   Ex = Ex->IgnoreParenCasts();
4183 
4184   for (;;) {
4185     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4186     if (!BO || !BO->isAdditiveOp())
4187       break;
4188 
4189     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4190     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4191 
4192     if (isa<IntegerLiteral>(RHS))
4193       Ex = LHS;
4194     else if (isa<IntegerLiteral>(LHS))
4195       Ex = RHS;
4196     else
4197       break;
4198   }
4199 
4200   return Ex;
4201 }
4202 
4203 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4204                                                       ASTContext &Context) {
4205   // Only handle constant-sized or VLAs, but not flexible members.
4206   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4207     // Only issue the FIXIT for arrays of size > 1.
4208     if (CAT->getSize().getSExtValue() <= 1)
4209       return false;
4210   } else if (!Ty->isVariableArrayType()) {
4211     return false;
4212   }
4213   return true;
4214 }
4215 
4216 // Warn if the user has made the 'size' argument to strlcpy or strlcat
4217 // be the size of the source, instead of the destination.
4218 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4219                                     IdentifierInfo *FnName) {
4220 
4221   // Don't crash if the user has the wrong number of arguments
4222   if (Call->getNumArgs() != 3)
4223     return;
4224 
4225   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4226   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4227   const Expr *CompareWithSrc = nullptr;
4228 
4229   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4230                                      Call->getLocStart(), Call->getRParenLoc()))
4231     return;
4232 
4233   // Look for 'strlcpy(dst, x, sizeof(x))'
4234   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4235     CompareWithSrc = Ex;
4236   else {
4237     // Look for 'strlcpy(dst, x, strlen(x))'
4238     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
4239       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4240           SizeCall->getNumArgs() == 1)
4241         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4242     }
4243   }
4244 
4245   if (!CompareWithSrc)
4246     return;
4247 
4248   // Determine if the argument to sizeof/strlen is equal to the source
4249   // argument.  In principle there's all kinds of things you could do
4250   // here, for instance creating an == expression and evaluating it with
4251   // EvaluateAsBooleanCondition, but this uses a more direct technique:
4252   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4253   if (!SrcArgDRE)
4254     return;
4255 
4256   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4257   if (!CompareWithSrcDRE ||
4258       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4259     return;
4260 
4261   const Expr *OriginalSizeArg = Call->getArg(2);
4262   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4263     << OriginalSizeArg->getSourceRange() << FnName;
4264 
4265   // Output a FIXIT hint if the destination is an array (rather than a
4266   // pointer to an array).  This could be enhanced to handle some
4267   // pointers if we know the actual size, like if DstArg is 'array+2'
4268   // we could say 'sizeof(array)-2'.
4269   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
4270   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
4271     return;
4272 
4273   SmallString<128> sizeString;
4274   llvm::raw_svector_ostream OS(sizeString);
4275   OS << "sizeof(";
4276   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4277   OS << ")";
4278 
4279   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4280     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4281                                     OS.str());
4282 }
4283 
4284 /// Check if two expressions refer to the same declaration.
4285 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4286   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4287     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4288       return D1->getDecl() == D2->getDecl();
4289   return false;
4290 }
4291 
4292 static const Expr *getStrlenExprArg(const Expr *E) {
4293   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4294     const FunctionDecl *FD = CE->getDirectCallee();
4295     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4296       return nullptr;
4297     return CE->getArg(0)->IgnoreParenCasts();
4298   }
4299   return nullptr;
4300 }
4301 
4302 // Warn on anti-patterns as the 'size' argument to strncat.
4303 // The correct size argument should look like following:
4304 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4305 void Sema::CheckStrncatArguments(const CallExpr *CE,
4306                                  IdentifierInfo *FnName) {
4307   // Don't crash if the user has the wrong number of arguments.
4308   if (CE->getNumArgs() < 3)
4309     return;
4310   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4311   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4312   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4313 
4314   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4315                                      CE->getRParenLoc()))
4316     return;
4317 
4318   // Identify common expressions, which are wrongly used as the size argument
4319   // to strncat and may lead to buffer overflows.
4320   unsigned PatternType = 0;
4321   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4322     // - sizeof(dst)
4323     if (referToTheSameDecl(SizeOfArg, DstArg))
4324       PatternType = 1;
4325     // - sizeof(src)
4326     else if (referToTheSameDecl(SizeOfArg, SrcArg))
4327       PatternType = 2;
4328   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4329     if (BE->getOpcode() == BO_Sub) {
4330       const Expr *L = BE->getLHS()->IgnoreParenCasts();
4331       const Expr *R = BE->getRHS()->IgnoreParenCasts();
4332       // - sizeof(dst) - strlen(dst)
4333       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4334           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4335         PatternType = 1;
4336       // - sizeof(src) - (anything)
4337       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4338         PatternType = 2;
4339     }
4340   }
4341 
4342   if (PatternType == 0)
4343     return;
4344 
4345   // Generate the diagnostic.
4346   SourceLocation SL = LenArg->getLocStart();
4347   SourceRange SR = LenArg->getSourceRange();
4348   SourceManager &SM = getSourceManager();
4349 
4350   // If the function is defined as a builtin macro, do not show macro expansion.
4351   if (SM.isMacroArgExpansion(SL)) {
4352     SL = SM.getSpellingLoc(SL);
4353     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4354                      SM.getSpellingLoc(SR.getEnd()));
4355   }
4356 
4357   // Check if the destination is an array (rather than a pointer to an array).
4358   QualType DstTy = DstArg->getType();
4359   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4360                                                                     Context);
4361   if (!isKnownSizeArray) {
4362     if (PatternType == 1)
4363       Diag(SL, diag::warn_strncat_wrong_size) << SR;
4364     else
4365       Diag(SL, diag::warn_strncat_src_size) << SR;
4366     return;
4367   }
4368 
4369   if (PatternType == 1)
4370     Diag(SL, diag::warn_strncat_large_size) << SR;
4371   else
4372     Diag(SL, diag::warn_strncat_src_size) << SR;
4373 
4374   SmallString<128> sizeString;
4375   llvm::raw_svector_ostream OS(sizeString);
4376   OS << "sizeof(";
4377   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4378   OS << ") - ";
4379   OS << "strlen(";
4380   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4381   OS << ") - 1";
4382 
4383   Diag(SL, diag::note_strncat_wrong_size)
4384     << FixItHint::CreateReplacement(SR, OS.str());
4385 }
4386 
4387 //===--- CHECK: Return Address of Stack Variable --------------------------===//
4388 
4389 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4390                      Decl *ParentDecl);
4391 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4392                       Decl *ParentDecl);
4393 
4394 /// CheckReturnStackAddr - Check if a return statement returns the address
4395 ///   of a stack variable.
4396 static void
4397 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4398                      SourceLocation ReturnLoc) {
4399 
4400   Expr *stackE = nullptr;
4401   SmallVector<DeclRefExpr *, 8> refVars;
4402 
4403   // Perform checking for returned stack addresses, local blocks,
4404   // label addresses or references to temporaries.
4405   if (lhsType->isPointerType() ||
4406       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4407     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
4408   } else if (lhsType->isReferenceType()) {
4409     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
4410   }
4411 
4412   if (!stackE)
4413     return; // Nothing suspicious was found.
4414 
4415   SourceLocation diagLoc;
4416   SourceRange diagRange;
4417   if (refVars.empty()) {
4418     diagLoc = stackE->getLocStart();
4419     diagRange = stackE->getSourceRange();
4420   } else {
4421     // We followed through a reference variable. 'stackE' contains the
4422     // problematic expression but we will warn at the return statement pointing
4423     // at the reference variable. We will later display the "trail" of
4424     // reference variables using notes.
4425     diagLoc = refVars[0]->getLocStart();
4426     diagRange = refVars[0]->getSourceRange();
4427   }
4428 
4429   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4430     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4431                                              : diag::warn_ret_stack_addr)
4432      << DR->getDecl()->getDeclName() << diagRange;
4433   } else if (isa<BlockExpr>(stackE)) { // local block.
4434     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4435   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4436     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4437   } else { // local temporary.
4438     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4439                                                : diag::warn_ret_local_temp_addr)
4440      << diagRange;
4441   }
4442 
4443   // Display the "trail" of reference variables that we followed until we
4444   // found the problematic expression using notes.
4445   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4446     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4447     // If this var binds to another reference var, show the range of the next
4448     // var, otherwise the var binds to the problematic expression, in which case
4449     // show the range of the expression.
4450     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4451                                   : stackE->getSourceRange();
4452     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4453         << VD->getDeclName() << range;
4454   }
4455 }
4456 
4457 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4458 ///  check if the expression in a return statement evaluates to an address
4459 ///  to a location on the stack, a local block, an address of a label, or a
4460 ///  reference to local temporary. The recursion is used to traverse the
4461 ///  AST of the return expression, with recursion backtracking when we
4462 ///  encounter a subexpression that (1) clearly does not lead to one of the
4463 ///  above problematic expressions (2) is something we cannot determine leads to
4464 ///  a problematic expression based on such local checking.
4465 ///
4466 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
4467 ///  the expression that they point to. Such variables are added to the
4468 ///  'refVars' vector so that we know what the reference variable "trail" was.
4469 ///
4470 ///  EvalAddr processes expressions that are pointers that are used as
4471 ///  references (and not L-values).  EvalVal handles all other values.
4472 ///  At the base case of the recursion is a check for the above problematic
4473 ///  expressions.
4474 ///
4475 ///  This implementation handles:
4476 ///
4477 ///   * pointer-to-pointer casts
4478 ///   * implicit conversions from array references to pointers
4479 ///   * taking the address of fields
4480 ///   * arbitrary interplay between "&" and "*" operators
4481 ///   * pointer arithmetic from an address of a stack variable
4482 ///   * taking the address of an array element where the array is on the stack
4483 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4484                       Decl *ParentDecl) {
4485   if (E->isTypeDependent())
4486     return nullptr;
4487 
4488   // We should only be called for evaluating pointer expressions.
4489   assert((E->getType()->isAnyPointerType() ||
4490           E->getType()->isBlockPointerType() ||
4491           E->getType()->isObjCQualifiedIdType()) &&
4492          "EvalAddr only works on pointers");
4493 
4494   E = E->IgnoreParens();
4495 
4496   // Our "symbolic interpreter" is just a dispatch off the currently
4497   // viewed AST node.  We then recursively traverse the AST by calling
4498   // EvalAddr and EvalVal appropriately.
4499   switch (E->getStmtClass()) {
4500   case Stmt::DeclRefExprClass: {
4501     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4502 
4503     // If we leave the immediate function, the lifetime isn't about to end.
4504     if (DR->refersToEnclosingLocal())
4505       return nullptr;
4506 
4507     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4508       // If this is a reference variable, follow through to the expression that
4509       // it points to.
4510       if (V->hasLocalStorage() &&
4511           V->getType()->isReferenceType() && V->hasInit()) {
4512         // Add the reference variable to the "trail".
4513         refVars.push_back(DR);
4514         return EvalAddr(V->getInit(), refVars, ParentDecl);
4515       }
4516 
4517     return nullptr;
4518   }
4519 
4520   case Stmt::UnaryOperatorClass: {
4521     // The only unary operator that make sense to handle here
4522     // is AddrOf.  All others don't make sense as pointers.
4523     UnaryOperator *U = cast<UnaryOperator>(E);
4524 
4525     if (U->getOpcode() == UO_AddrOf)
4526       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
4527     else
4528       return nullptr;
4529   }
4530 
4531   case Stmt::BinaryOperatorClass: {
4532     // Handle pointer arithmetic.  All other binary operators are not valid
4533     // in this context.
4534     BinaryOperator *B = cast<BinaryOperator>(E);
4535     BinaryOperatorKind op = B->getOpcode();
4536 
4537     if (op != BO_Add && op != BO_Sub)
4538       return nullptr;
4539 
4540     Expr *Base = B->getLHS();
4541 
4542     // Determine which argument is the real pointer base.  It could be
4543     // the RHS argument instead of the LHS.
4544     if (!Base->getType()->isPointerType()) Base = B->getRHS();
4545 
4546     assert (Base->getType()->isPointerType());
4547     return EvalAddr(Base, refVars, ParentDecl);
4548   }
4549 
4550   // For conditional operators we need to see if either the LHS or RHS are
4551   // valid DeclRefExpr*s.  If one of them is valid, we return it.
4552   case Stmt::ConditionalOperatorClass: {
4553     ConditionalOperator *C = cast<ConditionalOperator>(E);
4554 
4555     // Handle the GNU extension for missing LHS.
4556     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4557     if (Expr *LHSExpr = C->getLHS()) {
4558       // In C++, we can have a throw-expression, which has 'void' type.
4559       if (!LHSExpr->getType()->isVoidType())
4560         if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
4561           return LHS;
4562     }
4563 
4564     // In C++, we can have a throw-expression, which has 'void' type.
4565     if (C->getRHS()->getType()->isVoidType())
4566       return nullptr;
4567 
4568     return EvalAddr(C->getRHS(), refVars, ParentDecl);
4569   }
4570 
4571   case Stmt::BlockExprClass:
4572     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
4573       return E; // local block.
4574     return nullptr;
4575 
4576   case Stmt::AddrLabelExprClass:
4577     return E; // address of label.
4578 
4579   case Stmt::ExprWithCleanupsClass:
4580     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4581                     ParentDecl);
4582 
4583   // For casts, we need to handle conversions from arrays to
4584   // pointer values, and pointer-to-pointer conversions.
4585   case Stmt::ImplicitCastExprClass:
4586   case Stmt::CStyleCastExprClass:
4587   case Stmt::CXXFunctionalCastExprClass:
4588   case Stmt::ObjCBridgedCastExprClass:
4589   case Stmt::CXXStaticCastExprClass:
4590   case Stmt::CXXDynamicCastExprClass:
4591   case Stmt::CXXConstCastExprClass:
4592   case Stmt::CXXReinterpretCastExprClass: {
4593     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4594     switch (cast<CastExpr>(E)->getCastKind()) {
4595     case CK_BitCast:
4596     case CK_LValueToRValue:
4597     case CK_NoOp:
4598     case CK_BaseToDerived:
4599     case CK_DerivedToBase:
4600     case CK_UncheckedDerivedToBase:
4601     case CK_Dynamic:
4602     case CK_CPointerToObjCPointerCast:
4603     case CK_BlockPointerToObjCPointerCast:
4604     case CK_AnyPointerToBlockPointerCast:
4605       return EvalAddr(SubExpr, refVars, ParentDecl);
4606 
4607     case CK_ArrayToPointerDecay:
4608       return EvalVal(SubExpr, refVars, ParentDecl);
4609 
4610     default:
4611       return nullptr;
4612     }
4613   }
4614 
4615   case Stmt::MaterializeTemporaryExprClass:
4616     if (Expr *Result = EvalAddr(
4617                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4618                                 refVars, ParentDecl))
4619       return Result;
4620 
4621     return E;
4622 
4623   // Everything else: we simply don't reason about them.
4624   default:
4625     return nullptr;
4626   }
4627 }
4628 
4629 
4630 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
4631 ///   See the comments for EvalAddr for more details.
4632 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4633                      Decl *ParentDecl) {
4634 do {
4635   // We should only be called for evaluating non-pointer expressions, or
4636   // expressions with a pointer type that are not used as references but instead
4637   // are l-values (e.g., DeclRefExpr with a pointer type).
4638 
4639   // Our "symbolic interpreter" is just a dispatch off the currently
4640   // viewed AST node.  We then recursively traverse the AST by calling
4641   // EvalAddr and EvalVal appropriately.
4642 
4643   E = E->IgnoreParens();
4644   switch (E->getStmtClass()) {
4645   case Stmt::ImplicitCastExprClass: {
4646     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
4647     if (IE->getValueKind() == VK_LValue) {
4648       E = IE->getSubExpr();
4649       continue;
4650     }
4651     return nullptr;
4652   }
4653 
4654   case Stmt::ExprWithCleanupsClass:
4655     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
4656 
4657   case Stmt::DeclRefExprClass: {
4658     // When we hit a DeclRefExpr we are looking at code that refers to a
4659     // variable's name. If it's not a reference variable we check if it has
4660     // local storage within the function, and if so, return the expression.
4661     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4662 
4663     // If we leave the immediate function, the lifetime isn't about to end.
4664     if (DR->refersToEnclosingLocal())
4665       return nullptr;
4666 
4667     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4668       // Check if it refers to itself, e.g. "int& i = i;".
4669       if (V == ParentDecl)
4670         return DR;
4671 
4672       if (V->hasLocalStorage()) {
4673         if (!V->getType()->isReferenceType())
4674           return DR;
4675 
4676         // Reference variable, follow through to the expression that
4677         // it points to.
4678         if (V->hasInit()) {
4679           // Add the reference variable to the "trail".
4680           refVars.push_back(DR);
4681           return EvalVal(V->getInit(), refVars, V);
4682         }
4683       }
4684     }
4685 
4686     return nullptr;
4687   }
4688 
4689   case Stmt::UnaryOperatorClass: {
4690     // The only unary operator that make sense to handle here
4691     // is Deref.  All others don't resolve to a "name."  This includes
4692     // handling all sorts of rvalues passed to a unary operator.
4693     UnaryOperator *U = cast<UnaryOperator>(E);
4694 
4695     if (U->getOpcode() == UO_Deref)
4696       return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
4697 
4698     return nullptr;
4699   }
4700 
4701   case Stmt::ArraySubscriptExprClass: {
4702     // Array subscripts are potential references to data on the stack.  We
4703     // retrieve the DeclRefExpr* for the array variable if it indeed
4704     // has local storage.
4705     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
4706   }
4707 
4708   case Stmt::ConditionalOperatorClass: {
4709     // For conditional operators we need to see if either the LHS or RHS are
4710     // non-NULL Expr's.  If one is non-NULL, we return it.
4711     ConditionalOperator *C = cast<ConditionalOperator>(E);
4712 
4713     // Handle the GNU extension for missing LHS.
4714     if (Expr *LHSExpr = C->getLHS()) {
4715       // In C++, we can have a throw-expression, which has 'void' type.
4716       if (!LHSExpr->getType()->isVoidType())
4717         if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4718           return LHS;
4719     }
4720 
4721     // In C++, we can have a throw-expression, which has 'void' type.
4722     if (C->getRHS()->getType()->isVoidType())
4723       return nullptr;
4724 
4725     return EvalVal(C->getRHS(), refVars, ParentDecl);
4726   }
4727 
4728   // Accesses to members are potential references to data on the stack.
4729   case Stmt::MemberExprClass: {
4730     MemberExpr *M = cast<MemberExpr>(E);
4731 
4732     // Check for indirect access.  We only want direct field accesses.
4733     if (M->isArrow())
4734       return nullptr;
4735 
4736     // Check whether the member type is itself a reference, in which case
4737     // we're not going to refer to the member, but to what the member refers to.
4738     if (M->getMemberDecl()->getType()->isReferenceType())
4739       return nullptr;
4740 
4741     return EvalVal(M->getBase(), refVars, ParentDecl);
4742   }
4743 
4744   case Stmt::MaterializeTemporaryExprClass:
4745     if (Expr *Result = EvalVal(
4746                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4747                                refVars, ParentDecl))
4748       return Result;
4749 
4750     return E;
4751 
4752   default:
4753     // Check that we don't return or take the address of a reference to a
4754     // temporary. This is only useful in C++.
4755     if (!E->isTypeDependent() && E->isRValue())
4756       return E;
4757 
4758     // Everything else: we simply don't reason about them.
4759     return nullptr;
4760   }
4761 } while (true);
4762 }
4763 
4764 void
4765 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4766                          SourceLocation ReturnLoc,
4767                          bool isObjCMethod,
4768                          const AttrVec *Attrs,
4769                          const FunctionDecl *FD) {
4770   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4771 
4772   // Check if the return value is null but should not be.
4773   if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4774       CheckNonNullExpr(*this, RetValExp))
4775     Diag(ReturnLoc, diag::warn_null_ret)
4776       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4777 
4778   // C++11 [basic.stc.dynamic.allocation]p4:
4779   //   If an allocation function declared with a non-throwing
4780   //   exception-specification fails to allocate storage, it shall return
4781   //   a null pointer. Any other allocation function that fails to allocate
4782   //   storage shall indicate failure only by throwing an exception [...]
4783   if (FD) {
4784     OverloadedOperatorKind Op = FD->getOverloadedOperator();
4785     if (Op == OO_New || Op == OO_Array_New) {
4786       const FunctionProtoType *Proto
4787         = FD->getType()->castAs<FunctionProtoType>();
4788       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4789           CheckNonNullExpr(*this, RetValExp))
4790         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4791           << FD << getLangOpts().CPlusPlus11;
4792     }
4793   }
4794 }
4795 
4796 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4797 
4798 /// Check for comparisons of floating point operands using != and ==.
4799 /// Issue a warning if these are no self-comparisons, as they are not likely
4800 /// to do what the programmer intended.
4801 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
4802   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4803   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
4804 
4805   // Special case: check for x == x (which is OK).
4806   // Do not emit warnings for such cases.
4807   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4808     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4809       if (DRL->getDecl() == DRR->getDecl())
4810         return;
4811 
4812 
4813   // Special case: check for comparisons against literals that can be exactly
4814   //  represented by APFloat.  In such cases, do not emit a warning.  This
4815   //  is a heuristic: often comparison against such literals are used to
4816   //  detect if a value in a variable has not changed.  This clearly can
4817   //  lead to false negatives.
4818   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4819     if (FLL->isExact())
4820       return;
4821   } else
4822     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4823       if (FLR->isExact())
4824         return;
4825 
4826   // Check for comparisons with builtin types.
4827   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4828     if (CL->getBuiltinCallee())
4829       return;
4830 
4831   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4832     if (CR->getBuiltinCallee())
4833       return;
4834 
4835   // Emit the diagnostic.
4836   Diag(Loc, diag::warn_floatingpoint_eq)
4837     << LHS->getSourceRange() << RHS->getSourceRange();
4838 }
4839 
4840 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4841 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4842 
4843 namespace {
4844 
4845 /// Structure recording the 'active' range of an integer-valued
4846 /// expression.
4847 struct IntRange {
4848   /// The number of bits active in the int.
4849   unsigned Width;
4850 
4851   /// True if the int is known not to have negative values.
4852   bool NonNegative;
4853 
4854   IntRange(unsigned Width, bool NonNegative)
4855     : Width(Width), NonNegative(NonNegative)
4856   {}
4857 
4858   /// Returns the range of the bool type.
4859   static IntRange forBoolType() {
4860     return IntRange(1, true);
4861   }
4862 
4863   /// Returns the range of an opaque value of the given integral type.
4864   static IntRange forValueOfType(ASTContext &C, QualType T) {
4865     return forValueOfCanonicalType(C,
4866                           T->getCanonicalTypeInternal().getTypePtr());
4867   }
4868 
4869   /// Returns the range of an opaque value of a canonical integral type.
4870   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4871     assert(T->isCanonicalUnqualified());
4872 
4873     if (const VectorType *VT = dyn_cast<VectorType>(T))
4874       T = VT->getElementType().getTypePtr();
4875     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4876       T = CT->getElementType().getTypePtr();
4877 
4878     // For enum types, use the known bit width of the enumerators.
4879     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4880       EnumDecl *Enum = ET->getDecl();
4881       if (!Enum->isCompleteDefinition())
4882         return IntRange(C.getIntWidth(QualType(T, 0)), false);
4883 
4884       unsigned NumPositive = Enum->getNumPositiveBits();
4885       unsigned NumNegative = Enum->getNumNegativeBits();
4886 
4887       if (NumNegative == 0)
4888         return IntRange(NumPositive, true/*NonNegative*/);
4889       else
4890         return IntRange(std::max(NumPositive + 1, NumNegative),
4891                         false/*NonNegative*/);
4892     }
4893 
4894     const BuiltinType *BT = cast<BuiltinType>(T);
4895     assert(BT->isInteger());
4896 
4897     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4898   }
4899 
4900   /// Returns the "target" range of a canonical integral type, i.e.
4901   /// the range of values expressible in the type.
4902   ///
4903   /// This matches forValueOfCanonicalType except that enums have the
4904   /// full range of their type, not the range of their enumerators.
4905   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4906     assert(T->isCanonicalUnqualified());
4907 
4908     if (const VectorType *VT = dyn_cast<VectorType>(T))
4909       T = VT->getElementType().getTypePtr();
4910     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4911       T = CT->getElementType().getTypePtr();
4912     if (const EnumType *ET = dyn_cast<EnumType>(T))
4913       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4914 
4915     const BuiltinType *BT = cast<BuiltinType>(T);
4916     assert(BT->isInteger());
4917 
4918     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4919   }
4920 
4921   /// Returns the supremum of two ranges: i.e. their conservative merge.
4922   static IntRange join(IntRange L, IntRange R) {
4923     return IntRange(std::max(L.Width, R.Width),
4924                     L.NonNegative && R.NonNegative);
4925   }
4926 
4927   /// Returns the infinum of two ranges: i.e. their aggressive merge.
4928   static IntRange meet(IntRange L, IntRange R) {
4929     return IntRange(std::min(L.Width, R.Width),
4930                     L.NonNegative || R.NonNegative);
4931   }
4932 };
4933 
4934 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4935                               unsigned MaxWidth) {
4936   if (value.isSigned() && value.isNegative())
4937     return IntRange(value.getMinSignedBits(), false);
4938 
4939   if (value.getBitWidth() > MaxWidth)
4940     value = value.trunc(MaxWidth);
4941 
4942   // isNonNegative() just checks the sign bit without considering
4943   // signedness.
4944   return IntRange(value.getActiveBits(), true);
4945 }
4946 
4947 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4948                               unsigned MaxWidth) {
4949   if (result.isInt())
4950     return GetValueRange(C, result.getInt(), MaxWidth);
4951 
4952   if (result.isVector()) {
4953     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4954     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4955       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4956       R = IntRange::join(R, El);
4957     }
4958     return R;
4959   }
4960 
4961   if (result.isComplexInt()) {
4962     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4963     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4964     return IntRange::join(R, I);
4965   }
4966 
4967   // This can happen with lossless casts to intptr_t of "based" lvalues.
4968   // Assume it might use arbitrary bits.
4969   // FIXME: The only reason we need to pass the type in here is to get
4970   // the sign right on this one case.  It would be nice if APValue
4971   // preserved this.
4972   assert(result.isLValue() || result.isAddrLabelDiff());
4973   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4974 }
4975 
4976 static QualType GetExprType(Expr *E) {
4977   QualType Ty = E->getType();
4978   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4979     Ty = AtomicRHS->getValueType();
4980   return Ty;
4981 }
4982 
4983 /// Pseudo-evaluate the given integer expression, estimating the
4984 /// range of values it might take.
4985 ///
4986 /// \param MaxWidth - the width to which the value will be truncated
4987 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4988   E = E->IgnoreParens();
4989 
4990   // Try a full evaluation first.
4991   Expr::EvalResult result;
4992   if (E->EvaluateAsRValue(result, C))
4993     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
4994 
4995   // I think we only want to look through implicit casts here; if the
4996   // user has an explicit widening cast, we should treat the value as
4997   // being of the new, wider type.
4998   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4999     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
5000       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5001 
5002     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
5003 
5004     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
5005 
5006     // Assume that non-integer casts can span the full range of the type.
5007     if (!isIntegerCast)
5008       return OutputTypeRange;
5009 
5010     IntRange SubRange
5011       = GetExprRange(C, CE->getSubExpr(),
5012                      std::min(MaxWidth, OutputTypeRange.Width));
5013 
5014     // Bail out if the subexpr's range is as wide as the cast type.
5015     if (SubRange.Width >= OutputTypeRange.Width)
5016       return OutputTypeRange;
5017 
5018     // Otherwise, we take the smaller width, and we're non-negative if
5019     // either the output type or the subexpr is.
5020     return IntRange(SubRange.Width,
5021                     SubRange.NonNegative || OutputTypeRange.NonNegative);
5022   }
5023 
5024   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5025     // If we can fold the condition, just take that operand.
5026     bool CondResult;
5027     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5028       return GetExprRange(C, CondResult ? CO->getTrueExpr()
5029                                         : CO->getFalseExpr(),
5030                           MaxWidth);
5031 
5032     // Otherwise, conservatively merge.
5033     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5034     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5035     return IntRange::join(L, R);
5036   }
5037 
5038   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5039     switch (BO->getOpcode()) {
5040 
5041     // Boolean-valued operations are single-bit and positive.
5042     case BO_LAnd:
5043     case BO_LOr:
5044     case BO_LT:
5045     case BO_GT:
5046     case BO_LE:
5047     case BO_GE:
5048     case BO_EQ:
5049     case BO_NE:
5050       return IntRange::forBoolType();
5051 
5052     // The type of the assignments is the type of the LHS, so the RHS
5053     // is not necessarily the same type.
5054     case BO_MulAssign:
5055     case BO_DivAssign:
5056     case BO_RemAssign:
5057     case BO_AddAssign:
5058     case BO_SubAssign:
5059     case BO_XorAssign:
5060     case BO_OrAssign:
5061       // TODO: bitfields?
5062       return IntRange::forValueOfType(C, GetExprType(E));
5063 
5064     // Simple assignments just pass through the RHS, which will have
5065     // been coerced to the LHS type.
5066     case BO_Assign:
5067       // TODO: bitfields?
5068       return GetExprRange(C, BO->getRHS(), MaxWidth);
5069 
5070     // Operations with opaque sources are black-listed.
5071     case BO_PtrMemD:
5072     case BO_PtrMemI:
5073       return IntRange::forValueOfType(C, GetExprType(E));
5074 
5075     // Bitwise-and uses the *infinum* of the two source ranges.
5076     case BO_And:
5077     case BO_AndAssign:
5078       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5079                             GetExprRange(C, BO->getRHS(), MaxWidth));
5080 
5081     // Left shift gets black-listed based on a judgement call.
5082     case BO_Shl:
5083       // ...except that we want to treat '1 << (blah)' as logically
5084       // positive.  It's an important idiom.
5085       if (IntegerLiteral *I
5086             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5087         if (I->getValue() == 1) {
5088           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5089           return IntRange(R.Width, /*NonNegative*/ true);
5090         }
5091       }
5092       // fallthrough
5093 
5094     case BO_ShlAssign:
5095       return IntRange::forValueOfType(C, GetExprType(E));
5096 
5097     // Right shift by a constant can narrow its left argument.
5098     case BO_Shr:
5099     case BO_ShrAssign: {
5100       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5101 
5102       // If the shift amount is a positive constant, drop the width by
5103       // that much.
5104       llvm::APSInt shift;
5105       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5106           shift.isNonNegative()) {
5107         unsigned zext = shift.getZExtValue();
5108         if (zext >= L.Width)
5109           L.Width = (L.NonNegative ? 0 : 1);
5110         else
5111           L.Width -= zext;
5112       }
5113 
5114       return L;
5115     }
5116 
5117     // Comma acts as its right operand.
5118     case BO_Comma:
5119       return GetExprRange(C, BO->getRHS(), MaxWidth);
5120 
5121     // Black-list pointer subtractions.
5122     case BO_Sub:
5123       if (BO->getLHS()->getType()->isPointerType())
5124         return IntRange::forValueOfType(C, GetExprType(E));
5125       break;
5126 
5127     // The width of a division result is mostly determined by the size
5128     // of the LHS.
5129     case BO_Div: {
5130       // Don't 'pre-truncate' the operands.
5131       unsigned opWidth = C.getIntWidth(GetExprType(E));
5132       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5133 
5134       // If the divisor is constant, use that.
5135       llvm::APSInt divisor;
5136       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5137         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5138         if (log2 >= L.Width)
5139           L.Width = (L.NonNegative ? 0 : 1);
5140         else
5141           L.Width = std::min(L.Width - log2, MaxWidth);
5142         return L;
5143       }
5144 
5145       // Otherwise, just use the LHS's width.
5146       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5147       return IntRange(L.Width, L.NonNegative && R.NonNegative);
5148     }
5149 
5150     // The result of a remainder can't be larger than the result of
5151     // either side.
5152     case BO_Rem: {
5153       // Don't 'pre-truncate' the operands.
5154       unsigned opWidth = C.getIntWidth(GetExprType(E));
5155       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5156       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5157 
5158       IntRange meet = IntRange::meet(L, R);
5159       meet.Width = std::min(meet.Width, MaxWidth);
5160       return meet;
5161     }
5162 
5163     // The default behavior is okay for these.
5164     case BO_Mul:
5165     case BO_Add:
5166     case BO_Xor:
5167     case BO_Or:
5168       break;
5169     }
5170 
5171     // The default case is to treat the operation as if it were closed
5172     // on the narrowest type that encompasses both operands.
5173     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5174     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5175     return IntRange::join(L, R);
5176   }
5177 
5178   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5179     switch (UO->getOpcode()) {
5180     // Boolean-valued operations are white-listed.
5181     case UO_LNot:
5182       return IntRange::forBoolType();
5183 
5184     // Operations with opaque sources are black-listed.
5185     case UO_Deref:
5186     case UO_AddrOf: // should be impossible
5187       return IntRange::forValueOfType(C, GetExprType(E));
5188 
5189     default:
5190       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5191     }
5192   }
5193 
5194   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5195     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5196 
5197   if (FieldDecl *BitField = E->getSourceBitField())
5198     return IntRange(BitField->getBitWidthValue(C),
5199                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
5200 
5201   return IntRange::forValueOfType(C, GetExprType(E));
5202 }
5203 
5204 static IntRange GetExprRange(ASTContext &C, Expr *E) {
5205   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5206 }
5207 
5208 /// Checks whether the given value, which currently has the given
5209 /// source semantics, has the same value when coerced through the
5210 /// target semantics.
5211 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5212                                  const llvm::fltSemantics &Src,
5213                                  const llvm::fltSemantics &Tgt) {
5214   llvm::APFloat truncated = value;
5215 
5216   bool ignored;
5217   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5218   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5219 
5220   return truncated.bitwiseIsEqual(value);
5221 }
5222 
5223 /// Checks whether the given value, which currently has the given
5224 /// source semantics, has the same value when coerced through the
5225 /// target semantics.
5226 ///
5227 /// The value might be a vector of floats (or a complex number).
5228 static bool IsSameFloatAfterCast(const APValue &value,
5229                                  const llvm::fltSemantics &Src,
5230                                  const llvm::fltSemantics &Tgt) {
5231   if (value.isFloat())
5232     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5233 
5234   if (value.isVector()) {
5235     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5236       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5237         return false;
5238     return true;
5239   }
5240 
5241   assert(value.isComplexFloat());
5242   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5243           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5244 }
5245 
5246 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
5247 
5248 static bool IsZero(Sema &S, Expr *E) {
5249   // Suppress cases where we are comparing against an enum constant.
5250   if (const DeclRefExpr *DR =
5251       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5252     if (isa<EnumConstantDecl>(DR->getDecl()))
5253       return false;
5254 
5255   // Suppress cases where the '0' value is expanded from a macro.
5256   if (E->getLocStart().isMacroID())
5257     return false;
5258 
5259   llvm::APSInt Value;
5260   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5261 }
5262 
5263 static bool HasEnumType(Expr *E) {
5264   // Strip off implicit integral promotions.
5265   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5266     if (ICE->getCastKind() != CK_IntegralCast &&
5267         ICE->getCastKind() != CK_NoOp)
5268       break;
5269     E = ICE->getSubExpr();
5270   }
5271 
5272   return E->getType()->isEnumeralType();
5273 }
5274 
5275 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
5276   // Disable warning in template instantiations.
5277   if (!S.ActiveTemplateInstantiations.empty())
5278     return;
5279 
5280   BinaryOperatorKind op = E->getOpcode();
5281   if (E->isValueDependent())
5282     return;
5283 
5284   if (op == BO_LT && IsZero(S, E->getRHS())) {
5285     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5286       << "< 0" << "false" << HasEnumType(E->getLHS())
5287       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5288   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
5289     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5290       << ">= 0" << "true" << HasEnumType(E->getLHS())
5291       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5292   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
5293     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5294       << "0 >" << "false" << HasEnumType(E->getRHS())
5295       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5296   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
5297     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5298       << "0 <=" << "true" << HasEnumType(E->getRHS())
5299       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5300   }
5301 }
5302 
5303 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
5304                                          Expr *Constant, Expr *Other,
5305                                          llvm::APSInt Value,
5306                                          bool RhsConstant) {
5307   // Disable warning in template instantiations.
5308   if (!S.ActiveTemplateInstantiations.empty())
5309     return;
5310 
5311   // TODO: Investigate using GetExprRange() to get tighter bounds
5312   // on the bit ranges.
5313   QualType OtherT = Other->getType();
5314   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5315   unsigned OtherWidth = OtherRange.Width;
5316 
5317   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5318 
5319   // 0 values are handled later by CheckTrivialUnsignedComparison().
5320   if ((Value == 0) && (!OtherIsBooleanType))
5321     return;
5322 
5323   BinaryOperatorKind op = E->getOpcode();
5324   bool IsTrue = true;
5325 
5326   // Used for diagnostic printout.
5327   enum {
5328     LiteralConstant = 0,
5329     CXXBoolLiteralTrue,
5330     CXXBoolLiteralFalse
5331   } LiteralOrBoolConstant = LiteralConstant;
5332 
5333   if (!OtherIsBooleanType) {
5334     QualType ConstantT = Constant->getType();
5335     QualType CommonT = E->getLHS()->getType();
5336 
5337     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5338       return;
5339     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5340            "comparison with non-integer type");
5341 
5342     bool ConstantSigned = ConstantT->isSignedIntegerType();
5343     bool CommonSigned = CommonT->isSignedIntegerType();
5344 
5345     bool EqualityOnly = false;
5346 
5347     if (CommonSigned) {
5348       // The common type is signed, therefore no signed to unsigned conversion.
5349       if (!OtherRange.NonNegative) {
5350         // Check that the constant is representable in type OtherT.
5351         if (ConstantSigned) {
5352           if (OtherWidth >= Value.getMinSignedBits())
5353             return;
5354         } else { // !ConstantSigned
5355           if (OtherWidth >= Value.getActiveBits() + 1)
5356             return;
5357         }
5358       } else { // !OtherSigned
5359                // Check that the constant is representable in type OtherT.
5360         // Negative values are out of range.
5361         if (ConstantSigned) {
5362           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5363             return;
5364         } else { // !ConstantSigned
5365           if (OtherWidth >= Value.getActiveBits())
5366             return;
5367         }
5368       }
5369     } else { // !CommonSigned
5370       if (OtherRange.NonNegative) {
5371         if (OtherWidth >= Value.getActiveBits())
5372           return;
5373       } else { // OtherSigned
5374         assert(!ConstantSigned &&
5375                "Two signed types converted to unsigned types.");
5376         // Check to see if the constant is representable in OtherT.
5377         if (OtherWidth > Value.getActiveBits())
5378           return;
5379         // Check to see if the constant is equivalent to a negative value
5380         // cast to CommonT.
5381         if (S.Context.getIntWidth(ConstantT) ==
5382                 S.Context.getIntWidth(CommonT) &&
5383             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5384           return;
5385         // The constant value rests between values that OtherT can represent
5386         // after conversion.  Relational comparison still works, but equality
5387         // comparisons will be tautological.
5388         EqualityOnly = true;
5389       }
5390     }
5391 
5392     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5393 
5394     if (op == BO_EQ || op == BO_NE) {
5395       IsTrue = op == BO_NE;
5396     } else if (EqualityOnly) {
5397       return;
5398     } else if (RhsConstant) {
5399       if (op == BO_GT || op == BO_GE)
5400         IsTrue = !PositiveConstant;
5401       else // op == BO_LT || op == BO_LE
5402         IsTrue = PositiveConstant;
5403     } else {
5404       if (op == BO_LT || op == BO_LE)
5405         IsTrue = !PositiveConstant;
5406       else // op == BO_GT || op == BO_GE
5407         IsTrue = PositiveConstant;
5408     }
5409   } else {
5410     // Other isKnownToHaveBooleanValue
5411     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5412     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5413     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5414 
5415     static const struct LinkedConditions {
5416       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5417       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5418       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5419       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5420       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5421       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5422 
5423     } TruthTable = {
5424         // Constant on LHS.              | Constant on RHS.              |
5425         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
5426         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5427         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5428         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5429         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5430         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5431         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5432       };
5433 
5434     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5435 
5436     enum ConstantValue ConstVal = Zero;
5437     if (Value.isUnsigned() || Value.isNonNegative()) {
5438       if (Value == 0) {
5439         LiteralOrBoolConstant =
5440             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5441         ConstVal = Zero;
5442       } else if (Value == 1) {
5443         LiteralOrBoolConstant =
5444             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5445         ConstVal = One;
5446       } else {
5447         LiteralOrBoolConstant = LiteralConstant;
5448         ConstVal = GT_One;
5449       }
5450     } else {
5451       ConstVal = LT_Zero;
5452     }
5453 
5454     CompareBoolWithConstantResult CmpRes;
5455 
5456     switch (op) {
5457     case BO_LT:
5458       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5459       break;
5460     case BO_GT:
5461       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5462       break;
5463     case BO_LE:
5464       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5465       break;
5466     case BO_GE:
5467       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5468       break;
5469     case BO_EQ:
5470       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5471       break;
5472     case BO_NE:
5473       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5474       break;
5475     default:
5476       CmpRes = Unkwn;
5477       break;
5478     }
5479 
5480     if (CmpRes == AFals) {
5481       IsTrue = false;
5482     } else if (CmpRes == ATrue) {
5483       IsTrue = true;
5484     } else {
5485       return;
5486     }
5487   }
5488 
5489   // If this is a comparison to an enum constant, include that
5490   // constant in the diagnostic.
5491   const EnumConstantDecl *ED = nullptr;
5492   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5493     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5494 
5495   SmallString<64> PrettySourceValue;
5496   llvm::raw_svector_ostream OS(PrettySourceValue);
5497   if (ED)
5498     OS << '\'' << *ED << "' (" << Value << ")";
5499   else
5500     OS << Value;
5501 
5502   S.DiagRuntimeBehavior(
5503     E->getOperatorLoc(), E,
5504     S.PDiag(diag::warn_out_of_range_compare)
5505         << OS.str() << LiteralOrBoolConstant
5506         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5507         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
5508 }
5509 
5510 /// Analyze the operands of the given comparison.  Implements the
5511 /// fallback case from AnalyzeComparison.
5512 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
5513   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5514   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5515 }
5516 
5517 /// \brief Implements -Wsign-compare.
5518 ///
5519 /// \param E the binary operator to check for warnings
5520 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
5521   // The type the comparison is being performed in.
5522   QualType T = E->getLHS()->getType();
5523   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5524          && "comparison with mismatched types");
5525   if (E->isValueDependent())
5526     return AnalyzeImpConvsInComparison(S, E);
5527 
5528   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5529   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
5530 
5531   bool IsComparisonConstant = false;
5532 
5533   // Check whether an integer constant comparison results in a value
5534   // of 'true' or 'false'.
5535   if (T->isIntegralType(S.Context)) {
5536     llvm::APSInt RHSValue;
5537     bool IsRHSIntegralLiteral =
5538       RHS->isIntegerConstantExpr(RHSValue, S.Context);
5539     llvm::APSInt LHSValue;
5540     bool IsLHSIntegralLiteral =
5541       LHS->isIntegerConstantExpr(LHSValue, S.Context);
5542     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5543         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5544     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5545       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5546     else
5547       IsComparisonConstant =
5548         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
5549   } else if (!T->hasUnsignedIntegerRepresentation())
5550       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
5551 
5552   // We don't do anything special if this isn't an unsigned integral
5553   // comparison:  we're only interested in integral comparisons, and
5554   // signed comparisons only happen in cases we don't care to warn about.
5555   //
5556   // We also don't care about value-dependent expressions or expressions
5557   // whose result is a constant.
5558   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
5559     return AnalyzeImpConvsInComparison(S, E);
5560 
5561   // Check to see if one of the (unmodified) operands is of different
5562   // signedness.
5563   Expr *signedOperand, *unsignedOperand;
5564   if (LHS->getType()->hasSignedIntegerRepresentation()) {
5565     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
5566            "unsigned comparison between two signed integer expressions?");
5567     signedOperand = LHS;
5568     unsignedOperand = RHS;
5569   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5570     signedOperand = RHS;
5571     unsignedOperand = LHS;
5572   } else {
5573     CheckTrivialUnsignedComparison(S, E);
5574     return AnalyzeImpConvsInComparison(S, E);
5575   }
5576 
5577   // Otherwise, calculate the effective range of the signed operand.
5578   IntRange signedRange = GetExprRange(S.Context, signedOperand);
5579 
5580   // Go ahead and analyze implicit conversions in the operands.  Note
5581   // that we skip the implicit conversions on both sides.
5582   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5583   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
5584 
5585   // If the signed range is non-negative, -Wsign-compare won't fire,
5586   // but we should still check for comparisons which are always true
5587   // or false.
5588   if (signedRange.NonNegative)
5589     return CheckTrivialUnsignedComparison(S, E);
5590 
5591   // For (in)equality comparisons, if the unsigned operand is a
5592   // constant which cannot collide with a overflowed signed operand,
5593   // then reinterpreting the signed operand as unsigned will not
5594   // change the result of the comparison.
5595   if (E->isEqualityOp()) {
5596     unsigned comparisonWidth = S.Context.getIntWidth(T);
5597     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
5598 
5599     // We should never be unable to prove that the unsigned operand is
5600     // non-negative.
5601     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5602 
5603     if (unsignedRange.Width < comparisonWidth)
5604       return;
5605   }
5606 
5607   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5608     S.PDiag(diag::warn_mixed_sign_comparison)
5609       << LHS->getType() << RHS->getType()
5610       << LHS->getSourceRange() << RHS->getSourceRange());
5611 }
5612 
5613 /// Analyzes an attempt to assign the given value to a bitfield.
5614 ///
5615 /// Returns true if there was something fishy about the attempt.
5616 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5617                                       SourceLocation InitLoc) {
5618   assert(Bitfield->isBitField());
5619   if (Bitfield->isInvalidDecl())
5620     return false;
5621 
5622   // White-list bool bitfields.
5623   if (Bitfield->getType()->isBooleanType())
5624     return false;
5625 
5626   // Ignore value- or type-dependent expressions.
5627   if (Bitfield->getBitWidth()->isValueDependent() ||
5628       Bitfield->getBitWidth()->isTypeDependent() ||
5629       Init->isValueDependent() ||
5630       Init->isTypeDependent())
5631     return false;
5632 
5633   Expr *OriginalInit = Init->IgnoreParenImpCasts();
5634 
5635   llvm::APSInt Value;
5636   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
5637     return false;
5638 
5639   unsigned OriginalWidth = Value.getBitWidth();
5640   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
5641 
5642   if (OriginalWidth <= FieldWidth)
5643     return false;
5644 
5645   // Compute the value which the bitfield will contain.
5646   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
5647   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
5648 
5649   // Check whether the stored value is equal to the original value.
5650   TruncatedValue = TruncatedValue.extend(OriginalWidth);
5651   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
5652     return false;
5653 
5654   // Special-case bitfields of width 1: booleans are naturally 0/1, and
5655   // therefore don't strictly fit into a signed bitfield of width 1.
5656   if (FieldWidth == 1 && Value == 1)
5657     return false;
5658 
5659   std::string PrettyValue = Value.toString(10);
5660   std::string PrettyTrunc = TruncatedValue.toString(10);
5661 
5662   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5663     << PrettyValue << PrettyTrunc << OriginalInit->getType()
5664     << Init->getSourceRange();
5665 
5666   return true;
5667 }
5668 
5669 /// Analyze the given simple or compound assignment for warning-worthy
5670 /// operations.
5671 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
5672   // Just recurse on the LHS.
5673   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5674 
5675   // We want to recurse on the RHS as normal unless we're assigning to
5676   // a bitfield.
5677   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
5678     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
5679                                   E->getOperatorLoc())) {
5680       // Recurse, ignoring any implicit conversions on the RHS.
5681       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5682                                         E->getOperatorLoc());
5683     }
5684   }
5685 
5686   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5687 }
5688 
5689 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5690 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
5691                             SourceLocation CContext, unsigned diag,
5692                             bool pruneControlFlow = false) {
5693   if (pruneControlFlow) {
5694     S.DiagRuntimeBehavior(E->getExprLoc(), E,
5695                           S.PDiag(diag)
5696                             << SourceType << T << E->getSourceRange()
5697                             << SourceRange(CContext));
5698     return;
5699   }
5700   S.Diag(E->getExprLoc(), diag)
5701     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5702 }
5703 
5704 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5705 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
5706                             SourceLocation CContext, unsigned diag,
5707                             bool pruneControlFlow = false) {
5708   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
5709 }
5710 
5711 /// Diagnose an implicit cast from a literal expression. Does not warn when the
5712 /// cast wouldn't lose information.
5713 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5714                                     SourceLocation CContext) {
5715   // Try to convert the literal exactly to an integer. If we can, don't warn.
5716   bool isExact = false;
5717   const llvm::APFloat &Value = FL->getValue();
5718   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5719                             T->hasUnsignedIntegerRepresentation());
5720   if (Value.convertToInteger(IntegerValue,
5721                              llvm::APFloat::rmTowardZero, &isExact)
5722       == llvm::APFloat::opOK && isExact)
5723     return;
5724 
5725   // FIXME: Force the precision of the source value down so we don't print
5726   // digits which are usually useless (we don't really care here if we
5727   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
5728   // would automatically print the shortest representation, but it's a bit
5729   // tricky to implement.
5730   SmallString<16> PrettySourceValue;
5731   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5732   precision = (precision * 59 + 195) / 196;
5733   Value.toString(PrettySourceValue, precision);
5734 
5735   SmallString<16> PrettyTargetValue;
5736   if (T->isSpecificBuiltinType(BuiltinType::Bool))
5737     PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5738   else
5739     IntegerValue.toString(PrettyTargetValue);
5740 
5741   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
5742     << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5743     << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
5744 }
5745 
5746 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5747   if (!Range.Width) return "0";
5748 
5749   llvm::APSInt ValueInRange = Value;
5750   ValueInRange.setIsSigned(!Range.NonNegative);
5751   ValueInRange = ValueInRange.trunc(Range.Width);
5752   return ValueInRange.toString(10);
5753 }
5754 
5755 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5756   if (!isa<ImplicitCastExpr>(Ex))
5757     return false;
5758 
5759   Expr *InnerE = Ex->IgnoreParenImpCasts();
5760   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5761   const Type *Source =
5762     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5763   if (Target->isDependentType())
5764     return false;
5765 
5766   const BuiltinType *FloatCandidateBT =
5767     dyn_cast<BuiltinType>(ToBool ? Source : Target);
5768   const Type *BoolCandidateType = ToBool ? Target : Source;
5769 
5770   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5771           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5772 }
5773 
5774 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5775                                       SourceLocation CC) {
5776   unsigned NumArgs = TheCall->getNumArgs();
5777   for (unsigned i = 0; i < NumArgs; ++i) {
5778     Expr *CurrA = TheCall->getArg(i);
5779     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5780       continue;
5781 
5782     bool IsSwapped = ((i > 0) &&
5783         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5784     IsSwapped |= ((i < (NumArgs - 1)) &&
5785         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5786     if (IsSwapped) {
5787       // Warn on this floating-point to bool conversion.
5788       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5789                       CurrA->getType(), CC,
5790                       diag::warn_impcast_floating_point_to_bool);
5791     }
5792   }
5793 }
5794 
5795 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
5796                              SourceLocation CC, bool *ICContext = nullptr) {
5797   if (E->isTypeDependent() || E->isValueDependent()) return;
5798 
5799   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5800   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5801   if (Source == Target) return;
5802   if (Target->isDependentType()) return;
5803 
5804   // If the conversion context location is invalid don't complain. We also
5805   // don't want to emit a warning if the issue occurs from the expansion of
5806   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5807   // delay this check as long as possible. Once we detect we are in that
5808   // scenario, we just return.
5809   if (CC.isInvalid())
5810     return;
5811 
5812   // Diagnose implicit casts to bool.
5813   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5814     if (isa<StringLiteral>(E))
5815       // Warn on string literal to bool.  Checks for string literals in logical
5816       // and expressions, for instance, assert(0 && "error here"), are
5817       // prevented by a check in AnalyzeImplicitConversions().
5818       return DiagnoseImpCast(S, E, T, CC,
5819                              diag::warn_impcast_string_literal_to_bool);
5820     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5821         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5822       // This covers the literal expressions that evaluate to Objective-C
5823       // objects.
5824       return DiagnoseImpCast(S, E, T, CC,
5825                              diag::warn_impcast_objective_c_literal_to_bool);
5826     }
5827     if (Source->isPointerType() || Source->canDecayToPointerType()) {
5828       // Warn on pointer to bool conversion that is always true.
5829       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5830                                      SourceRange(CC));
5831     }
5832   }
5833 
5834   // Strip vector types.
5835   if (isa<VectorType>(Source)) {
5836     if (!isa<VectorType>(Target)) {
5837       if (S.SourceMgr.isInSystemMacro(CC))
5838         return;
5839       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
5840     }
5841 
5842     // If the vector cast is cast between two vectors of the same size, it is
5843     // a bitcast, not a conversion.
5844     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5845       return;
5846 
5847     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5848     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5849   }
5850   if (auto VecTy = dyn_cast<VectorType>(Target))
5851     Target = VecTy->getElementType().getTypePtr();
5852 
5853   // Strip complex types.
5854   if (isa<ComplexType>(Source)) {
5855     if (!isa<ComplexType>(Target)) {
5856       if (S.SourceMgr.isInSystemMacro(CC))
5857         return;
5858 
5859       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
5860     }
5861 
5862     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5863     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5864   }
5865 
5866   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5867   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5868 
5869   // If the source is floating point...
5870   if (SourceBT && SourceBT->isFloatingPoint()) {
5871     // ...and the target is floating point...
5872     if (TargetBT && TargetBT->isFloatingPoint()) {
5873       // ...then warn if we're dropping FP rank.
5874 
5875       // Builtin FP kinds are ordered by increasing FP rank.
5876       if (SourceBT->getKind() > TargetBT->getKind()) {
5877         // Don't warn about float constants that are precisely
5878         // representable in the target type.
5879         Expr::EvalResult result;
5880         if (E->EvaluateAsRValue(result, S.Context)) {
5881           // Value might be a float, a float vector, or a float complex.
5882           if (IsSameFloatAfterCast(result.Val,
5883                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5884                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
5885             return;
5886         }
5887 
5888         if (S.SourceMgr.isInSystemMacro(CC))
5889           return;
5890 
5891         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
5892       }
5893       return;
5894     }
5895 
5896     // If the target is integral, always warn.
5897     if (TargetBT && TargetBT->isInteger()) {
5898       if (S.SourceMgr.isInSystemMacro(CC))
5899         return;
5900 
5901       Expr *InnerE = E->IgnoreParenImpCasts();
5902       // We also want to warn on, e.g., "int i = -1.234"
5903       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5904         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5905           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5906 
5907       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5908         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
5909       } else {
5910         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5911       }
5912     }
5913 
5914     // If the target is bool, warn if expr is a function or method call.
5915     if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5916         isa<CallExpr>(E)) {
5917       // Check last argument of function call to see if it is an
5918       // implicit cast from a type matching the type the result
5919       // is being cast to.
5920       CallExpr *CEx = cast<CallExpr>(E);
5921       unsigned NumArgs = CEx->getNumArgs();
5922       if (NumArgs > 0) {
5923         Expr *LastA = CEx->getArg(NumArgs - 1);
5924         Expr *InnerE = LastA->IgnoreParenImpCasts();
5925         const Type *InnerType =
5926           S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5927         if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5928           // Warn on this floating-point to bool conversion
5929           DiagnoseImpCast(S, E, T, CC,
5930                           diag::warn_impcast_floating_point_to_bool);
5931         }
5932       }
5933     }
5934     return;
5935   }
5936 
5937   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5938            == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5939       && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5940       && Target->isScalarType() && !Target->isNullPtrType()) {
5941     SourceLocation Loc = E->getSourceRange().getBegin();
5942     if (Loc.isMacroID())
5943       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5944     if (!Loc.isMacroID() || CC.isMacroID())
5945       S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5946           << T << clang::SourceRange(CC)
5947           << FixItHint::CreateReplacement(Loc,
5948                                           S.getFixItZeroLiteralForType(T, Loc));
5949   }
5950 
5951   if (!Source->isIntegerType() || !Target->isIntegerType())
5952     return;
5953 
5954   // TODO: remove this early return once the false positives for constant->bool
5955   // in templates, macros, etc, are reduced or removed.
5956   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5957     return;
5958 
5959   IntRange SourceRange = GetExprRange(S.Context, E);
5960   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5961 
5962   if (SourceRange.Width > TargetRange.Width) {
5963     // If the source is a constant, use a default-on diagnostic.
5964     // TODO: this should happen for bitfield stores, too.
5965     llvm::APSInt Value(32);
5966     if (E->isIntegerConstantExpr(Value, S.Context)) {
5967       if (S.SourceMgr.isInSystemMacro(CC))
5968         return;
5969 
5970       std::string PrettySourceValue = Value.toString(10);
5971       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5972 
5973       S.DiagRuntimeBehavior(E->getExprLoc(), E,
5974         S.PDiag(diag::warn_impcast_integer_precision_constant)
5975             << PrettySourceValue << PrettyTargetValue
5976             << E->getType() << T << E->getSourceRange()
5977             << clang::SourceRange(CC));
5978       return;
5979     }
5980 
5981     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5982     if (S.SourceMgr.isInSystemMacro(CC))
5983       return;
5984 
5985     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5986       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5987                              /* pruneControlFlow */ true);
5988     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5989   }
5990 
5991   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5992       (!TargetRange.NonNegative && SourceRange.NonNegative &&
5993        SourceRange.Width == TargetRange.Width)) {
5994 
5995     if (S.SourceMgr.isInSystemMacro(CC))
5996       return;
5997 
5998     unsigned DiagID = diag::warn_impcast_integer_sign;
5999 
6000     // Traditionally, gcc has warned about this under -Wsign-compare.
6001     // We also want to warn about it in -Wconversion.
6002     // So if -Wconversion is off, use a completely identical diagnostic
6003     // in the sign-compare group.
6004     // The conditional-checking code will
6005     if (ICContext) {
6006       DiagID = diag::warn_impcast_integer_sign_conditional;
6007       *ICContext = true;
6008     }
6009 
6010     return DiagnoseImpCast(S, E, T, CC, DiagID);
6011   }
6012 
6013   // Diagnose conversions between different enumeration types.
6014   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6015   // type, to give us better diagnostics.
6016   QualType SourceType = E->getType();
6017   if (!S.getLangOpts().CPlusPlus) {
6018     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6019       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6020         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6021         SourceType = S.Context.getTypeDeclType(Enum);
6022         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6023       }
6024   }
6025 
6026   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6027     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
6028       if (SourceEnum->getDecl()->hasNameForLinkage() &&
6029           TargetEnum->getDecl()->hasNameForLinkage() &&
6030           SourceEnum != TargetEnum) {
6031         if (S.SourceMgr.isInSystemMacro(CC))
6032           return;
6033 
6034         return DiagnoseImpCast(S, E, SourceType, T, CC,
6035                                diag::warn_impcast_different_enum_types);
6036       }
6037 
6038   return;
6039 }
6040 
6041 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6042                               SourceLocation CC, QualType T);
6043 
6044 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
6045                              SourceLocation CC, bool &ICContext) {
6046   E = E->IgnoreParenImpCasts();
6047 
6048   if (isa<ConditionalOperator>(E))
6049     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
6050 
6051   AnalyzeImplicitConversions(S, E, CC);
6052   if (E->getType() != T)
6053     return CheckImplicitConversion(S, E, T, CC, &ICContext);
6054   return;
6055 }
6056 
6057 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6058                               SourceLocation CC, QualType T) {
6059   AnalyzeImplicitConversions(S, E->getCond(), CC);
6060 
6061   bool Suspicious = false;
6062   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6063   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
6064 
6065   // If -Wconversion would have warned about either of the candidates
6066   // for a signedness conversion to the context type...
6067   if (!Suspicious) return;
6068 
6069   // ...but it's currently ignored...
6070   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
6071     return;
6072 
6073   // ...then check whether it would have warned about either of the
6074   // candidates for a signedness conversion to the condition type.
6075   if (E->getType() == T) return;
6076 
6077   Suspicious = false;
6078   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6079                           E->getType(), CC, &Suspicious);
6080   if (!Suspicious)
6081     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
6082                             E->getType(), CC, &Suspicious);
6083 }
6084 
6085 /// AnalyzeImplicitConversions - Find and report any interesting
6086 /// implicit conversions in the given expression.  There are a couple
6087 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
6088 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
6089   QualType T = OrigE->getType();
6090   Expr *E = OrigE->IgnoreParenImpCasts();
6091 
6092   if (E->isTypeDependent() || E->isValueDependent())
6093     return;
6094 
6095   // For conditional operators, we analyze the arguments as if they
6096   // were being fed directly into the output.
6097   if (isa<ConditionalOperator>(E)) {
6098     ConditionalOperator *CO = cast<ConditionalOperator>(E);
6099     CheckConditionalOperator(S, CO, CC, T);
6100     return;
6101   }
6102 
6103   // Check implicit argument conversions for function calls.
6104   if (CallExpr *Call = dyn_cast<CallExpr>(E))
6105     CheckImplicitArgumentConversions(S, Call, CC);
6106 
6107   // Go ahead and check any implicit conversions we might have skipped.
6108   // The non-canonical typecheck is just an optimization;
6109   // CheckImplicitConversion will filter out dead implicit conversions.
6110   if (E->getType() != T)
6111     CheckImplicitConversion(S, E, T, CC);
6112 
6113   // Now continue drilling into this expression.
6114 
6115   if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
6116     if (POE->getResultExpr())
6117       E = POE->getResultExpr();
6118   }
6119 
6120   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6121     return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6122 
6123   // Skip past explicit casts.
6124   if (isa<ExplicitCastExpr>(E)) {
6125     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
6126     return AnalyzeImplicitConversions(S, E, CC);
6127   }
6128 
6129   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6130     // Do a somewhat different check with comparison operators.
6131     if (BO->isComparisonOp())
6132       return AnalyzeComparison(S, BO);
6133 
6134     // And with simple assignments.
6135     if (BO->getOpcode() == BO_Assign)
6136       return AnalyzeAssignment(S, BO);
6137   }
6138 
6139   // These break the otherwise-useful invariant below.  Fortunately,
6140   // we don't really need to recurse into them, because any internal
6141   // expressions should have been analyzed already when they were
6142   // built into statements.
6143   if (isa<StmtExpr>(E)) return;
6144 
6145   // Don't descend into unevaluated contexts.
6146   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6147 
6148   // Now just recurse over the expression's children.
6149   CC = E->getExprLoc();
6150   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6151   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6152   for (Stmt::child_range I = E->children(); I; ++I) {
6153     Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6154     if (!ChildExpr)
6155       continue;
6156 
6157     if (IsLogicalAndOperator &&
6158         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6159       // Ignore checking string literals that are in logical and operators.
6160       // This is a common pattern for asserts.
6161       continue;
6162     AnalyzeImplicitConversions(S, ChildExpr, CC);
6163   }
6164 }
6165 
6166 } // end anonymous namespace
6167 
6168 enum {
6169   AddressOf,
6170   FunctionPointer,
6171   ArrayPointer
6172 };
6173 
6174 /// \brief Diagnose pointers that are always non-null.
6175 /// \param E the expression containing the pointer
6176 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6177 /// compared to a null pointer
6178 /// \param IsEqual True when the comparison is equal to a null pointer
6179 /// \param Range Extra SourceRange to highlight in the diagnostic
6180 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6181                                         Expr::NullPointerConstantKind NullKind,
6182                                         bool IsEqual, SourceRange Range) {
6183   if (!E)
6184     return;
6185 
6186   // Don't warn inside macros.
6187   if (E->getExprLoc().isMacroID())
6188       return;
6189   E = E->IgnoreImpCasts();
6190 
6191   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6192 
6193   if (isa<CXXThisExpr>(E)) {
6194     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6195                                 : diag::warn_this_bool_conversion;
6196     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6197     return;
6198   }
6199 
6200   bool IsAddressOf = false;
6201 
6202   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6203     if (UO->getOpcode() != UO_AddrOf)
6204       return;
6205     IsAddressOf = true;
6206     E = UO->getSubExpr();
6207   }
6208 
6209   // Expect to find a single Decl.  Skip anything more complicated.
6210   ValueDecl *D = nullptr;
6211   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6212     D = R->getDecl();
6213   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6214     D = M->getMemberDecl();
6215   }
6216 
6217   // Weak Decls can be null.
6218   if (!D || D->isWeak())
6219     return;
6220 
6221   QualType T = D->getType();
6222   const bool IsArray = T->isArrayType();
6223   const bool IsFunction = T->isFunctionType();
6224 
6225   if (IsAddressOf) {
6226     // Address of function is used to silence the function warning.
6227     if (IsFunction)
6228       return;
6229 
6230     if (T->isReferenceType()) {
6231       unsigned DiagID = IsCompare
6232                             ? diag::warn_address_of_reference_null_compare
6233                             : diag::warn_address_of_reference_bool_conversion;
6234       Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6235       return;
6236     }
6237   }
6238 
6239   // Found nothing.
6240   if (!IsAddressOf && !IsFunction && !IsArray)
6241     return;
6242 
6243   // Pretty print the expression for the diagnostic.
6244   std::string Str;
6245   llvm::raw_string_ostream S(Str);
6246   E->printPretty(S, nullptr, getPrintingPolicy());
6247 
6248   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6249                               : diag::warn_impcast_pointer_to_bool;
6250   unsigned DiagType;
6251   if (IsAddressOf)
6252     DiagType = AddressOf;
6253   else if (IsFunction)
6254     DiagType = FunctionPointer;
6255   else if (IsArray)
6256     DiagType = ArrayPointer;
6257   else
6258     llvm_unreachable("Could not determine diagnostic.");
6259   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6260                                 << Range << IsEqual;
6261 
6262   if (!IsFunction)
6263     return;
6264 
6265   // Suggest '&' to silence the function warning.
6266   Diag(E->getExprLoc(), diag::note_function_warning_silence)
6267       << FixItHint::CreateInsertion(E->getLocStart(), "&");
6268 
6269   // Check to see if '()' fixit should be emitted.
6270   QualType ReturnType;
6271   UnresolvedSet<4> NonTemplateOverloads;
6272   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6273   if (ReturnType.isNull())
6274     return;
6275 
6276   if (IsCompare) {
6277     // There are two cases here.  If there is null constant, the only suggest
6278     // for a pointer return type.  If the null is 0, then suggest if the return
6279     // type is a pointer or an integer type.
6280     if (!ReturnType->isPointerType()) {
6281       if (NullKind == Expr::NPCK_ZeroExpression ||
6282           NullKind == Expr::NPCK_ZeroLiteral) {
6283         if (!ReturnType->isIntegerType())
6284           return;
6285       } else {
6286         return;
6287       }
6288     }
6289   } else { // !IsCompare
6290     // For function to bool, only suggest if the function pointer has bool
6291     // return type.
6292     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6293       return;
6294   }
6295   Diag(E->getExprLoc(), diag::note_function_to_function_call)
6296       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
6297 }
6298 
6299 
6300 /// Diagnoses "dangerous" implicit conversions within the given
6301 /// expression (which is a full expression).  Implements -Wconversion
6302 /// and -Wsign-compare.
6303 ///
6304 /// \param CC the "context" location of the implicit conversion, i.e.
6305 ///   the most location of the syntactic entity requiring the implicit
6306 ///   conversion
6307 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
6308   // Don't diagnose in unevaluated contexts.
6309   if (isUnevaluatedContext())
6310     return;
6311 
6312   // Don't diagnose for value- or type-dependent expressions.
6313   if (E->isTypeDependent() || E->isValueDependent())
6314     return;
6315 
6316   // Check for array bounds violations in cases where the check isn't triggered
6317   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6318   // ArraySubscriptExpr is on the RHS of a variable initialization.
6319   CheckArrayAccess(E);
6320 
6321   // This is not the right CC for (e.g.) a variable initialization.
6322   AnalyzeImplicitConversions(*this, E, CC);
6323 }
6324 
6325 /// Diagnose when expression is an integer constant expression and its evaluation
6326 /// results in integer overflow
6327 void Sema::CheckForIntOverflow (Expr *E) {
6328   if (isa<BinaryOperator>(E->IgnoreParens()))
6329     E->EvaluateForOverflow(Context);
6330 }
6331 
6332 namespace {
6333 /// \brief Visitor for expressions which looks for unsequenced operations on the
6334 /// same object.
6335 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
6336   typedef EvaluatedExprVisitor<SequenceChecker> Base;
6337 
6338   /// \brief A tree of sequenced regions within an expression. Two regions are
6339   /// unsequenced if one is an ancestor or a descendent of the other. When we
6340   /// finish processing an expression with sequencing, such as a comma
6341   /// expression, we fold its tree nodes into its parent, since they are
6342   /// unsequenced with respect to nodes we will visit later.
6343   class SequenceTree {
6344     struct Value {
6345       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6346       unsigned Parent : 31;
6347       bool Merged : 1;
6348     };
6349     SmallVector<Value, 8> Values;
6350 
6351   public:
6352     /// \brief A region within an expression which may be sequenced with respect
6353     /// to some other region.
6354     class Seq {
6355       explicit Seq(unsigned N) : Index(N) {}
6356       unsigned Index;
6357       friend class SequenceTree;
6358     public:
6359       Seq() : Index(0) {}
6360     };
6361 
6362     SequenceTree() { Values.push_back(Value(0)); }
6363     Seq root() const { return Seq(0); }
6364 
6365     /// \brief Create a new sequence of operations, which is an unsequenced
6366     /// subset of \p Parent. This sequence of operations is sequenced with
6367     /// respect to other children of \p Parent.
6368     Seq allocate(Seq Parent) {
6369       Values.push_back(Value(Parent.Index));
6370       return Seq(Values.size() - 1);
6371     }
6372 
6373     /// \brief Merge a sequence of operations into its parent.
6374     void merge(Seq S) {
6375       Values[S.Index].Merged = true;
6376     }
6377 
6378     /// \brief Determine whether two operations are unsequenced. This operation
6379     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6380     /// should have been merged into its parent as appropriate.
6381     bool isUnsequenced(Seq Cur, Seq Old) {
6382       unsigned C = representative(Cur.Index);
6383       unsigned Target = representative(Old.Index);
6384       while (C >= Target) {
6385         if (C == Target)
6386           return true;
6387         C = Values[C].Parent;
6388       }
6389       return false;
6390     }
6391 
6392   private:
6393     /// \brief Pick a representative for a sequence.
6394     unsigned representative(unsigned K) {
6395       if (Values[K].Merged)
6396         // Perform path compression as we go.
6397         return Values[K].Parent = representative(Values[K].Parent);
6398       return K;
6399     }
6400   };
6401 
6402   /// An object for which we can track unsequenced uses.
6403   typedef NamedDecl *Object;
6404 
6405   /// Different flavors of object usage which we track. We only track the
6406   /// least-sequenced usage of each kind.
6407   enum UsageKind {
6408     /// A read of an object. Multiple unsequenced reads are OK.
6409     UK_Use,
6410     /// A modification of an object which is sequenced before the value
6411     /// computation of the expression, such as ++n in C++.
6412     UK_ModAsValue,
6413     /// A modification of an object which is not sequenced before the value
6414     /// computation of the expression, such as n++.
6415     UK_ModAsSideEffect,
6416 
6417     UK_Count = UK_ModAsSideEffect + 1
6418   };
6419 
6420   struct Usage {
6421     Usage() : Use(nullptr), Seq() {}
6422     Expr *Use;
6423     SequenceTree::Seq Seq;
6424   };
6425 
6426   struct UsageInfo {
6427     UsageInfo() : Diagnosed(false) {}
6428     Usage Uses[UK_Count];
6429     /// Have we issued a diagnostic for this variable already?
6430     bool Diagnosed;
6431   };
6432   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6433 
6434   Sema &SemaRef;
6435   /// Sequenced regions within the expression.
6436   SequenceTree Tree;
6437   /// Declaration modifications and references which we have seen.
6438   UsageInfoMap UsageMap;
6439   /// The region we are currently within.
6440   SequenceTree::Seq Region;
6441   /// Filled in with declarations which were modified as a side-effect
6442   /// (that is, post-increment operations).
6443   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
6444   /// Expressions to check later. We defer checking these to reduce
6445   /// stack usage.
6446   SmallVectorImpl<Expr *> &WorkList;
6447 
6448   /// RAII object wrapping the visitation of a sequenced subexpression of an
6449   /// expression. At the end of this process, the side-effects of the evaluation
6450   /// become sequenced with respect to the value computation of the result, so
6451   /// we downgrade any UK_ModAsSideEffect within the evaluation to
6452   /// UK_ModAsValue.
6453   struct SequencedSubexpression {
6454     SequencedSubexpression(SequenceChecker &Self)
6455       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6456       Self.ModAsSideEffect = &ModAsSideEffect;
6457     }
6458     ~SequencedSubexpression() {
6459       for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6460         UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6461         U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6462         Self.addUsage(U, ModAsSideEffect[I].first,
6463                       ModAsSideEffect[I].second.Use, UK_ModAsValue);
6464       }
6465       Self.ModAsSideEffect = OldModAsSideEffect;
6466     }
6467 
6468     SequenceChecker &Self;
6469     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6470     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
6471   };
6472 
6473   /// RAII object wrapping the visitation of a subexpression which we might
6474   /// choose to evaluate as a constant. If any subexpression is evaluated and
6475   /// found to be non-constant, this allows us to suppress the evaluation of
6476   /// the outer expression.
6477   class EvaluationTracker {
6478   public:
6479     EvaluationTracker(SequenceChecker &Self)
6480         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6481       Self.EvalTracker = this;
6482     }
6483     ~EvaluationTracker() {
6484       Self.EvalTracker = Prev;
6485       if (Prev)
6486         Prev->EvalOK &= EvalOK;
6487     }
6488 
6489     bool evaluate(const Expr *E, bool &Result) {
6490       if (!EvalOK || E->isValueDependent())
6491         return false;
6492       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6493       return EvalOK;
6494     }
6495 
6496   private:
6497     SequenceChecker &Self;
6498     EvaluationTracker *Prev;
6499     bool EvalOK;
6500   } *EvalTracker;
6501 
6502   /// \brief Find the object which is produced by the specified expression,
6503   /// if any.
6504   Object getObject(Expr *E, bool Mod) const {
6505     E = E->IgnoreParenCasts();
6506     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6507       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6508         return getObject(UO->getSubExpr(), Mod);
6509     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6510       if (BO->getOpcode() == BO_Comma)
6511         return getObject(BO->getRHS(), Mod);
6512       if (Mod && BO->isAssignmentOp())
6513         return getObject(BO->getLHS(), Mod);
6514     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6515       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6516       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6517         return ME->getMemberDecl();
6518     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6519       // FIXME: If this is a reference, map through to its value.
6520       return DRE->getDecl();
6521     return nullptr;
6522   }
6523 
6524   /// \brief Note that an object was modified or used by an expression.
6525   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6526     Usage &U = UI.Uses[UK];
6527     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6528       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6529         ModAsSideEffect->push_back(std::make_pair(O, U));
6530       U.Use = Ref;
6531       U.Seq = Region;
6532     }
6533   }
6534   /// \brief Check whether a modification or use conflicts with a prior usage.
6535   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6536                   bool IsModMod) {
6537     if (UI.Diagnosed)
6538       return;
6539 
6540     const Usage &U = UI.Uses[OtherKind];
6541     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6542       return;
6543 
6544     Expr *Mod = U.Use;
6545     Expr *ModOrUse = Ref;
6546     if (OtherKind == UK_Use)
6547       std::swap(Mod, ModOrUse);
6548 
6549     SemaRef.Diag(Mod->getExprLoc(),
6550                  IsModMod ? diag::warn_unsequenced_mod_mod
6551                           : diag::warn_unsequenced_mod_use)
6552       << O << SourceRange(ModOrUse->getExprLoc());
6553     UI.Diagnosed = true;
6554   }
6555 
6556   void notePreUse(Object O, Expr *Use) {
6557     UsageInfo &U = UsageMap[O];
6558     // Uses conflict with other modifications.
6559     checkUsage(O, U, Use, UK_ModAsValue, false);
6560   }
6561   void notePostUse(Object O, Expr *Use) {
6562     UsageInfo &U = UsageMap[O];
6563     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6564     addUsage(U, O, Use, UK_Use);
6565   }
6566 
6567   void notePreMod(Object O, Expr *Mod) {
6568     UsageInfo &U = UsageMap[O];
6569     // Modifications conflict with other modifications and with uses.
6570     checkUsage(O, U, Mod, UK_ModAsValue, true);
6571     checkUsage(O, U, Mod, UK_Use, false);
6572   }
6573   void notePostMod(Object O, Expr *Use, UsageKind UK) {
6574     UsageInfo &U = UsageMap[O];
6575     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6576     addUsage(U, O, Use, UK);
6577   }
6578 
6579 public:
6580   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6581       : Base(S.Context), SemaRef(S), Region(Tree.root()),
6582         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
6583     Visit(E);
6584   }
6585 
6586   void VisitStmt(Stmt *S) {
6587     // Skip all statements which aren't expressions for now.
6588   }
6589 
6590   void VisitExpr(Expr *E) {
6591     // By default, just recurse to evaluated subexpressions.
6592     Base::VisitStmt(E);
6593   }
6594 
6595   void VisitCastExpr(CastExpr *E) {
6596     Object O = Object();
6597     if (E->getCastKind() == CK_LValueToRValue)
6598       O = getObject(E->getSubExpr(), false);
6599 
6600     if (O)
6601       notePreUse(O, E);
6602     VisitExpr(E);
6603     if (O)
6604       notePostUse(O, E);
6605   }
6606 
6607   void VisitBinComma(BinaryOperator *BO) {
6608     // C++11 [expr.comma]p1:
6609     //   Every value computation and side effect associated with the left
6610     //   expression is sequenced before every value computation and side
6611     //   effect associated with the right expression.
6612     SequenceTree::Seq LHS = Tree.allocate(Region);
6613     SequenceTree::Seq RHS = Tree.allocate(Region);
6614     SequenceTree::Seq OldRegion = Region;
6615 
6616     {
6617       SequencedSubexpression SeqLHS(*this);
6618       Region = LHS;
6619       Visit(BO->getLHS());
6620     }
6621 
6622     Region = RHS;
6623     Visit(BO->getRHS());
6624 
6625     Region = OldRegion;
6626 
6627     // Forget that LHS and RHS are sequenced. They are both unsequenced
6628     // with respect to other stuff.
6629     Tree.merge(LHS);
6630     Tree.merge(RHS);
6631   }
6632 
6633   void VisitBinAssign(BinaryOperator *BO) {
6634     // The modification is sequenced after the value computation of the LHS
6635     // and RHS, so check it before inspecting the operands and update the
6636     // map afterwards.
6637     Object O = getObject(BO->getLHS(), true);
6638     if (!O)
6639       return VisitExpr(BO);
6640 
6641     notePreMod(O, BO);
6642 
6643     // C++11 [expr.ass]p7:
6644     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6645     //   only once.
6646     //
6647     // Therefore, for a compound assignment operator, O is considered used
6648     // everywhere except within the evaluation of E1 itself.
6649     if (isa<CompoundAssignOperator>(BO))
6650       notePreUse(O, BO);
6651 
6652     Visit(BO->getLHS());
6653 
6654     if (isa<CompoundAssignOperator>(BO))
6655       notePostUse(O, BO);
6656 
6657     Visit(BO->getRHS());
6658 
6659     // C++11 [expr.ass]p1:
6660     //   the assignment is sequenced [...] before the value computation of the
6661     //   assignment expression.
6662     // C11 6.5.16/3 has no such rule.
6663     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6664                                                        : UK_ModAsSideEffect);
6665   }
6666   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6667     VisitBinAssign(CAO);
6668   }
6669 
6670   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6671   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6672   void VisitUnaryPreIncDec(UnaryOperator *UO) {
6673     Object O = getObject(UO->getSubExpr(), true);
6674     if (!O)
6675       return VisitExpr(UO);
6676 
6677     notePreMod(O, UO);
6678     Visit(UO->getSubExpr());
6679     // C++11 [expr.pre.incr]p1:
6680     //   the expression ++x is equivalent to x+=1
6681     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6682                                                        : UK_ModAsSideEffect);
6683   }
6684 
6685   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6686   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6687   void VisitUnaryPostIncDec(UnaryOperator *UO) {
6688     Object O = getObject(UO->getSubExpr(), true);
6689     if (!O)
6690       return VisitExpr(UO);
6691 
6692     notePreMod(O, UO);
6693     Visit(UO->getSubExpr());
6694     notePostMod(O, UO, UK_ModAsSideEffect);
6695   }
6696 
6697   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6698   void VisitBinLOr(BinaryOperator *BO) {
6699     // The side-effects of the LHS of an '&&' are sequenced before the
6700     // value computation of the RHS, and hence before the value computation
6701     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6702     // as if they were unconditionally sequenced.
6703     EvaluationTracker Eval(*this);
6704     {
6705       SequencedSubexpression Sequenced(*this);
6706       Visit(BO->getLHS());
6707     }
6708 
6709     bool Result;
6710     if (Eval.evaluate(BO->getLHS(), Result)) {
6711       if (!Result)
6712         Visit(BO->getRHS());
6713     } else {
6714       // Check for unsequenced operations in the RHS, treating it as an
6715       // entirely separate evaluation.
6716       //
6717       // FIXME: If there are operations in the RHS which are unsequenced
6718       // with respect to operations outside the RHS, and those operations
6719       // are unconditionally evaluated, diagnose them.
6720       WorkList.push_back(BO->getRHS());
6721     }
6722   }
6723   void VisitBinLAnd(BinaryOperator *BO) {
6724     EvaluationTracker Eval(*this);
6725     {
6726       SequencedSubexpression Sequenced(*this);
6727       Visit(BO->getLHS());
6728     }
6729 
6730     bool Result;
6731     if (Eval.evaluate(BO->getLHS(), Result)) {
6732       if (Result)
6733         Visit(BO->getRHS());
6734     } else {
6735       WorkList.push_back(BO->getRHS());
6736     }
6737   }
6738 
6739   // Only visit the condition, unless we can be sure which subexpression will
6740   // be chosen.
6741   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
6742     EvaluationTracker Eval(*this);
6743     {
6744       SequencedSubexpression Sequenced(*this);
6745       Visit(CO->getCond());
6746     }
6747 
6748     bool Result;
6749     if (Eval.evaluate(CO->getCond(), Result))
6750       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
6751     else {
6752       WorkList.push_back(CO->getTrueExpr());
6753       WorkList.push_back(CO->getFalseExpr());
6754     }
6755   }
6756 
6757   void VisitCallExpr(CallExpr *CE) {
6758     // C++11 [intro.execution]p15:
6759     //   When calling a function [...], every value computation and side effect
6760     //   associated with any argument expression, or with the postfix expression
6761     //   designating the called function, is sequenced before execution of every
6762     //   expression or statement in the body of the function [and thus before
6763     //   the value computation of its result].
6764     SequencedSubexpression Sequenced(*this);
6765     Base::VisitCallExpr(CE);
6766 
6767     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6768   }
6769 
6770   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
6771     // This is a call, so all subexpressions are sequenced before the result.
6772     SequencedSubexpression Sequenced(*this);
6773 
6774     if (!CCE->isListInitialization())
6775       return VisitExpr(CCE);
6776 
6777     // In C++11, list initializations are sequenced.
6778     SmallVector<SequenceTree::Seq, 32> Elts;
6779     SequenceTree::Seq Parent = Region;
6780     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6781                                         E = CCE->arg_end();
6782          I != E; ++I) {
6783       Region = Tree.allocate(Parent);
6784       Elts.push_back(Region);
6785       Visit(*I);
6786     }
6787 
6788     // Forget that the initializers are sequenced.
6789     Region = Parent;
6790     for (unsigned I = 0; I < Elts.size(); ++I)
6791       Tree.merge(Elts[I]);
6792   }
6793 
6794   void VisitInitListExpr(InitListExpr *ILE) {
6795     if (!SemaRef.getLangOpts().CPlusPlus11)
6796       return VisitExpr(ILE);
6797 
6798     // In C++11, list initializations are sequenced.
6799     SmallVector<SequenceTree::Seq, 32> Elts;
6800     SequenceTree::Seq Parent = Region;
6801     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6802       Expr *E = ILE->getInit(I);
6803       if (!E) continue;
6804       Region = Tree.allocate(Parent);
6805       Elts.push_back(Region);
6806       Visit(E);
6807     }
6808 
6809     // Forget that the initializers are sequenced.
6810     Region = Parent;
6811     for (unsigned I = 0; I < Elts.size(); ++I)
6812       Tree.merge(Elts[I]);
6813   }
6814 };
6815 }
6816 
6817 void Sema::CheckUnsequencedOperations(Expr *E) {
6818   SmallVector<Expr *, 8> WorkList;
6819   WorkList.push_back(E);
6820   while (!WorkList.empty()) {
6821     Expr *Item = WorkList.pop_back_val();
6822     SequenceChecker(*this, Item, WorkList);
6823   }
6824 }
6825 
6826 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6827                               bool IsConstexpr) {
6828   CheckImplicitConversions(E, CheckLoc);
6829   CheckUnsequencedOperations(E);
6830   if (!IsConstexpr && !E->isValueDependent())
6831     CheckForIntOverflow(E);
6832 }
6833 
6834 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6835                                        FieldDecl *BitField,
6836                                        Expr *Init) {
6837   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6838 }
6839 
6840 /// CheckParmsForFunctionDef - Check that the parameters of the given
6841 /// function are appropriate for the definition of a function. This
6842 /// takes care of any checks that cannot be performed on the
6843 /// declaration itself, e.g., that the types of each of the function
6844 /// parameters are complete.
6845 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6846                                     ParmVarDecl *const *PEnd,
6847                                     bool CheckParameterNames) {
6848   bool HasInvalidParm = false;
6849   for (; P != PEnd; ++P) {
6850     ParmVarDecl *Param = *P;
6851 
6852     // C99 6.7.5.3p4: the parameters in a parameter type list in a
6853     // function declarator that is part of a function definition of
6854     // that function shall not have incomplete type.
6855     //
6856     // This is also C++ [dcl.fct]p6.
6857     if (!Param->isInvalidDecl() &&
6858         RequireCompleteType(Param->getLocation(), Param->getType(),
6859                             diag::err_typecheck_decl_incomplete_type)) {
6860       Param->setInvalidDecl();
6861       HasInvalidParm = true;
6862     }
6863 
6864     // C99 6.9.1p5: If the declarator includes a parameter type list, the
6865     // declaration of each parameter shall include an identifier.
6866     if (CheckParameterNames &&
6867         Param->getIdentifier() == nullptr &&
6868         !Param->isImplicit() &&
6869         !getLangOpts().CPlusPlus)
6870       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6871 
6872     // C99 6.7.5.3p12:
6873     //   If the function declarator is not part of a definition of that
6874     //   function, parameters may have incomplete type and may use the [*]
6875     //   notation in their sequences of declarator specifiers to specify
6876     //   variable length array types.
6877     QualType PType = Param->getOriginalType();
6878     while (const ArrayType *AT = Context.getAsArrayType(PType)) {
6879       if (AT->getSizeModifier() == ArrayType::Star) {
6880         // FIXME: This diagnostic should point the '[*]' if source-location
6881         // information is added for it.
6882         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
6883         break;
6884       }
6885       PType= AT->getElementType();
6886     }
6887 
6888     // MSVC destroys objects passed by value in the callee.  Therefore a
6889     // function definition which takes such a parameter must be able to call the
6890     // object's destructor.  However, we don't perform any direct access check
6891     // on the dtor.
6892     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6893                                        .getCXXABI()
6894                                        .areArgsDestroyedLeftToRightInCallee()) {
6895       if (!Param->isInvalidDecl()) {
6896         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6897           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6898           if (!ClassDecl->isInvalidDecl() &&
6899               !ClassDecl->hasIrrelevantDestructor() &&
6900               !ClassDecl->isDependentContext()) {
6901             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6902             MarkFunctionReferenced(Param->getLocation(), Destructor);
6903             DiagnoseUseOfDecl(Destructor, Param->getLocation());
6904           }
6905         }
6906       }
6907     }
6908   }
6909 
6910   return HasInvalidParm;
6911 }
6912 
6913 /// CheckCastAlign - Implements -Wcast-align, which warns when a
6914 /// pointer cast increases the alignment requirements.
6915 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6916   // This is actually a lot of work to potentially be doing on every
6917   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
6918   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
6919     return;
6920 
6921   // Ignore dependent types.
6922   if (T->isDependentType() || Op->getType()->isDependentType())
6923     return;
6924 
6925   // Require that the destination be a pointer type.
6926   const PointerType *DestPtr = T->getAs<PointerType>();
6927   if (!DestPtr) return;
6928 
6929   // If the destination has alignment 1, we're done.
6930   QualType DestPointee = DestPtr->getPointeeType();
6931   if (DestPointee->isIncompleteType()) return;
6932   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6933   if (DestAlign.isOne()) return;
6934 
6935   // Require that the source be a pointer type.
6936   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6937   if (!SrcPtr) return;
6938   QualType SrcPointee = SrcPtr->getPointeeType();
6939 
6940   // Whitelist casts from cv void*.  We already implicitly
6941   // whitelisted casts to cv void*, since they have alignment 1.
6942   // Also whitelist casts involving incomplete types, which implicitly
6943   // includes 'void'.
6944   if (SrcPointee->isIncompleteType()) return;
6945 
6946   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6947   if (SrcAlign >= DestAlign) return;
6948 
6949   Diag(TRange.getBegin(), diag::warn_cast_align)
6950     << Op->getType() << T
6951     << static_cast<unsigned>(SrcAlign.getQuantity())
6952     << static_cast<unsigned>(DestAlign.getQuantity())
6953     << TRange << Op->getSourceRange();
6954 }
6955 
6956 static const Type* getElementType(const Expr *BaseExpr) {
6957   const Type* EltType = BaseExpr->getType().getTypePtr();
6958   if (EltType->isAnyPointerType())
6959     return EltType->getPointeeType().getTypePtr();
6960   else if (EltType->isArrayType())
6961     return EltType->getBaseElementTypeUnsafe();
6962   return EltType;
6963 }
6964 
6965 /// \brief Check whether this array fits the idiom of a size-one tail padded
6966 /// array member of a struct.
6967 ///
6968 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
6969 /// commonly used to emulate flexible arrays in C89 code.
6970 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6971                                     const NamedDecl *ND) {
6972   if (Size != 1 || !ND) return false;
6973 
6974   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6975   if (!FD) return false;
6976 
6977   // Don't consider sizes resulting from macro expansions or template argument
6978   // substitution to form C89 tail-padded arrays.
6979 
6980   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
6981   while (TInfo) {
6982     TypeLoc TL = TInfo->getTypeLoc();
6983     // Look through typedefs.
6984     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6985       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
6986       TInfo = TDL->getTypeSourceInfo();
6987       continue;
6988     }
6989     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6990       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
6991       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6992         return false;
6993     }
6994     break;
6995   }
6996 
6997   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
6998   if (!RD) return false;
6999   if (RD->isUnion()) return false;
7000   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7001     if (!CRD->isStandardLayout()) return false;
7002   }
7003 
7004   // See if this is the last field decl in the record.
7005   const Decl *D = FD;
7006   while ((D = D->getNextDeclInContext()))
7007     if (isa<FieldDecl>(D))
7008       return false;
7009   return true;
7010 }
7011 
7012 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7013                             const ArraySubscriptExpr *ASE,
7014                             bool AllowOnePastEnd, bool IndexNegated) {
7015   IndexExpr = IndexExpr->IgnoreParenImpCasts();
7016   if (IndexExpr->isValueDependent())
7017     return;
7018 
7019   const Type *EffectiveType = getElementType(BaseExpr);
7020   BaseExpr = BaseExpr->IgnoreParenCasts();
7021   const ConstantArrayType *ArrayTy =
7022     Context.getAsConstantArrayType(BaseExpr->getType());
7023   if (!ArrayTy)
7024     return;
7025 
7026   llvm::APSInt index;
7027   if (!IndexExpr->EvaluateAsInt(index, Context))
7028     return;
7029   if (IndexNegated)
7030     index = -index;
7031 
7032   const NamedDecl *ND = nullptr;
7033   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7034     ND = dyn_cast<NamedDecl>(DRE->getDecl());
7035   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7036     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7037 
7038   if (index.isUnsigned() || !index.isNegative()) {
7039     llvm::APInt size = ArrayTy->getSize();
7040     if (!size.isStrictlyPositive())
7041       return;
7042 
7043     const Type* BaseType = getElementType(BaseExpr);
7044     if (BaseType != EffectiveType) {
7045       // Make sure we're comparing apples to apples when comparing index to size
7046       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7047       uint64_t array_typesize = Context.getTypeSize(BaseType);
7048       // Handle ptrarith_typesize being zero, such as when casting to void*
7049       if (!ptrarith_typesize) ptrarith_typesize = 1;
7050       if (ptrarith_typesize != array_typesize) {
7051         // There's a cast to a different size type involved
7052         uint64_t ratio = array_typesize / ptrarith_typesize;
7053         // TODO: Be smarter about handling cases where array_typesize is not a
7054         // multiple of ptrarith_typesize
7055         if (ptrarith_typesize * ratio == array_typesize)
7056           size *= llvm::APInt(size.getBitWidth(), ratio);
7057       }
7058     }
7059 
7060     if (size.getBitWidth() > index.getBitWidth())
7061       index = index.zext(size.getBitWidth());
7062     else if (size.getBitWidth() < index.getBitWidth())
7063       size = size.zext(index.getBitWidth());
7064 
7065     // For array subscripting the index must be less than size, but for pointer
7066     // arithmetic also allow the index (offset) to be equal to size since
7067     // computing the next address after the end of the array is legal and
7068     // commonly done e.g. in C++ iterators and range-based for loops.
7069     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
7070       return;
7071 
7072     // Also don't warn for arrays of size 1 which are members of some
7073     // structure. These are often used to approximate flexible arrays in C89
7074     // code.
7075     if (IsTailPaddedMemberArray(*this, size, ND))
7076       return;
7077 
7078     // Suppress the warning if the subscript expression (as identified by the
7079     // ']' location) and the index expression are both from macro expansions
7080     // within a system header.
7081     if (ASE) {
7082       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7083           ASE->getRBracketLoc());
7084       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7085         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7086             IndexExpr->getLocStart());
7087         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
7088           return;
7089       }
7090     }
7091 
7092     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
7093     if (ASE)
7094       DiagID = diag::warn_array_index_exceeds_bounds;
7095 
7096     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7097                         PDiag(DiagID) << index.toString(10, true)
7098                           << size.toString(10, true)
7099                           << (unsigned)size.getLimitedValue(~0U)
7100                           << IndexExpr->getSourceRange());
7101   } else {
7102     unsigned DiagID = diag::warn_array_index_precedes_bounds;
7103     if (!ASE) {
7104       DiagID = diag::warn_ptr_arith_precedes_bounds;
7105       if (index.isNegative()) index = -index;
7106     }
7107 
7108     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7109                         PDiag(DiagID) << index.toString(10, true)
7110                           << IndexExpr->getSourceRange());
7111   }
7112 
7113   if (!ND) {
7114     // Try harder to find a NamedDecl to point at in the note.
7115     while (const ArraySubscriptExpr *ASE =
7116            dyn_cast<ArraySubscriptExpr>(BaseExpr))
7117       BaseExpr = ASE->getBase()->IgnoreParenCasts();
7118     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7119       ND = dyn_cast<NamedDecl>(DRE->getDecl());
7120     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7121       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7122   }
7123 
7124   if (ND)
7125     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7126                         PDiag(diag::note_array_index_out_of_bounds)
7127                           << ND->getDeclName());
7128 }
7129 
7130 void Sema::CheckArrayAccess(const Expr *expr) {
7131   int AllowOnePastEnd = 0;
7132   while (expr) {
7133     expr = expr->IgnoreParenImpCasts();
7134     switch (expr->getStmtClass()) {
7135       case Stmt::ArraySubscriptExprClass: {
7136         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
7137         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
7138                          AllowOnePastEnd > 0);
7139         return;
7140       }
7141       case Stmt::UnaryOperatorClass: {
7142         // Only unwrap the * and & unary operators
7143         const UnaryOperator *UO = cast<UnaryOperator>(expr);
7144         expr = UO->getSubExpr();
7145         switch (UO->getOpcode()) {
7146           case UO_AddrOf:
7147             AllowOnePastEnd++;
7148             break;
7149           case UO_Deref:
7150             AllowOnePastEnd--;
7151             break;
7152           default:
7153             return;
7154         }
7155         break;
7156       }
7157       case Stmt::ConditionalOperatorClass: {
7158         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7159         if (const Expr *lhs = cond->getLHS())
7160           CheckArrayAccess(lhs);
7161         if (const Expr *rhs = cond->getRHS())
7162           CheckArrayAccess(rhs);
7163         return;
7164       }
7165       default:
7166         return;
7167     }
7168   }
7169 }
7170 
7171 //===--- CHECK: Objective-C retain cycles ----------------------------------//
7172 
7173 namespace {
7174   struct RetainCycleOwner {
7175     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
7176     VarDecl *Variable;
7177     SourceRange Range;
7178     SourceLocation Loc;
7179     bool Indirect;
7180 
7181     void setLocsFrom(Expr *e) {
7182       Loc = e->getExprLoc();
7183       Range = e->getSourceRange();
7184     }
7185   };
7186 }
7187 
7188 /// Consider whether capturing the given variable can possibly lead to
7189 /// a retain cycle.
7190 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
7191   // In ARC, it's captured strongly iff the variable has __strong
7192   // lifetime.  In MRR, it's captured strongly if the variable is
7193   // __block and has an appropriate type.
7194   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7195     return false;
7196 
7197   owner.Variable = var;
7198   if (ref)
7199     owner.setLocsFrom(ref);
7200   return true;
7201 }
7202 
7203 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
7204   while (true) {
7205     e = e->IgnoreParens();
7206     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7207       switch (cast->getCastKind()) {
7208       case CK_BitCast:
7209       case CK_LValueBitCast:
7210       case CK_LValueToRValue:
7211       case CK_ARCReclaimReturnedObject:
7212         e = cast->getSubExpr();
7213         continue;
7214 
7215       default:
7216         return false;
7217       }
7218     }
7219 
7220     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7221       ObjCIvarDecl *ivar = ref->getDecl();
7222       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7223         return false;
7224 
7225       // Try to find a retain cycle in the base.
7226       if (!findRetainCycleOwner(S, ref->getBase(), owner))
7227         return false;
7228 
7229       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7230       owner.Indirect = true;
7231       return true;
7232     }
7233 
7234     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7235       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7236       if (!var) return false;
7237       return considerVariable(var, ref, owner);
7238     }
7239 
7240     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7241       if (member->isArrow()) return false;
7242 
7243       // Don't count this as an indirect ownership.
7244       e = member->getBase();
7245       continue;
7246     }
7247 
7248     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7249       // Only pay attention to pseudo-objects on property references.
7250       ObjCPropertyRefExpr *pre
7251         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7252                                               ->IgnoreParens());
7253       if (!pre) return false;
7254       if (pre->isImplicitProperty()) return false;
7255       ObjCPropertyDecl *property = pre->getExplicitProperty();
7256       if (!property->isRetaining() &&
7257           !(property->getPropertyIvarDecl() &&
7258             property->getPropertyIvarDecl()->getType()
7259               .getObjCLifetime() == Qualifiers::OCL_Strong))
7260           return false;
7261 
7262       owner.Indirect = true;
7263       if (pre->isSuperReceiver()) {
7264         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7265         if (!owner.Variable)
7266           return false;
7267         owner.Loc = pre->getLocation();
7268         owner.Range = pre->getSourceRange();
7269         return true;
7270       }
7271       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7272                               ->getSourceExpr());
7273       continue;
7274     }
7275 
7276     // Array ivars?
7277 
7278     return false;
7279   }
7280 }
7281 
7282 namespace {
7283   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7284     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7285       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7286         Context(Context), Variable(variable), Capturer(nullptr),
7287         VarWillBeReased(false) {}
7288     ASTContext &Context;
7289     VarDecl *Variable;
7290     Expr *Capturer;
7291     bool VarWillBeReased;
7292 
7293     void VisitDeclRefExpr(DeclRefExpr *ref) {
7294       if (ref->getDecl() == Variable && !Capturer)
7295         Capturer = ref;
7296     }
7297 
7298     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7299       if (Capturer) return;
7300       Visit(ref->getBase());
7301       if (Capturer && ref->isFreeIvar())
7302         Capturer = ref;
7303     }
7304 
7305     void VisitBlockExpr(BlockExpr *block) {
7306       // Look inside nested blocks
7307       if (block->getBlockDecl()->capturesVariable(Variable))
7308         Visit(block->getBlockDecl()->getBody());
7309     }
7310 
7311     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7312       if (Capturer) return;
7313       if (OVE->getSourceExpr())
7314         Visit(OVE->getSourceExpr());
7315     }
7316     void VisitBinaryOperator(BinaryOperator *BinOp) {
7317       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7318         return;
7319       Expr *LHS = BinOp->getLHS();
7320       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7321         if (DRE->getDecl() != Variable)
7322           return;
7323         if (Expr *RHS = BinOp->getRHS()) {
7324           RHS = RHS->IgnoreParenCasts();
7325           llvm::APSInt Value;
7326           VarWillBeReased =
7327             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7328         }
7329       }
7330     }
7331   };
7332 }
7333 
7334 /// Check whether the given argument is a block which captures a
7335 /// variable.
7336 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7337   assert(owner.Variable && owner.Loc.isValid());
7338 
7339   e = e->IgnoreParenCasts();
7340 
7341   // Look through [^{...} copy] and Block_copy(^{...}).
7342   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7343     Selector Cmd = ME->getSelector();
7344     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7345       e = ME->getInstanceReceiver();
7346       if (!e)
7347         return nullptr;
7348       e = e->IgnoreParenCasts();
7349     }
7350   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7351     if (CE->getNumArgs() == 1) {
7352       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
7353       if (Fn) {
7354         const IdentifierInfo *FnI = Fn->getIdentifier();
7355         if (FnI && FnI->isStr("_Block_copy")) {
7356           e = CE->getArg(0)->IgnoreParenCasts();
7357         }
7358       }
7359     }
7360   }
7361 
7362   BlockExpr *block = dyn_cast<BlockExpr>(e);
7363   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7364     return nullptr;
7365 
7366   FindCaptureVisitor visitor(S.Context, owner.Variable);
7367   visitor.Visit(block->getBlockDecl()->getBody());
7368   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
7369 }
7370 
7371 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7372                                 RetainCycleOwner &owner) {
7373   assert(capturer);
7374   assert(owner.Variable && owner.Loc.isValid());
7375 
7376   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7377     << owner.Variable << capturer->getSourceRange();
7378   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7379     << owner.Indirect << owner.Range;
7380 }
7381 
7382 /// Check for a keyword selector that starts with the word 'add' or
7383 /// 'set'.
7384 static bool isSetterLikeSelector(Selector sel) {
7385   if (sel.isUnarySelector()) return false;
7386 
7387   StringRef str = sel.getNameForSlot(0);
7388   while (!str.empty() && str.front() == '_') str = str.substr(1);
7389   if (str.startswith("set"))
7390     str = str.substr(3);
7391   else if (str.startswith("add")) {
7392     // Specially whitelist 'addOperationWithBlock:'.
7393     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7394       return false;
7395     str = str.substr(3);
7396   }
7397   else
7398     return false;
7399 
7400   if (str.empty()) return true;
7401   return !isLowercase(str.front());
7402 }
7403 
7404 /// Check a message send to see if it's likely to cause a retain cycle.
7405 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7406   // Only check instance methods whose selector looks like a setter.
7407   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7408     return;
7409 
7410   // Try to find a variable that the receiver is strongly owned by.
7411   RetainCycleOwner owner;
7412   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
7413     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
7414       return;
7415   } else {
7416     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7417     owner.Variable = getCurMethodDecl()->getSelfDecl();
7418     owner.Loc = msg->getSuperLoc();
7419     owner.Range = msg->getSuperLoc();
7420   }
7421 
7422   // Check whether the receiver is captured by any of the arguments.
7423   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7424     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7425       return diagnoseRetainCycle(*this, capturer, owner);
7426 }
7427 
7428 /// Check a property assign to see if it's likely to cause a retain cycle.
7429 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7430   RetainCycleOwner owner;
7431   if (!findRetainCycleOwner(*this, receiver, owner))
7432     return;
7433 
7434   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7435     diagnoseRetainCycle(*this, capturer, owner);
7436 }
7437 
7438 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7439   RetainCycleOwner Owner;
7440   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
7441     return;
7442 
7443   // Because we don't have an expression for the variable, we have to set the
7444   // location explicitly here.
7445   Owner.Loc = Var->getLocation();
7446   Owner.Range = Var->getSourceRange();
7447 
7448   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7449     diagnoseRetainCycle(*this, Capturer, Owner);
7450 }
7451 
7452 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7453                                      Expr *RHS, bool isProperty) {
7454   // Check if RHS is an Objective-C object literal, which also can get
7455   // immediately zapped in a weak reference.  Note that we explicitly
7456   // allow ObjCStringLiterals, since those are designed to never really die.
7457   RHS = RHS->IgnoreParenImpCasts();
7458 
7459   // This enum needs to match with the 'select' in
7460   // warn_objc_arc_literal_assign (off-by-1).
7461   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7462   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7463     return false;
7464 
7465   S.Diag(Loc, diag::warn_arc_literal_assign)
7466     << (unsigned) Kind
7467     << (isProperty ? 0 : 1)
7468     << RHS->getSourceRange();
7469 
7470   return true;
7471 }
7472 
7473 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7474                                     Qualifiers::ObjCLifetime LT,
7475                                     Expr *RHS, bool isProperty) {
7476   // Strip off any implicit cast added to get to the one ARC-specific.
7477   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7478     if (cast->getCastKind() == CK_ARCConsumeObject) {
7479       S.Diag(Loc, diag::warn_arc_retained_assign)
7480         << (LT == Qualifiers::OCL_ExplicitNone)
7481         << (isProperty ? 0 : 1)
7482         << RHS->getSourceRange();
7483       return true;
7484     }
7485     RHS = cast->getSubExpr();
7486   }
7487 
7488   if (LT == Qualifiers::OCL_Weak &&
7489       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7490     return true;
7491 
7492   return false;
7493 }
7494 
7495 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7496                               QualType LHS, Expr *RHS) {
7497   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7498 
7499   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7500     return false;
7501 
7502   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7503     return true;
7504 
7505   return false;
7506 }
7507 
7508 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7509                               Expr *LHS, Expr *RHS) {
7510   QualType LHSType;
7511   // PropertyRef on LHS type need be directly obtained from
7512   // its declaration as it has a PseudoType.
7513   ObjCPropertyRefExpr *PRE
7514     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7515   if (PRE && !PRE->isImplicitProperty()) {
7516     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7517     if (PD)
7518       LHSType = PD->getType();
7519   }
7520 
7521   if (LHSType.isNull())
7522     LHSType = LHS->getType();
7523 
7524   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7525 
7526   if (LT == Qualifiers::OCL_Weak) {
7527     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
7528       getCurFunction()->markSafeWeakUse(LHS);
7529   }
7530 
7531   if (checkUnsafeAssigns(Loc, LHSType, RHS))
7532     return;
7533 
7534   // FIXME. Check for other life times.
7535   if (LT != Qualifiers::OCL_None)
7536     return;
7537 
7538   if (PRE) {
7539     if (PRE->isImplicitProperty())
7540       return;
7541     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7542     if (!PD)
7543       return;
7544 
7545     unsigned Attributes = PD->getPropertyAttributes();
7546     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
7547       // when 'assign' attribute was not explicitly specified
7548       // by user, ignore it and rely on property type itself
7549       // for lifetime info.
7550       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7551       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7552           LHSType->isObjCRetainableType())
7553         return;
7554 
7555       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7556         if (cast->getCastKind() == CK_ARCConsumeObject) {
7557           Diag(Loc, diag::warn_arc_retained_property_assign)
7558           << RHS->getSourceRange();
7559           return;
7560         }
7561         RHS = cast->getSubExpr();
7562       }
7563     }
7564     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
7565       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7566         return;
7567     }
7568   }
7569 }
7570 
7571 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7572 
7573 namespace {
7574 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7575                                  SourceLocation StmtLoc,
7576                                  const NullStmt *Body) {
7577   // Do not warn if the body is a macro that expands to nothing, e.g:
7578   //
7579   // #define CALL(x)
7580   // if (condition)
7581   //   CALL(0);
7582   //
7583   if (Body->hasLeadingEmptyMacro())
7584     return false;
7585 
7586   // Get line numbers of statement and body.
7587   bool StmtLineInvalid;
7588   unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7589                                                       &StmtLineInvalid);
7590   if (StmtLineInvalid)
7591     return false;
7592 
7593   bool BodyLineInvalid;
7594   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7595                                                       &BodyLineInvalid);
7596   if (BodyLineInvalid)
7597     return false;
7598 
7599   // Warn if null statement and body are on the same line.
7600   if (StmtLine != BodyLine)
7601     return false;
7602 
7603   return true;
7604 }
7605 } // Unnamed namespace
7606 
7607 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7608                                  const Stmt *Body,
7609                                  unsigned DiagID) {
7610   // Since this is a syntactic check, don't emit diagnostic for template
7611   // instantiations, this just adds noise.
7612   if (CurrentInstantiationScope)
7613     return;
7614 
7615   // The body should be a null statement.
7616   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7617   if (!NBody)
7618     return;
7619 
7620   // Do the usual checks.
7621   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7622     return;
7623 
7624   Diag(NBody->getSemiLoc(), DiagID);
7625   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7626 }
7627 
7628 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7629                                  const Stmt *PossibleBody) {
7630   assert(!CurrentInstantiationScope); // Ensured by caller
7631 
7632   SourceLocation StmtLoc;
7633   const Stmt *Body;
7634   unsigned DiagID;
7635   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7636     StmtLoc = FS->getRParenLoc();
7637     Body = FS->getBody();
7638     DiagID = diag::warn_empty_for_body;
7639   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7640     StmtLoc = WS->getCond()->getSourceRange().getEnd();
7641     Body = WS->getBody();
7642     DiagID = diag::warn_empty_while_body;
7643   } else
7644     return; // Neither `for' nor `while'.
7645 
7646   // The body should be a null statement.
7647   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7648   if (!NBody)
7649     return;
7650 
7651   // Skip expensive checks if diagnostic is disabled.
7652   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
7653     return;
7654 
7655   // Do the usual checks.
7656   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7657     return;
7658 
7659   // `for(...);' and `while(...);' are popular idioms, so in order to keep
7660   // noise level low, emit diagnostics only if for/while is followed by a
7661   // CompoundStmt, e.g.:
7662   //    for (int i = 0; i < n; i++);
7663   //    {
7664   //      a(i);
7665   //    }
7666   // or if for/while is followed by a statement with more indentation
7667   // than for/while itself:
7668   //    for (int i = 0; i < n; i++);
7669   //      a(i);
7670   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7671   if (!ProbableTypo) {
7672     bool BodyColInvalid;
7673     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7674                              PossibleBody->getLocStart(),
7675                              &BodyColInvalid);
7676     if (BodyColInvalid)
7677       return;
7678 
7679     bool StmtColInvalid;
7680     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7681                              S->getLocStart(),
7682                              &StmtColInvalid);
7683     if (StmtColInvalid)
7684       return;
7685 
7686     if (BodyCol > StmtCol)
7687       ProbableTypo = true;
7688   }
7689 
7690   if (ProbableTypo) {
7691     Diag(NBody->getSemiLoc(), DiagID);
7692     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7693   }
7694 }
7695 
7696 //===--- Layout compatibility ----------------------------------------------//
7697 
7698 namespace {
7699 
7700 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7701 
7702 /// \brief Check if two enumeration types are layout-compatible.
7703 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7704   // C++11 [dcl.enum] p8:
7705   // Two enumeration types are layout-compatible if they have the same
7706   // underlying type.
7707   return ED1->isComplete() && ED2->isComplete() &&
7708          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7709 }
7710 
7711 /// \brief Check if two fields are layout-compatible.
7712 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7713   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7714     return false;
7715 
7716   if (Field1->isBitField() != Field2->isBitField())
7717     return false;
7718 
7719   if (Field1->isBitField()) {
7720     // Make sure that the bit-fields are the same length.
7721     unsigned Bits1 = Field1->getBitWidthValue(C);
7722     unsigned Bits2 = Field2->getBitWidthValue(C);
7723 
7724     if (Bits1 != Bits2)
7725       return false;
7726   }
7727 
7728   return true;
7729 }
7730 
7731 /// \brief Check if two standard-layout structs are layout-compatible.
7732 /// (C++11 [class.mem] p17)
7733 bool isLayoutCompatibleStruct(ASTContext &C,
7734                               RecordDecl *RD1,
7735                               RecordDecl *RD2) {
7736   // If both records are C++ classes, check that base classes match.
7737   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7738     // If one of records is a CXXRecordDecl we are in C++ mode,
7739     // thus the other one is a CXXRecordDecl, too.
7740     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7741     // Check number of base classes.
7742     if (D1CXX->getNumBases() != D2CXX->getNumBases())
7743       return false;
7744 
7745     // Check the base classes.
7746     for (CXXRecordDecl::base_class_const_iterator
7747                Base1 = D1CXX->bases_begin(),
7748            BaseEnd1 = D1CXX->bases_end(),
7749               Base2 = D2CXX->bases_begin();
7750          Base1 != BaseEnd1;
7751          ++Base1, ++Base2) {
7752       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7753         return false;
7754     }
7755   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7756     // If only RD2 is a C++ class, it should have zero base classes.
7757     if (D2CXX->getNumBases() > 0)
7758       return false;
7759   }
7760 
7761   // Check the fields.
7762   RecordDecl::field_iterator Field2 = RD2->field_begin(),
7763                              Field2End = RD2->field_end(),
7764                              Field1 = RD1->field_begin(),
7765                              Field1End = RD1->field_end();
7766   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7767     if (!isLayoutCompatible(C, *Field1, *Field2))
7768       return false;
7769   }
7770   if (Field1 != Field1End || Field2 != Field2End)
7771     return false;
7772 
7773   return true;
7774 }
7775 
7776 /// \brief Check if two standard-layout unions are layout-compatible.
7777 /// (C++11 [class.mem] p18)
7778 bool isLayoutCompatibleUnion(ASTContext &C,
7779                              RecordDecl *RD1,
7780                              RecordDecl *RD2) {
7781   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7782   for (auto *Field2 : RD2->fields())
7783     UnmatchedFields.insert(Field2);
7784 
7785   for (auto *Field1 : RD1->fields()) {
7786     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7787         I = UnmatchedFields.begin(),
7788         E = UnmatchedFields.end();
7789 
7790     for ( ; I != E; ++I) {
7791       if (isLayoutCompatible(C, Field1, *I)) {
7792         bool Result = UnmatchedFields.erase(*I);
7793         (void) Result;
7794         assert(Result);
7795         break;
7796       }
7797     }
7798     if (I == E)
7799       return false;
7800   }
7801 
7802   return UnmatchedFields.empty();
7803 }
7804 
7805 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7806   if (RD1->isUnion() != RD2->isUnion())
7807     return false;
7808 
7809   if (RD1->isUnion())
7810     return isLayoutCompatibleUnion(C, RD1, RD2);
7811   else
7812     return isLayoutCompatibleStruct(C, RD1, RD2);
7813 }
7814 
7815 /// \brief Check if two types are layout-compatible in C++11 sense.
7816 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7817   if (T1.isNull() || T2.isNull())
7818     return false;
7819 
7820   // C++11 [basic.types] p11:
7821   // If two types T1 and T2 are the same type, then T1 and T2 are
7822   // layout-compatible types.
7823   if (C.hasSameType(T1, T2))
7824     return true;
7825 
7826   T1 = T1.getCanonicalType().getUnqualifiedType();
7827   T2 = T2.getCanonicalType().getUnqualifiedType();
7828 
7829   const Type::TypeClass TC1 = T1->getTypeClass();
7830   const Type::TypeClass TC2 = T2->getTypeClass();
7831 
7832   if (TC1 != TC2)
7833     return false;
7834 
7835   if (TC1 == Type::Enum) {
7836     return isLayoutCompatible(C,
7837                               cast<EnumType>(T1)->getDecl(),
7838                               cast<EnumType>(T2)->getDecl());
7839   } else if (TC1 == Type::Record) {
7840     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7841       return false;
7842 
7843     return isLayoutCompatible(C,
7844                               cast<RecordType>(T1)->getDecl(),
7845                               cast<RecordType>(T2)->getDecl());
7846   }
7847 
7848   return false;
7849 }
7850 }
7851 
7852 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7853 
7854 namespace {
7855 /// \brief Given a type tag expression find the type tag itself.
7856 ///
7857 /// \param TypeExpr Type tag expression, as it appears in user's code.
7858 ///
7859 /// \param VD Declaration of an identifier that appears in a type tag.
7860 ///
7861 /// \param MagicValue Type tag magic value.
7862 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7863                      const ValueDecl **VD, uint64_t *MagicValue) {
7864   while(true) {
7865     if (!TypeExpr)
7866       return false;
7867 
7868     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7869 
7870     switch (TypeExpr->getStmtClass()) {
7871     case Stmt::UnaryOperatorClass: {
7872       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7873       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7874         TypeExpr = UO->getSubExpr();
7875         continue;
7876       }
7877       return false;
7878     }
7879 
7880     case Stmt::DeclRefExprClass: {
7881       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7882       *VD = DRE->getDecl();
7883       return true;
7884     }
7885 
7886     case Stmt::IntegerLiteralClass: {
7887       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7888       llvm::APInt MagicValueAPInt = IL->getValue();
7889       if (MagicValueAPInt.getActiveBits() <= 64) {
7890         *MagicValue = MagicValueAPInt.getZExtValue();
7891         return true;
7892       } else
7893         return false;
7894     }
7895 
7896     case Stmt::BinaryConditionalOperatorClass:
7897     case Stmt::ConditionalOperatorClass: {
7898       const AbstractConditionalOperator *ACO =
7899           cast<AbstractConditionalOperator>(TypeExpr);
7900       bool Result;
7901       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7902         if (Result)
7903           TypeExpr = ACO->getTrueExpr();
7904         else
7905           TypeExpr = ACO->getFalseExpr();
7906         continue;
7907       }
7908       return false;
7909     }
7910 
7911     case Stmt::BinaryOperatorClass: {
7912       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7913       if (BO->getOpcode() == BO_Comma) {
7914         TypeExpr = BO->getRHS();
7915         continue;
7916       }
7917       return false;
7918     }
7919 
7920     default:
7921       return false;
7922     }
7923   }
7924 }
7925 
7926 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
7927 ///
7928 /// \param TypeExpr Expression that specifies a type tag.
7929 ///
7930 /// \param MagicValues Registered magic values.
7931 ///
7932 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7933 ///        kind.
7934 ///
7935 /// \param TypeInfo Information about the corresponding C type.
7936 ///
7937 /// \returns true if the corresponding C type was found.
7938 bool GetMatchingCType(
7939         const IdentifierInfo *ArgumentKind,
7940         const Expr *TypeExpr, const ASTContext &Ctx,
7941         const llvm::DenseMap<Sema::TypeTagMagicValue,
7942                              Sema::TypeTagData> *MagicValues,
7943         bool &FoundWrongKind,
7944         Sema::TypeTagData &TypeInfo) {
7945   FoundWrongKind = false;
7946 
7947   // Variable declaration that has type_tag_for_datatype attribute.
7948   const ValueDecl *VD = nullptr;
7949 
7950   uint64_t MagicValue;
7951 
7952   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7953     return false;
7954 
7955   if (VD) {
7956     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
7957       if (I->getArgumentKind() != ArgumentKind) {
7958         FoundWrongKind = true;
7959         return false;
7960       }
7961       TypeInfo.Type = I->getMatchingCType();
7962       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7963       TypeInfo.MustBeNull = I->getMustBeNull();
7964       return true;
7965     }
7966     return false;
7967   }
7968 
7969   if (!MagicValues)
7970     return false;
7971 
7972   llvm::DenseMap<Sema::TypeTagMagicValue,
7973                  Sema::TypeTagData>::const_iterator I =
7974       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7975   if (I == MagicValues->end())
7976     return false;
7977 
7978   TypeInfo = I->second;
7979   return true;
7980 }
7981 } // unnamed namespace
7982 
7983 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7984                                       uint64_t MagicValue, QualType Type,
7985                                       bool LayoutCompatible,
7986                                       bool MustBeNull) {
7987   if (!TypeTagForDatatypeMagicValues)
7988     TypeTagForDatatypeMagicValues.reset(
7989         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7990 
7991   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7992   (*TypeTagForDatatypeMagicValues)[Magic] =
7993       TypeTagData(Type, LayoutCompatible, MustBeNull);
7994 }
7995 
7996 namespace {
7997 bool IsSameCharType(QualType T1, QualType T2) {
7998   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7999   if (!BT1)
8000     return false;
8001 
8002   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8003   if (!BT2)
8004     return false;
8005 
8006   BuiltinType::Kind T1Kind = BT1->getKind();
8007   BuiltinType::Kind T2Kind = BT2->getKind();
8008 
8009   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
8010          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
8011          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8012          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8013 }
8014 } // unnamed namespace
8015 
8016 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8017                                     const Expr * const *ExprArgs) {
8018   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8019   bool IsPointerAttr = Attr->getIsPointer();
8020 
8021   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8022   bool FoundWrongKind;
8023   TypeTagData TypeInfo;
8024   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8025                         TypeTagForDatatypeMagicValues.get(),
8026                         FoundWrongKind, TypeInfo)) {
8027     if (FoundWrongKind)
8028       Diag(TypeTagExpr->getExprLoc(),
8029            diag::warn_type_tag_for_datatype_wrong_kind)
8030         << TypeTagExpr->getSourceRange();
8031     return;
8032   }
8033 
8034   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8035   if (IsPointerAttr) {
8036     // Skip implicit cast of pointer to `void *' (as a function argument).
8037     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
8038       if (ICE->getType()->isVoidPointerType() &&
8039           ICE->getCastKind() == CK_BitCast)
8040         ArgumentExpr = ICE->getSubExpr();
8041   }
8042   QualType ArgumentType = ArgumentExpr->getType();
8043 
8044   // Passing a `void*' pointer shouldn't trigger a warning.
8045   if (IsPointerAttr && ArgumentType->isVoidPointerType())
8046     return;
8047 
8048   if (TypeInfo.MustBeNull) {
8049     // Type tag with matching void type requires a null pointer.
8050     if (!ArgumentExpr->isNullPointerConstant(Context,
8051                                              Expr::NPC_ValueDependentIsNotNull)) {
8052       Diag(ArgumentExpr->getExprLoc(),
8053            diag::warn_type_safety_null_pointer_required)
8054           << ArgumentKind->getName()
8055           << ArgumentExpr->getSourceRange()
8056           << TypeTagExpr->getSourceRange();
8057     }
8058     return;
8059   }
8060 
8061   QualType RequiredType = TypeInfo.Type;
8062   if (IsPointerAttr)
8063     RequiredType = Context.getPointerType(RequiredType);
8064 
8065   bool mismatch = false;
8066   if (!TypeInfo.LayoutCompatible) {
8067     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8068 
8069     // C++11 [basic.fundamental] p1:
8070     // Plain char, signed char, and unsigned char are three distinct types.
8071     //
8072     // But we treat plain `char' as equivalent to `signed char' or `unsigned
8073     // char' depending on the current char signedness mode.
8074     if (mismatch)
8075       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8076                                            RequiredType->getPointeeType())) ||
8077           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8078         mismatch = false;
8079   } else
8080     if (IsPointerAttr)
8081       mismatch = !isLayoutCompatible(Context,
8082                                      ArgumentType->getPointeeType(),
8083                                      RequiredType->getPointeeType());
8084     else
8085       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8086 
8087   if (mismatch)
8088     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
8089         << ArgumentType << ArgumentKind
8090         << TypeInfo.LayoutCompatible << RequiredType
8091         << ArgumentExpr->getSourceRange()
8092         << TypeTagExpr->getSourceRange();
8093 }
8094 
8095