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