1 //===-- Scalar.cpp --------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Utility/Scalar.h"
10 #include "lldb/Utility/DataBufferHeap.h"
11 #include "lldb/Utility/DataExtractor.h"
12 #include "lldb/Utility/Endian.h"
13 #include "lldb/Utility/Status.h"
14 #include "lldb/Utility/Stream.h"
15 #include "lldb/Utility/StreamString.h"
16 #include "lldb/lldb-types.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/SmallString.h"
19 
20 #include <cinttypes>
21 #include <cstdio>
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 
26 using llvm::APFloat;
27 using llvm::APInt;
28 
29 namespace {
30 enum class Category { Void, Integral, Float };
31 }
32 
33 static Category GetCategory(Scalar::Type type) {
34   switch (type) {
35   case Scalar::e_void:
36     return Category::Void;
37   case Scalar::e_float:
38   case Scalar::e_double:
39   case Scalar::e_long_double:
40     return Category::Float;
41   case Scalar::e_sint:
42   case Scalar::e_slong:
43   case Scalar::e_slonglong:
44   case Scalar::e_sint128:
45   case Scalar::e_sint256:
46   case Scalar::e_sint512:
47   case Scalar::e_uint:
48   case Scalar::e_ulong:
49   case Scalar::e_ulonglong:
50   case Scalar::e_uint128:
51   case Scalar::e_uint256:
52   case Scalar::e_uint512:
53     return Category::Integral;
54   }
55   llvm_unreachable("Unhandled type!");
56 }
57 
58 static bool IsSigned(Scalar::Type type) {
59   switch (type) {
60   case Scalar::e_void:
61   case Scalar::e_uint:
62   case Scalar::e_ulong:
63   case Scalar::e_ulonglong:
64   case Scalar::e_uint128:
65   case Scalar::e_uint256:
66   case Scalar::e_uint512:
67     return false;
68   case Scalar::e_sint:
69   case Scalar::e_slong:
70   case Scalar::e_slonglong:
71   case Scalar::e_sint128:
72   case Scalar::e_sint256:
73   case Scalar::e_sint512:
74   case Scalar::e_float:
75   case Scalar::e_double:
76   case Scalar::e_long_double:
77     return true;
78   }
79   llvm_unreachable("Unhandled type!");
80 }
81 
82 
83 // Promote to max type currently follows the ANSI C rule for type promotion in
84 // expressions.
85 static Scalar::Type PromoteToMaxType(
86     const Scalar &lhs,  // The const left hand side object
87     const Scalar &rhs,  // The const right hand side object
88     Scalar &temp_value, // A modifiable temp value than can be used to hold
89                         // either the promoted lhs or rhs object
90     const Scalar *&promoted_lhs_ptr, // Pointer to the resulting possibly
91                                      // promoted value of lhs (at most one of
92                                      // lhs/rhs will get promoted)
93     const Scalar *&promoted_rhs_ptr  // Pointer to the resulting possibly
94                                      // promoted value of rhs (at most one of
95                                      // lhs/rhs will get promoted)
96 ) {
97   Scalar result;
98   // Initialize the promoted values for both the right and left hand side
99   // values to be the objects themselves. If no promotion is needed (both right
100   // and left have the same type), then the temp_value will not get used.
101   promoted_lhs_ptr = &lhs;
102   promoted_rhs_ptr = &rhs;
103   // Extract the types of both the right and left hand side values
104   Scalar::Type lhs_type = lhs.GetType();
105   Scalar::Type rhs_type = rhs.GetType();
106 
107   if (lhs_type > rhs_type) {
108     // Right hand side need to be promoted
109     temp_value = rhs; // Copy right hand side into the temp value
110     if (temp_value.Promote(lhs_type)) // Promote it
111       promoted_rhs_ptr =
112           &temp_value; // Update the pointer for the promoted right hand side
113   } else if (lhs_type < rhs_type) {
114     // Left hand side need to be promoted
115     temp_value = lhs; // Copy left hand side value into the temp value
116     if (temp_value.Promote(rhs_type)) // Promote it
117       promoted_lhs_ptr =
118           &temp_value; // Update the pointer for the promoted left hand side
119   }
120 
121   // Make sure our type promotion worked as expected
122   if (promoted_lhs_ptr->GetType() == promoted_rhs_ptr->GetType())
123     return promoted_lhs_ptr->GetType(); // Return the resulting max type
124 
125   // Return the void type (zero) if we fail to promote either of the values.
126   return Scalar::e_void;
127 }
128 
129 bool Scalar::GetData(DataExtractor &data, size_t limit_byte_size) const {
130   size_t byte_size = GetByteSize();
131   if (byte_size == 0) {
132     data.Clear();
133     return false;
134   }
135   auto buffer_up = std::make_unique<DataBufferHeap>(byte_size, 0);
136   GetBytes(buffer_up->GetData());
137   lldb::offset_t offset = 0;
138 
139   if (limit_byte_size < byte_size) {
140     if (endian::InlHostByteOrder() == eByteOrderLittle) {
141       // On little endian systems if we want fewer bytes from the current
142       // type we just specify fewer bytes since the LSByte is first...
143       byte_size = limit_byte_size;
144     } else if (endian::InlHostByteOrder() == eByteOrderBig) {
145       // On big endian systems if we want fewer bytes from the current type
146       // have to advance our initial byte pointer and trim down the number of
147       // bytes since the MSByte is first
148       offset = byte_size - limit_byte_size;
149       byte_size = limit_byte_size;
150     }
151   }
152 
153   data.SetData(std::move(buffer_up), offset, byte_size);
154   data.SetByteOrder(endian::InlHostByteOrder());
155   return true;
156 }
157 
158 void Scalar::GetBytes(llvm::MutableArrayRef<uint8_t> storage) const {
159   assert(storage.size() >= GetByteSize());
160 
161   const auto &store = [&](const llvm::APInt &val) {
162     StoreIntToMemory(val, storage.data(), (val.getBitWidth() + 7) / 8);
163   };
164   switch (GetCategory(m_type)) {
165   case Category::Void:
166     break;
167   case Category::Integral:
168     store(m_integer);
169     break;
170   case Category::Float:
171     store(m_float.bitcastToAPInt());
172     break;
173   }
174 }
175 
176 size_t Scalar::GetByteSize() const {
177   switch (m_type) {
178   case e_void:
179     break;
180   case e_sint:
181   case e_uint:
182   case e_slong:
183   case e_ulong:
184   case e_slonglong:
185   case e_ulonglong:
186   case e_sint128:
187   case e_uint128:
188   case e_sint256:
189   case e_uint256:
190   case e_sint512:
191   case e_uint512:
192     return (m_integer.getBitWidth() / 8);
193   case e_float:
194     return sizeof(float_t);
195   case e_double:
196     return sizeof(double_t);
197   case e_long_double:
198     return sizeof(long_double_t);
199   }
200   return 0;
201 }
202 
203 bool Scalar::IsZero() const {
204   switch (GetCategory(m_type)) {
205   case Category::Void:
206     break;
207   case Category::Integral:
208     return m_integer.isNullValue();
209   case Category::Float:
210     return m_float.isZero();
211   }
212   return false;
213 }
214 
215 void Scalar::GetValue(Stream *s, bool show_type) const {
216   if (show_type)
217     s->Printf("(%s) ", GetTypeAsCString());
218 
219   switch (GetCategory(m_type)) {
220   case Category::Void:
221     break;
222   case Category::Integral:
223     s->PutCString(m_integer.toString(10, IsSigned(m_type)));
224     break;
225   case Category::Float:
226     llvm::SmallString<24> string;
227     m_float.toString(string);
228     s->PutCString(string);
229     break;
230   }
231 }
232 
233 Scalar::Type Scalar::GetBestTypeForBitSize(size_t bit_size, bool sign) {
234   // Scalar types are always host types, hence the sizeof().
235   if (sign) {
236     if (bit_size <= sizeof(int)*8) return Scalar::e_sint;
237     if (bit_size <= sizeof(long)*8) return Scalar::e_slong;
238     if (bit_size <= sizeof(long long)*8) return Scalar::e_slonglong;
239     if (bit_size <= 128) return Scalar::e_sint128;
240     if (bit_size <= 256) return Scalar::e_sint256;
241     if (bit_size <= 512) return Scalar::e_sint512;
242   } else {
243     if (bit_size <= sizeof(unsigned int)*8) return Scalar::e_uint;
244     if (bit_size <= sizeof(unsigned long)*8) return Scalar::e_ulong;
245     if (bit_size <= sizeof(unsigned long long)*8) return Scalar::e_ulonglong;
246     if (bit_size <= 128) return Scalar::e_uint128;
247     if (bit_size <= 256) return Scalar::e_uint256;
248     if (bit_size <= 512) return Scalar::e_uint512;
249   }
250   return Scalar::e_void;
251 }
252 
253 void Scalar::TruncOrExtendTo(uint16_t bits, bool sign) {
254   m_integer = sign ? m_integer.sextOrTrunc(bits) : m_integer.zextOrTrunc(bits);
255   m_type = GetBestTypeForBitSize(bits, sign);
256 }
257 
258 static size_t GetBitSize(Scalar::Type type) {
259   switch (type) {
260   case Scalar::e_void:
261     return 0;
262   case Scalar::e_sint:
263     return 8 * sizeof(int);
264   case Scalar::e_uint:
265     return 8 * sizeof(unsigned int);
266   case Scalar::e_slong:
267     return 8 * sizeof(long);
268   case Scalar::e_ulong:
269     return 8 * sizeof(unsigned long);
270   case Scalar::e_slonglong:
271     return 8 * sizeof(long long);
272   case Scalar::e_ulonglong:
273     return 8 * sizeof(unsigned long long);
274   case Scalar::e_sint128:
275   case Scalar::e_uint128:
276     return BITWIDTH_INT128;
277   case Scalar::e_sint256:
278   case Scalar::e_uint256:
279     return BITWIDTH_INT256;
280   case Scalar::e_sint512:
281   case Scalar::e_uint512:
282     return BITWIDTH_INT512;
283   case Scalar::e_float:
284     return 8 * sizeof(float);
285   case Scalar::e_double:
286     return 8 * sizeof(double);
287   case Scalar::e_long_double:
288     return 8 * sizeof(long double);
289   }
290   llvm_unreachable("Unhandled type!");
291 }
292 
293 static const llvm::fltSemantics &GetFltSemantics(Scalar::Type type) {
294   switch (type) {
295   case Scalar::e_void:
296   case Scalar::e_sint:
297   case Scalar::e_slong:
298   case Scalar::e_slonglong:
299   case Scalar::e_sint128:
300   case Scalar::e_sint256:
301   case Scalar::e_sint512:
302   case Scalar::e_uint:
303   case Scalar::e_ulong:
304   case Scalar::e_ulonglong:
305   case Scalar::e_uint128:
306   case Scalar::e_uint256:
307   case Scalar::e_uint512:
308     llvm_unreachable("Only floating point types supported!");
309   case Scalar::e_float:
310     return llvm::APFloat::IEEEsingle();
311   case Scalar::e_double:
312     return llvm::APFloat::IEEEdouble();
313   case Scalar::e_long_double:
314     return llvm::APFloat::x87DoubleExtended();
315   }
316   llvm_unreachable("Unhandled type!");
317 }
318 
319 bool Scalar::Promote(Scalar::Type type) {
320   bool success = false;
321   switch (GetCategory(m_type)) {
322   case Category::Void:
323     break;
324   case Category::Integral:
325     switch (GetCategory(type)) {
326     case Category::Void:
327       break;
328     case Category::Integral:
329       if (type < m_type)
330         break;
331       success = true;
332       if (IsSigned(m_type))
333         m_integer = m_integer.sextOrTrunc(GetBitSize(type));
334       else
335         m_integer = m_integer.zextOrTrunc(GetBitSize(type));
336       break;
337     case Category::Float:
338       m_float = llvm::APFloat(GetFltSemantics(type));
339       m_float.convertFromAPInt(m_integer, IsSigned(m_type),
340                                llvm::APFloat::rmNearestTiesToEven);
341       success = true;
342       break;
343     }
344     break;
345   case Category::Float:
346     switch (GetCategory(type)) {
347     case Category::Void:
348     case Category::Integral:
349       break;
350     case Category::Float:
351       if (type < m_type)
352         break;
353       bool ignore;
354       success = true;
355       m_float.convert(GetFltSemantics(type), llvm::APFloat::rmNearestTiesToEven,
356                       &ignore);
357     }
358   }
359 
360   if (success)
361     m_type = type;
362   return success;
363 }
364 
365 const char *Scalar::GetValueTypeAsCString(Scalar::Type type) {
366   switch (type) {
367   case e_void:
368     return "void";
369   case e_sint:
370     return "int";
371   case e_uint:
372     return "unsigned int";
373   case e_slong:
374     return "long";
375   case e_ulong:
376     return "unsigned long";
377   case e_slonglong:
378     return "long long";
379   case e_ulonglong:
380     return "unsigned long long";
381   case e_float:
382     return "float";
383   case e_double:
384     return "double";
385   case e_long_double:
386     return "long double";
387   case e_sint128:
388     return "int128_t";
389   case e_uint128:
390     return "uint128_t";
391   case e_sint256:
392     return "int256_t";
393   case e_uint256:
394     return "uint256_t";
395   case e_sint512:
396     return "int512_t";
397   case e_uint512:
398     return "uint512_t";
399   }
400   return "???";
401 }
402 
403 Scalar::Type
404 Scalar::GetValueTypeForSignedIntegerWithByteSize(size_t byte_size) {
405   if (byte_size <= sizeof(sint_t))
406     return e_sint;
407   if (byte_size <= sizeof(slong_t))
408     return e_slong;
409   if (byte_size <= sizeof(slonglong_t))
410     return e_slonglong;
411   return e_void;
412 }
413 
414 Scalar::Type
415 Scalar::GetValueTypeForUnsignedIntegerWithByteSize(size_t byte_size) {
416   if (byte_size <= sizeof(uint_t))
417     return e_uint;
418   if (byte_size <= sizeof(ulong_t))
419     return e_ulong;
420   if (byte_size <= sizeof(ulonglong_t))
421     return e_ulonglong;
422   return e_void;
423 }
424 
425 Scalar::Type Scalar::GetValueTypeForFloatWithByteSize(size_t byte_size) {
426   if (byte_size == sizeof(float_t))
427     return e_float;
428   if (byte_size == sizeof(double_t))
429     return e_double;
430   if (byte_size == sizeof(long_double_t))
431     return e_long_double;
432   return e_void;
433 }
434 
435 bool Scalar::MakeSigned() {
436   bool success = false;
437 
438   switch (m_type) {
439   case e_void:
440     break;
441   case e_sint:
442     success = true;
443     break;
444   case e_uint:
445     m_type = e_sint;
446     success = true;
447     break;
448   case e_slong:
449     success = true;
450     break;
451   case e_ulong:
452     m_type = e_slong;
453     success = true;
454     break;
455   case e_slonglong:
456     success = true;
457     break;
458   case e_ulonglong:
459     m_type = e_slonglong;
460     success = true;
461     break;
462   case e_sint128:
463     success = true;
464     break;
465   case e_uint128:
466     m_type = e_sint128;
467     success = true;
468     break;
469   case e_sint256:
470     success = true;
471     break;
472   case e_uint256:
473     m_type = e_sint256;
474     success = true;
475     break;
476   case e_sint512:
477     success = true;
478     break;
479   case e_uint512:
480     m_type = e_sint512;
481     success = true;
482     break;
483   case e_float:
484     success = true;
485     break;
486   case e_double:
487     success = true;
488     break;
489   case e_long_double:
490     success = true;
491     break;
492   }
493 
494   return success;
495 }
496 
497 bool Scalar::MakeUnsigned() {
498   bool success = false;
499 
500   switch (m_type) {
501   case e_void:
502     break;
503   case e_sint:
504     m_type = e_uint;
505     success = true;
506     break;
507   case e_uint:
508     success = true;
509     break;
510   case e_slong:
511     m_type = e_ulong;
512     success = true;
513     break;
514   case e_ulong:
515     success = true;
516     break;
517   case e_slonglong:
518     m_type = e_ulonglong;
519     success = true;
520     break;
521   case e_ulonglong:
522     success = true;
523     break;
524   case e_sint128:
525     m_type = e_uint128;
526     success = true;
527     break;
528   case e_uint128:
529     success = true;
530     break;
531   case e_sint256:
532     m_type = e_uint256;
533     success = true;
534     break;
535   case e_uint256:
536     success = true;
537     break;
538   case e_sint512:
539     m_type = e_uint512;
540     success = true;
541     break;
542   case e_uint512:
543     success = true;
544     break;
545   case e_float:
546     success = true;
547     break;
548   case e_double:
549     success = true;
550     break;
551   case e_long_double:
552     success = true;
553     break;
554   }
555 
556   return success;
557 }
558 
559 static llvm::APInt ToAPInt(const llvm::APFloat &f, unsigned bits,
560                            bool is_unsigned) {
561   llvm::APSInt result(bits, is_unsigned);
562   bool isExact;
563   f.convertToInteger(result, llvm::APFloat::rmTowardZero, &isExact);
564   return std::move(result);
565 }
566 
567 template <typename T> T Scalar::GetAs(T fail_value) const {
568   switch (GetCategory(m_type)) {
569   case Category::Void:
570     break;
571   case Category::Integral:
572     if (IsSigned(m_type))
573       return m_integer.sextOrTrunc(sizeof(T) * 8).getSExtValue();
574     return m_integer.zextOrTrunc(sizeof(T) * 8).getZExtValue();
575   case Category::Float:
576     return ToAPInt(m_float, sizeof(T) * 8, std::is_unsigned<T>::value)
577         .getSExtValue();
578   }
579   return fail_value;
580 }
581 
582 signed char Scalar::SChar(signed char fail_value) const {
583   return GetAs<signed char>(fail_value);
584 }
585 
586 unsigned char Scalar::UChar(unsigned char fail_value) const {
587   return GetAs<unsigned char>(fail_value);
588 }
589 
590 short Scalar::SShort(short fail_value) const {
591   return GetAs<short>(fail_value);
592 }
593 
594 unsigned short Scalar::UShort(unsigned short fail_value) const {
595   return GetAs<unsigned short>(fail_value);
596 }
597 
598 int Scalar::SInt(int fail_value) const { return GetAs<int>(fail_value); }
599 
600 unsigned int Scalar::UInt(unsigned int fail_value) const {
601   return GetAs<unsigned int>(fail_value);
602 }
603 
604 long Scalar::SLong(long fail_value) const { return GetAs<long>(fail_value); }
605 
606 unsigned long Scalar::ULong(unsigned long fail_value) const {
607   return GetAs<unsigned long>(fail_value);
608 }
609 
610 long long Scalar::SLongLong(long long fail_value) const {
611   return GetAs<long long>(fail_value);
612 }
613 
614 unsigned long long Scalar::ULongLong(unsigned long long fail_value) const {
615   return GetAs<unsigned long long>(fail_value);
616 }
617 
618 llvm::APInt Scalar::SInt128(const llvm::APInt &fail_value) const {
619   switch (GetCategory(m_type)) {
620   case Category::Void:
621     break;
622   case Category::Integral:
623     return m_integer;
624   case Category::Float:
625     return ToAPInt(m_float, 128, /*is_unsigned=*/false);
626   }
627   return fail_value;
628 }
629 
630 llvm::APInt Scalar::UInt128(const llvm::APInt &fail_value) const {
631   switch (GetCategory(m_type)) {
632   case Category::Void:
633     break;
634   case Category::Integral:
635     return m_integer;
636   case Category::Float:
637     return ToAPInt(m_float, 128, /*is_unsigned=*/true);
638   }
639   return fail_value;
640 }
641 
642 float Scalar::Float(float fail_value) const {
643   switch (GetCategory(m_type)) {
644   case Category::Void:
645     break;
646   case Category::Integral:
647     if (IsSigned(m_type))
648       return llvm::APIntOps::RoundSignedAPIntToFloat(m_integer);
649     return llvm::APIntOps::RoundAPIntToFloat(m_integer);
650 
651   case Category::Float: {
652     APFloat result = m_float;
653     bool losesInfo;
654     result.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
655                    &losesInfo);
656     return result.convertToFloat();
657   }
658   }
659   return fail_value;
660 }
661 
662 double Scalar::Double(double fail_value) const {
663   switch (GetCategory(m_type)) {
664   case Category::Void:
665     break;
666   case Category::Integral:
667     if (IsSigned(m_type))
668       return llvm::APIntOps::RoundSignedAPIntToDouble(m_integer);
669     return llvm::APIntOps::RoundAPIntToDouble(m_integer);
670 
671   case Category::Float: {
672     APFloat result = m_float;
673     bool losesInfo;
674     result.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
675                    &losesInfo);
676     return result.convertToDouble();
677   }
678   }
679   return fail_value;
680 }
681 
682 long double Scalar::LongDouble(long double fail_value) const {
683   /// No way to get more precision at the moment.
684   return static_cast<long double>(Double(fail_value));
685 }
686 
687 Scalar &Scalar::operator+=(const Scalar &rhs) {
688   Scalar temp_value;
689   const Scalar *a;
690   const Scalar *b;
691   if ((m_type = PromoteToMaxType(*this, rhs, temp_value, a, b)) !=
692       Scalar::e_void) {
693     switch (GetCategory(m_type)) {
694     case Category::Void:
695       break;
696     case Category::Integral:
697       m_integer = a->m_integer + b->m_integer;
698       break;
699 
700     case Category::Float:
701       m_float = a->m_float + b->m_float;
702       break;
703     }
704   }
705   return *this;
706 }
707 
708 Scalar &Scalar::operator<<=(const Scalar &rhs) {
709   if (GetCategory(m_type) == Category::Integral &&
710       GetCategory(rhs.m_type) == Category::Integral)
711     m_integer <<= rhs.m_integer;
712   else
713     m_type = e_void;
714   return *this;
715 }
716 
717 bool Scalar::ShiftRightLogical(const Scalar &rhs) {
718   if (GetCategory(m_type) == Category::Integral &&
719       GetCategory(rhs.m_type) == Category::Integral) {
720     m_integer = m_integer.lshr(rhs.m_integer);
721     return true;
722   }
723   m_type = e_void;
724   return false;
725 }
726 
727 Scalar &Scalar::operator>>=(const Scalar &rhs) {
728   switch (m_type) {
729   case e_void:
730   case e_float:
731   case e_double:
732   case e_long_double:
733     m_type = e_void;
734     break;
735 
736   case e_sint:
737   case e_uint:
738   case e_slong:
739   case e_ulong:
740   case e_slonglong:
741   case e_ulonglong:
742   case e_sint128:
743   case e_uint128:
744   case e_sint256:
745   case e_uint256:
746   case e_sint512:
747   case e_uint512:
748     switch (rhs.m_type) {
749     case e_void:
750     case e_float:
751     case e_double:
752     case e_long_double:
753       m_type = e_void;
754       break;
755     case e_sint:
756     case e_uint:
757     case e_slong:
758     case e_ulong:
759     case e_slonglong:
760     case e_ulonglong:
761     case e_sint128:
762     case e_uint128:
763     case e_sint256:
764     case e_uint256:
765     case e_sint512:
766     case e_uint512:
767       m_integer = m_integer.ashr(rhs.m_integer);
768       break;
769     }
770     break;
771   }
772   return *this;
773 }
774 
775 Scalar &Scalar::operator&=(const Scalar &rhs) {
776   if (GetCategory(m_type) == Category::Integral &&
777       GetCategory(rhs.m_type) == Category::Integral)
778     m_integer &= rhs.m_integer;
779   else
780     m_type = e_void;
781   return *this;
782 }
783 
784 bool Scalar::AbsoluteValue() {
785   switch (m_type) {
786   case e_void:
787     break;
788 
789   case e_sint:
790   case e_slong:
791   case e_slonglong:
792   case e_sint128:
793   case e_sint256:
794   case e_sint512:
795     if (m_integer.isNegative())
796       m_integer = -m_integer;
797     return true;
798 
799   case e_uint:
800   case e_ulong:
801   case e_ulonglong:
802     return true;
803   case e_uint128:
804   case e_uint256:
805   case e_uint512:
806   case e_float:
807   case e_double:
808   case e_long_double:
809     m_float.clearSign();
810     return true;
811   }
812   return false;
813 }
814 
815 bool Scalar::UnaryNegate() {
816   switch (GetCategory(m_type)) {
817   case Category::Void:
818     break;
819   case Category::Integral:
820     m_integer = -m_integer;
821     return true;
822   case Category::Float:
823     m_float.changeSign();
824     return true;
825   }
826   return false;
827 }
828 
829 bool Scalar::OnesComplement() {
830   if (GetCategory(m_type) == Category::Integral) {
831     m_integer = ~m_integer;
832     return true;
833   }
834 
835   return false;
836 }
837 
838 const Scalar lldb_private::operator+(const Scalar &lhs, const Scalar &rhs) {
839   Scalar result = lhs;
840   result += rhs;
841   return result;
842 }
843 
844 const Scalar lldb_private::operator-(const Scalar &lhs, const Scalar &rhs) {
845   Scalar result;
846   Scalar temp_value;
847   const Scalar *a;
848   const Scalar *b;
849   if ((result.m_type = PromoteToMaxType(lhs, rhs, temp_value, a, b)) !=
850       Scalar::e_void) {
851     switch (GetCategory(result.m_type)) {
852     case Category::Void:
853       break;
854     case Category::Integral:
855       result.m_integer = a->m_integer - b->m_integer;
856       break;
857     case Category::Float:
858       result.m_float = a->m_float - b->m_float;
859       break;
860     }
861   }
862   return result;
863 }
864 
865 const Scalar lldb_private::operator/(const Scalar &lhs, const Scalar &rhs) {
866   Scalar result;
867   Scalar temp_value;
868   const Scalar *a;
869   const Scalar *b;
870   if ((result.m_type = PromoteToMaxType(lhs, rhs, temp_value, a, b)) !=
871           Scalar::e_void &&
872       !b->IsZero()) {
873     switch (GetCategory(result.m_type)) {
874     case Category::Void:
875       break;
876     case Category::Integral:
877       if (IsSigned(result.m_type))
878         result.m_integer = a->m_integer.sdiv(b->m_integer);
879       else
880         result.m_integer = a->m_integer.udiv(b->m_integer);
881       return result;
882     case Category::Float:
883       result.m_float = a->m_float / b->m_float;
884       return result;
885     }
886   }
887   // For division only, the only way it should make it here is if a promotion
888   // failed, or if we are trying to do a divide by zero.
889   result.m_type = Scalar::e_void;
890   return result;
891 }
892 
893 const Scalar lldb_private::operator*(const Scalar &lhs, const Scalar &rhs) {
894   Scalar result;
895   Scalar temp_value;
896   const Scalar *a;
897   const Scalar *b;
898   if ((result.m_type = PromoteToMaxType(lhs, rhs, temp_value, a, b)) !=
899       Scalar::e_void) {
900     switch (GetCategory(result.m_type)) {
901     case Category::Void:
902       break;
903     case Category::Integral:
904       result.m_integer = a->m_integer * b->m_integer;
905       break;
906     case Category::Float:
907       result.m_float = a->m_float * b->m_float;
908       break;
909     }
910   }
911   return result;
912 }
913 
914 const Scalar lldb_private::operator&(const Scalar &lhs, const Scalar &rhs) {
915   Scalar result;
916   Scalar temp_value;
917   const Scalar *a;
918   const Scalar *b;
919   if ((result.m_type = PromoteToMaxType(lhs, rhs, temp_value, a, b)) !=
920       Scalar::e_void) {
921     if (GetCategory(result.m_type) == Category::Integral)
922       result.m_integer = a->m_integer & b->m_integer;
923     else
924       result.m_type = Scalar::e_void;
925   }
926   return result;
927 }
928 
929 const Scalar lldb_private::operator|(const Scalar &lhs, const Scalar &rhs) {
930   Scalar result;
931   Scalar temp_value;
932   const Scalar *a;
933   const Scalar *b;
934   if ((result.m_type = PromoteToMaxType(lhs, rhs, temp_value, a, b)) !=
935       Scalar::e_void) {
936     if (GetCategory(result.m_type) == Category::Integral)
937       result.m_integer = a->m_integer | b->m_integer;
938     else
939       result.m_type = Scalar::e_void;
940   }
941   return result;
942 }
943 
944 const Scalar lldb_private::operator%(const Scalar &lhs, const Scalar &rhs) {
945   Scalar result;
946   Scalar temp_value;
947   const Scalar *a;
948   const Scalar *b;
949   if ((result.m_type = PromoteToMaxType(lhs, rhs, temp_value, a, b)) !=
950       Scalar::e_void) {
951     if (!b->IsZero() && GetCategory(result.m_type) == Category::Integral) {
952       if (IsSigned(result.m_type))
953         result.m_integer = a->m_integer.srem(b->m_integer);
954       else
955         result.m_integer = a->m_integer.urem(b->m_integer);
956       return result;
957     }
958   }
959   result.m_type = Scalar::e_void;
960   return result;
961 }
962 
963 const Scalar lldb_private::operator^(const Scalar &lhs, const Scalar &rhs) {
964   Scalar result;
965   Scalar temp_value;
966   const Scalar *a;
967   const Scalar *b;
968   if ((result.m_type = PromoteToMaxType(lhs, rhs, temp_value, a, b)) !=
969       Scalar::e_void) {
970     if (GetCategory(result.m_type) == Category::Integral)
971       result.m_integer = a->m_integer ^ b->m_integer;
972     else
973       result.m_type = Scalar::e_void;
974   }
975   return result;
976 }
977 
978 const Scalar lldb_private::operator<<(const Scalar &lhs, const Scalar &rhs) {
979   Scalar result = lhs;
980   result <<= rhs;
981   return result;
982 }
983 
984 const Scalar lldb_private::operator>>(const Scalar &lhs, const Scalar &rhs) {
985   Scalar result = lhs;
986   result >>= rhs;
987   return result;
988 }
989 
990 Status Scalar::SetValueFromCString(const char *value_str, Encoding encoding,
991                                    size_t byte_size) {
992   Status error;
993   if (value_str == nullptr || value_str[0] == '\0') {
994     error.SetErrorString("Invalid c-string value string.");
995     return error;
996   }
997   switch (encoding) {
998   case eEncodingInvalid:
999     error.SetErrorString("Invalid encoding.");
1000     break;
1001 
1002   case eEncodingSint:
1003   case eEncodingUint: {
1004     llvm::StringRef str = value_str;
1005     bool is_signed = encoding == eEncodingSint;
1006     bool is_negative = is_signed && str.consume_front("-");
1007     APInt integer;
1008     if (str.getAsInteger(0, integer)) {
1009       error.SetErrorStringWithFormatv(
1010           "'{0}' is not a valid integer string value", value_str);
1011       break;
1012     }
1013     bool fits;
1014     if (is_signed) {
1015       integer = integer.zext(integer.getBitWidth() + 1);
1016       if (is_negative)
1017         integer.negate();
1018       fits = integer.isSignedIntN(byte_size * 8);
1019     } else
1020       fits = integer.isIntN(byte_size * 8);
1021     if (!fits) {
1022       error.SetErrorStringWithFormatv(
1023           "value {0} is too large to fit in a {1} byte integer value",
1024           value_str, byte_size);
1025       break;
1026     }
1027     m_type = GetBestTypeForBitSize(8 * byte_size, is_signed);
1028     if (m_type == e_void) {
1029       error.SetErrorStringWithFormatv("unsupported integer byte size: {0}",
1030                                       byte_size);
1031       break;
1032     }
1033     if (is_signed)
1034       m_integer = integer.sextOrTrunc(GetBitSize(m_type));
1035     else
1036       m_integer = integer.zextOrTrunc(GetBitSize(m_type));
1037     break;
1038   }
1039 
1040   case eEncodingIEEE754: {
1041     Type type = GetValueTypeForFloatWithByteSize(byte_size);
1042     if (type == e_void) {
1043       error.SetErrorStringWithFormatv("unsupported float byte size: {0}",
1044                                       byte_size);
1045       break;
1046     }
1047     APFloat f(GetFltSemantics(type));
1048     if (llvm::Expected<APFloat::opStatus> op =
1049             f.convertFromString(value_str, APFloat::rmNearestTiesToEven)) {
1050       m_type = type;
1051       m_float = std::move(f);
1052     } else
1053       error = op.takeError();
1054     break;
1055   }
1056 
1057   case eEncodingVector:
1058     error.SetErrorString("vector encoding unsupported.");
1059     break;
1060   }
1061   if (error.Fail())
1062     m_type = e_void;
1063 
1064   return error;
1065 }
1066 
1067 Status Scalar::SetValueFromData(const DataExtractor &data,
1068                                 lldb::Encoding encoding, size_t byte_size) {
1069   Status error;
1070   switch (encoding) {
1071   case lldb::eEncodingInvalid:
1072     error.SetErrorString("invalid encoding");
1073     break;
1074   case lldb::eEncodingVector:
1075     error.SetErrorString("vector encoding unsupported");
1076     break;
1077   case lldb::eEncodingUint:
1078   case lldb::eEncodingSint: {
1079     if (data.GetByteSize() < byte_size)
1080       return Status("insufficient data");
1081     Type type = GetBestTypeForBitSize(byte_size*8, encoding == lldb::eEncodingSint);
1082     if (type == e_void) {
1083       return Status("unsupported integer byte size: %" PRIu64 "",
1084                     static_cast<uint64_t>(byte_size));
1085     }
1086     m_type = type;
1087     if (data.GetByteOrder() == endian::InlHostByteOrder()) {
1088       m_integer = APInt::getNullValue(8 * byte_size);
1089       llvm::LoadIntFromMemory(m_integer, data.GetDataStart(), byte_size);
1090     } else {
1091       std::vector<uint8_t> buffer(byte_size);
1092       std::copy_n(data.GetDataStart(), byte_size, buffer.rbegin());
1093       llvm::LoadIntFromMemory(m_integer, buffer.data(), byte_size);
1094     }
1095     break;
1096   }
1097   case lldb::eEncodingIEEE754: {
1098     lldb::offset_t offset = 0;
1099 
1100     if (byte_size == sizeof(float))
1101       operator=(data.GetFloat(&offset));
1102     else if (byte_size == sizeof(double))
1103       operator=(data.GetDouble(&offset));
1104     else if (byte_size == sizeof(long double))
1105       operator=(data.GetLongDouble(&offset));
1106     else
1107       error.SetErrorStringWithFormat("unsupported float byte size: %" PRIu64 "",
1108                                      static_cast<uint64_t>(byte_size));
1109   } break;
1110   }
1111 
1112   return error;
1113 }
1114 
1115 bool Scalar::SignExtend(uint32_t sign_bit_pos) {
1116   const uint32_t max_bit_pos = GetByteSize() * 8;
1117 
1118   if (sign_bit_pos < max_bit_pos) {
1119     switch (m_type) {
1120     case Scalar::e_void:
1121     case Scalar::e_float:
1122     case Scalar::e_double:
1123     case Scalar::e_long_double:
1124       return false;
1125 
1126     case Scalar::e_sint:
1127     case Scalar::e_uint:
1128     case Scalar::e_slong:
1129     case Scalar::e_ulong:
1130     case Scalar::e_slonglong:
1131     case Scalar::e_ulonglong:
1132     case Scalar::e_sint128:
1133     case Scalar::e_uint128:
1134     case Scalar::e_sint256:
1135     case Scalar::e_uint256:
1136     case Scalar::e_sint512:
1137     case Scalar::e_uint512:
1138       if (max_bit_pos == sign_bit_pos)
1139         return true;
1140       else if (sign_bit_pos < (max_bit_pos - 1)) {
1141         llvm::APInt sign_bit = llvm::APInt::getSignMask(sign_bit_pos + 1);
1142         llvm::APInt bitwize_and = m_integer & sign_bit;
1143         if (bitwize_and.getBoolValue()) {
1144           const llvm::APInt mask =
1145               ~(sign_bit) + llvm::APInt(m_integer.getBitWidth(), 1);
1146           m_integer |= mask;
1147         }
1148         return true;
1149       }
1150       break;
1151     }
1152   }
1153   return false;
1154 }
1155 
1156 size_t Scalar::GetAsMemoryData(void *dst, size_t dst_len,
1157                                lldb::ByteOrder dst_byte_order,
1158                                Status &error) const {
1159   // Get a data extractor that points to the native scalar data
1160   DataExtractor data;
1161   if (!GetData(data)) {
1162     error.SetErrorString("invalid scalar value");
1163     return 0;
1164   }
1165 
1166   const size_t src_len = data.GetByteSize();
1167 
1168   // Prepare a memory buffer that contains some or all of the register value
1169   const size_t bytes_copied =
1170       data.CopyByteOrderedData(0,               // src offset
1171                                src_len,         // src length
1172                                dst,             // dst buffer
1173                                dst_len,         // dst length
1174                                dst_byte_order); // dst byte order
1175   if (bytes_copied == 0)
1176     error.SetErrorString("failed to copy data");
1177 
1178   return bytes_copied;
1179 }
1180 
1181 bool Scalar::ExtractBitfield(uint32_t bit_size, uint32_t bit_offset) {
1182   if (bit_size == 0)
1183     return true;
1184 
1185   switch (m_type) {
1186   case Scalar::e_void:
1187   case Scalar::e_float:
1188   case Scalar::e_double:
1189   case Scalar::e_long_double:
1190     break;
1191 
1192   case Scalar::e_sint:
1193   case Scalar::e_slong:
1194   case Scalar::e_slonglong:
1195   case Scalar::e_sint128:
1196   case Scalar::e_sint256:
1197   case Scalar::e_sint512:
1198     m_integer = m_integer.ashr(bit_offset)
1199                     .sextOrTrunc(bit_size)
1200                     .sextOrSelf(8 * GetByteSize());
1201     return true;
1202 
1203   case Scalar::e_uint:
1204   case Scalar::e_ulong:
1205   case Scalar::e_ulonglong:
1206   case Scalar::e_uint128:
1207   case Scalar::e_uint256:
1208   case Scalar::e_uint512:
1209     m_integer = m_integer.lshr(bit_offset)
1210                     .zextOrTrunc(bit_size)
1211                     .zextOrSelf(8 * GetByteSize());
1212     return true;
1213   }
1214   return false;
1215 }
1216 
1217 bool lldb_private::operator==(const Scalar &lhs, const Scalar &rhs) {
1218   // If either entry is void then we can just compare the types
1219   if (lhs.m_type == Scalar::e_void || rhs.m_type == Scalar::e_void)
1220     return lhs.m_type == rhs.m_type;
1221 
1222   Scalar temp_value;
1223   const Scalar *a;
1224   const Scalar *b;
1225   llvm::APFloat::cmpResult result;
1226   switch (PromoteToMaxType(lhs, rhs, temp_value, a, b)) {
1227   case Scalar::e_void:
1228     break;
1229   case Scalar::e_sint:
1230   case Scalar::e_uint:
1231   case Scalar::e_slong:
1232   case Scalar::e_ulong:
1233   case Scalar::e_slonglong:
1234   case Scalar::e_ulonglong:
1235   case Scalar::e_sint128:
1236   case Scalar::e_uint128:
1237   case Scalar::e_sint256:
1238   case Scalar::e_uint256:
1239   case Scalar::e_sint512:
1240   case Scalar::e_uint512:
1241     return a->m_integer == b->m_integer;
1242   case Scalar::e_float:
1243   case Scalar::e_double:
1244   case Scalar::e_long_double:
1245     result = a->m_float.compare(b->m_float);
1246     if (result == llvm::APFloat::cmpEqual)
1247       return true;
1248   }
1249   return false;
1250 }
1251 
1252 bool lldb_private::operator!=(const Scalar &lhs, const Scalar &rhs) {
1253   return !(lhs == rhs);
1254 }
1255 
1256 bool lldb_private::operator<(const Scalar &lhs, const Scalar &rhs) {
1257   if (lhs.m_type == Scalar::e_void || rhs.m_type == Scalar::e_void)
1258     return false;
1259 
1260   Scalar temp_value;
1261   const Scalar *a;
1262   const Scalar *b;
1263   llvm::APFloat::cmpResult result;
1264   switch (PromoteToMaxType(lhs, rhs, temp_value, a, b)) {
1265   case Scalar::e_void:
1266     break;
1267   case Scalar::e_sint:
1268   case Scalar::e_slong:
1269   case Scalar::e_slonglong:
1270   case Scalar::e_sint128:
1271   case Scalar::e_sint256:
1272   case Scalar::e_sint512:
1273   case Scalar::e_uint512:
1274     return a->m_integer.slt(b->m_integer);
1275   case Scalar::e_uint:
1276   case Scalar::e_ulong:
1277   case Scalar::e_ulonglong:
1278   case Scalar::e_uint128:
1279   case Scalar::e_uint256:
1280     return a->m_integer.ult(b->m_integer);
1281   case Scalar::e_float:
1282   case Scalar::e_double:
1283   case Scalar::e_long_double:
1284     result = a->m_float.compare(b->m_float);
1285     if (result == llvm::APFloat::cmpLessThan)
1286       return true;
1287   }
1288   return false;
1289 }
1290 
1291 bool lldb_private::operator<=(const Scalar &lhs, const Scalar &rhs) {
1292   return !(rhs < lhs);
1293 }
1294 
1295 bool lldb_private::operator>(const Scalar &lhs, const Scalar &rhs) {
1296   return rhs < lhs;
1297 }
1298 
1299 bool lldb_private::operator>=(const Scalar &lhs, const Scalar &rhs) {
1300   return !(lhs < rhs);
1301 }
1302 
1303 bool Scalar::ClearBit(uint32_t bit) {
1304   switch (m_type) {
1305   case e_void:
1306     break;
1307   case e_sint:
1308   case e_uint:
1309   case e_slong:
1310   case e_ulong:
1311   case e_slonglong:
1312   case e_ulonglong:
1313   case e_sint128:
1314   case e_uint128:
1315   case e_sint256:
1316   case e_uint256:
1317   case e_sint512:
1318   case e_uint512:
1319     m_integer.clearBit(bit);
1320     return true;
1321   case e_float:
1322   case e_double:
1323   case e_long_double:
1324     break;
1325   }
1326   return false;
1327 }
1328 
1329 bool Scalar::SetBit(uint32_t bit) {
1330   switch (m_type) {
1331   case e_void:
1332     break;
1333   case e_sint:
1334   case e_uint:
1335   case e_slong:
1336   case e_ulong:
1337   case e_slonglong:
1338   case e_ulonglong:
1339   case e_sint128:
1340   case e_uint128:
1341   case e_sint256:
1342   case e_uint256:
1343   case e_sint512:
1344   case e_uint512:
1345     m_integer.setBit(bit);
1346     return true;
1347   case e_float:
1348   case e_double:
1349   case e_long_double:
1350     break;
1351   }
1352   return false;
1353 }
1354 
1355 llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &os, const Scalar &scalar) {
1356   StreamString s;
1357   scalar.GetValue(&s, /*show_type*/ true);
1358   return os << s.GetString();
1359 }
1360