1 //===-- Host.cpp - Implement OS Host Concept --------------------*- C++ -*-===//
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 the operating system Host concept.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Support/Host.h"
15 #include "llvm/ADT/SmallSet.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <assert.h>
26 #include <string.h>
27 
28 // Include the platform-specific parts of this class.
29 #ifdef LLVM_ON_UNIX
30 #include "Unix/Host.inc"
31 #endif
32 #ifdef LLVM_ON_WIN32
33 #include "Windows/Host.inc"
34 #endif
35 #ifdef _MSC_VER
36 #include <intrin.h>
37 #endif
38 #if defined(__APPLE__) && (defined(__ppc__) || defined(__powerpc__))
39 #include <mach/host_info.h>
40 #include <mach/mach.h>
41 #include <mach/mach_host.h>
42 #include <mach/machine.h>
43 #endif
44 
45 #define DEBUG_TYPE "host-detection"
46 
47 //===----------------------------------------------------------------------===//
48 //
49 //  Implementations of the CPU detection routines
50 //
51 //===----------------------------------------------------------------------===//
52 
53 using namespace llvm;
54 
55 static std::unique_ptr<llvm::MemoryBuffer>
56     LLVM_ATTRIBUTE_UNUSED getProcCpuinfoContent() {
57   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
58       llvm::MemoryBuffer::getFileAsStream("/proc/cpuinfo");
59   if (std::error_code EC = Text.getError()) {
60     llvm::errs() << "Can't read "
61                  << "/proc/cpuinfo: " << EC.message() << "\n";
62     return nullptr;
63   }
64   return std::move(*Text);
65 }
66 
67 StringRef sys::detail::getHostCPUNameForPowerPC(
68     const StringRef &ProcCpuinfoContent) {
69   // Access to the Processor Version Register (PVR) on PowerPC is privileged,
70   // and so we must use an operating-system interface to determine the current
71   // processor type. On Linux, this is exposed through the /proc/cpuinfo file.
72   const char *generic = "generic";
73 
74   // The cpu line is second (after the 'processor: 0' line), so if this
75   // buffer is too small then something has changed (or is wrong).
76   StringRef::const_iterator CPUInfoStart = ProcCpuinfoContent.begin();
77   StringRef::const_iterator CPUInfoEnd = ProcCpuinfoContent.end();
78 
79   StringRef::const_iterator CIP = CPUInfoStart;
80 
81   StringRef::const_iterator CPUStart = 0;
82   size_t CPULen = 0;
83 
84   // We need to find the first line which starts with cpu, spaces, and a colon.
85   // After the colon, there may be some additional spaces and then the cpu type.
86   while (CIP < CPUInfoEnd && CPUStart == 0) {
87     if (CIP < CPUInfoEnd && *CIP == '\n')
88       ++CIP;
89 
90     if (CIP < CPUInfoEnd && *CIP == 'c') {
91       ++CIP;
92       if (CIP < CPUInfoEnd && *CIP == 'p') {
93         ++CIP;
94         if (CIP < CPUInfoEnd && *CIP == 'u') {
95           ++CIP;
96           while (CIP < CPUInfoEnd && (*CIP == ' ' || *CIP == '\t'))
97             ++CIP;
98 
99           if (CIP < CPUInfoEnd && *CIP == ':') {
100             ++CIP;
101             while (CIP < CPUInfoEnd && (*CIP == ' ' || *CIP == '\t'))
102               ++CIP;
103 
104             if (CIP < CPUInfoEnd) {
105               CPUStart = CIP;
106               while (CIP < CPUInfoEnd && (*CIP != ' ' && *CIP != '\t' &&
107                                           *CIP != ',' && *CIP != '\n'))
108                 ++CIP;
109               CPULen = CIP - CPUStart;
110             }
111           }
112         }
113       }
114     }
115 
116     if (CPUStart == 0)
117       while (CIP < CPUInfoEnd && *CIP != '\n')
118         ++CIP;
119   }
120 
121   if (CPUStart == 0)
122     return generic;
123 
124   return StringSwitch<const char *>(StringRef(CPUStart, CPULen))
125       .Case("604e", "604e")
126       .Case("604", "604")
127       .Case("7400", "7400")
128       .Case("7410", "7400")
129       .Case("7447", "7400")
130       .Case("7455", "7450")
131       .Case("G4", "g4")
132       .Case("POWER4", "970")
133       .Case("PPC970FX", "970")
134       .Case("PPC970MP", "970")
135       .Case("G5", "g5")
136       .Case("POWER5", "g5")
137       .Case("A2", "a2")
138       .Case("POWER6", "pwr6")
139       .Case("POWER7", "pwr7")
140       .Case("POWER8", "pwr8")
141       .Case("POWER8E", "pwr8")
142       .Case("POWER8NVL", "pwr8")
143       .Case("POWER9", "pwr9")
144       .Default(generic);
145 }
146 
147 StringRef sys::detail::getHostCPUNameForARM(
148     const StringRef &ProcCpuinfoContent) {
149   // The cpuid register on arm is not accessible from user space. On Linux,
150   // it is exposed through the /proc/cpuinfo file.
151 
152   // Read 32 lines from /proc/cpuinfo, which should contain the CPU part line
153   // in all cases.
154   SmallVector<StringRef, 32> Lines;
155   ProcCpuinfoContent.split(Lines, "\n");
156 
157   // Look for the CPU implementer line.
158   StringRef Implementer;
159   StringRef Hardware;
160   for (unsigned I = 0, E = Lines.size(); I != E; ++I) {
161     if (Lines[I].startswith("CPU implementer"))
162       Implementer = Lines[I].substr(15).ltrim("\t :");
163     if (Lines[I].startswith("Hardware"))
164       Hardware = Lines[I].substr(8).ltrim("\t :");
165   }
166 
167   if (Implementer == "0x41") { // ARM Ltd.
168     // MSM8992/8994 may give cpu part for the core that the kernel is running on,
169     // which is undeterministic and wrong. Always return cortex-a53 for these SoC.
170     if (Hardware.endswith("MSM8994") || Hardware.endswith("MSM8996"))
171       return "cortex-a53";
172 
173 
174     // Look for the CPU part line.
175     for (unsigned I = 0, E = Lines.size(); I != E; ++I)
176       if (Lines[I].startswith("CPU part"))
177         // The CPU part is a 3 digit hexadecimal number with a 0x prefix. The
178         // values correspond to the "Part number" in the CP15/c0 register. The
179         // contents are specified in the various processor manuals.
180         return StringSwitch<const char *>(Lines[I].substr(8).ltrim("\t :"))
181             .Case("0x926", "arm926ej-s")
182             .Case("0xb02", "mpcore")
183             .Case("0xb36", "arm1136j-s")
184             .Case("0xb56", "arm1156t2-s")
185             .Case("0xb76", "arm1176jz-s")
186             .Case("0xc08", "cortex-a8")
187             .Case("0xc09", "cortex-a9")
188             .Case("0xc0f", "cortex-a15")
189             .Case("0xc20", "cortex-m0")
190             .Case("0xc23", "cortex-m3")
191             .Case("0xc24", "cortex-m4")
192             .Case("0xd04", "cortex-a35")
193             .Case("0xd03", "cortex-a53")
194             .Case("0xd07", "cortex-a57")
195             .Case("0xd08", "cortex-a72")
196             .Case("0xd09", "cortex-a73")
197             .Default("generic");
198   }
199 
200   if (Implementer == "0x51") // Qualcomm Technologies, Inc.
201     // Look for the CPU part line.
202     for (unsigned I = 0, E = Lines.size(); I != E; ++I)
203       if (Lines[I].startswith("CPU part"))
204         // The CPU part is a 3 digit hexadecimal number with a 0x prefix. The
205         // values correspond to the "Part number" in the CP15/c0 register. The
206         // contents are specified in the various processor manuals.
207         return StringSwitch<const char *>(Lines[I].substr(8).ltrim("\t :"))
208             .Case("0x06f", "krait") // APQ8064
209             .Case("0x201", "kryo")
210             .Case("0x205", "kryo")
211             .Default("generic");
212 
213   return "generic";
214 }
215 
216 StringRef sys::detail::getHostCPUNameForS390x(
217     const StringRef &ProcCpuinfoContent) {
218   // STIDP is a privileged operation, so use /proc/cpuinfo instead.
219 
220   // The "processor 0:" line comes after a fair amount of other information,
221   // including a cache breakdown, but this should be plenty.
222   SmallVector<StringRef, 32> Lines;
223   ProcCpuinfoContent.split(Lines, "\n");
224 
225   // Look for the CPU features.
226   SmallVector<StringRef, 32> CPUFeatures;
227   for (unsigned I = 0, E = Lines.size(); I != E; ++I)
228     if (Lines[I].startswith("features")) {
229       size_t Pos = Lines[I].find(":");
230       if (Pos != StringRef::npos) {
231         Lines[I].drop_front(Pos + 1).split(CPUFeatures, ' ');
232         break;
233       }
234     }
235 
236   // We need to check for the presence of vector support independently of
237   // the machine type, since we may only use the vector register set when
238   // supported by the kernel (and hypervisor).
239   bool HaveVectorSupport = false;
240   for (unsigned I = 0, E = CPUFeatures.size(); I != E; ++I) {
241     if (CPUFeatures[I] == "vx")
242       HaveVectorSupport = true;
243   }
244 
245   // Now check the processor machine type.
246   for (unsigned I = 0, E = Lines.size(); I != E; ++I) {
247     if (Lines[I].startswith("processor ")) {
248       size_t Pos = Lines[I].find("machine = ");
249       if (Pos != StringRef::npos) {
250         Pos += sizeof("machine = ") - 1;
251         unsigned int Id;
252         if (!Lines[I].drop_front(Pos).getAsInteger(10, Id)) {
253           if (Id >= 2964 && HaveVectorSupport)
254             return "z13";
255           if (Id >= 2827)
256             return "zEC12";
257           if (Id >= 2817)
258             return "z196";
259         }
260       }
261       break;
262     }
263   }
264 
265   return "generic";
266 }
267 
268 #if defined(__i386__) || defined(_M_IX86) || \
269     defined(__x86_64__) || defined(_M_X64)
270 
271 enum VendorSignatures {
272   SIG_INTEL = 0x756e6547 /* Genu */,
273   SIG_AMD = 0x68747541 /* Auth */
274 };
275 
276 enum ProcessorVendors {
277   VENDOR_INTEL = 1,
278   VENDOR_AMD,
279   VENDOR_OTHER,
280   VENDOR_MAX
281 };
282 
283 enum ProcessorTypes {
284   INTEL_ATOM = 1,
285   INTEL_CORE2,
286   INTEL_COREI7,
287   AMDFAM10H,
288   AMDFAM15H,
289   INTEL_i386,
290   INTEL_i486,
291   INTEL_PENTIUM,
292   INTEL_PENTIUM_PRO,
293   INTEL_PENTIUM_II,
294   INTEL_PENTIUM_III,
295   INTEL_PENTIUM_IV,
296   INTEL_PENTIUM_M,
297   INTEL_CORE_DUO,
298   INTEL_XEONPHI,
299   INTEL_X86_64,
300   INTEL_NOCONA,
301   INTEL_PRESCOTT,
302   AMD_i486,
303   AMDPENTIUM,
304   AMDATHLON,
305   AMDFAM14H,
306   AMDFAM16H,
307   AMDFAM17H,
308   CPU_TYPE_MAX
309 };
310 
311 enum ProcessorSubtypes {
312   INTEL_COREI7_NEHALEM = 1,
313   INTEL_COREI7_WESTMERE,
314   INTEL_COREI7_SANDYBRIDGE,
315   AMDFAM10H_BARCELONA,
316   AMDFAM10H_SHANGHAI,
317   AMDFAM10H_ISTANBUL,
318   AMDFAM15H_BDVER1,
319   AMDFAM15H_BDVER2,
320   INTEL_PENTIUM_MMX,
321   INTEL_CORE2_65,
322   INTEL_CORE2_45,
323   INTEL_COREI7_IVYBRIDGE,
324   INTEL_COREI7_HASWELL,
325   INTEL_COREI7_BROADWELL,
326   INTEL_COREI7_SKYLAKE,
327   INTEL_COREI7_SKYLAKE_AVX512,
328   INTEL_ATOM_BONNELL,
329   INTEL_ATOM_SILVERMONT,
330   INTEL_ATOM_GOLDMONT,
331   INTEL_KNIGHTS_LANDING,
332   AMDPENTIUM_K6,
333   AMDPENTIUM_K62,
334   AMDPENTIUM_K63,
335   AMDPENTIUM_GEODE,
336   AMDATHLON_TBIRD,
337   AMDATHLON_MP,
338   AMDATHLON_XP,
339   AMDATHLON_K8SSE3,
340   AMDATHLON_OPTERON,
341   AMDATHLON_FX,
342   AMDATHLON_64,
343   AMD_BTVER1,
344   AMD_BTVER2,
345   AMDFAM15H_BDVER3,
346   AMDFAM15H_BDVER4,
347   AMDFAM17H_ZNVER1,
348   CPU_SUBTYPE_MAX
349 };
350 
351 enum ProcessorFeatures {
352   FEATURE_CMOV = 0,
353   FEATURE_MMX,
354   FEATURE_POPCNT,
355   FEATURE_SSE,
356   FEATURE_SSE2,
357   FEATURE_SSE3,
358   FEATURE_SSSE3,
359   FEATURE_SSE4_1,
360   FEATURE_SSE4_2,
361   FEATURE_AVX,
362   FEATURE_AVX2,
363   FEATURE_AVX512,
364   FEATURE_AVX512SAVE,
365   FEATURE_MOVBE,
366   FEATURE_ADX,
367   FEATURE_EM64T
368 };
369 
370 // The check below for i386 was copied from clang's cpuid.h (__get_cpuid_max).
371 // Check motivated by bug reports for OpenSSL crashing on CPUs without CPUID
372 // support. Consequently, for i386, the presence of CPUID is checked first
373 // via the corresponding eflags bit.
374 // Removal of cpuid.h header motivated by PR30384
375 // Header cpuid.h and method __get_cpuid_max are not used in llvm, clang, openmp
376 // or test-suite, but are used in external projects e.g. libstdcxx
377 static bool isCpuIdSupported() {
378 #if defined(__GNUC__) || defined(__clang__)
379 #if defined(__i386__)
380   int __cpuid_supported;
381   __asm__("  pushfl\n"
382           "  popl   %%eax\n"
383           "  movl   %%eax,%%ecx\n"
384           "  xorl   $0x00200000,%%eax\n"
385           "  pushl  %%eax\n"
386           "  popfl\n"
387           "  pushfl\n"
388           "  popl   %%eax\n"
389           "  movl   $0,%0\n"
390           "  cmpl   %%eax,%%ecx\n"
391           "  je     1f\n"
392           "  movl   $1,%0\n"
393           "1:"
394           : "=r"(__cpuid_supported)
395           :
396           : "eax", "ecx");
397   if (!__cpuid_supported)
398     return false;
399 #endif
400   return true;
401 #endif
402   return true;
403 }
404 
405 /// getX86CpuIDAndInfo - Execute the specified cpuid and return the 4 values in
406 /// the specified arguments.  If we can't run cpuid on the host, return true.
407 static bool getX86CpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX,
408                                unsigned *rECX, unsigned *rEDX) {
409 #if defined(__GNUC__) || defined(__clang__)
410 #if defined(__x86_64__)
411   // gcc doesn't know cpuid would clobber ebx/rbx. Preserve it manually.
412   // FIXME: should we save this for Clang?
413   __asm__("movq\t%%rbx, %%rsi\n\t"
414           "cpuid\n\t"
415           "xchgq\t%%rbx, %%rsi\n\t"
416           : "=a"(*rEAX), "=S"(*rEBX), "=c"(*rECX), "=d"(*rEDX)
417           : "a"(value));
418   return false;
419 #elif defined(__i386__)
420   __asm__("movl\t%%ebx, %%esi\n\t"
421           "cpuid\n\t"
422           "xchgl\t%%ebx, %%esi\n\t"
423           : "=a"(*rEAX), "=S"(*rEBX), "=c"(*rECX), "=d"(*rEDX)
424           : "a"(value));
425   return false;
426 #else
427   return true;
428 #endif
429 #elif defined(_MSC_VER)
430   // The MSVC intrinsic is portable across x86 and x64.
431   int registers[4];
432   __cpuid(registers, value);
433   *rEAX = registers[0];
434   *rEBX = registers[1];
435   *rECX = registers[2];
436   *rEDX = registers[3];
437   return false;
438 #else
439   return true;
440 #endif
441 }
442 
443 /// getX86CpuIDAndInfoEx - Execute the specified cpuid with subleaf and return
444 /// the 4 values in the specified arguments.  If we can't run cpuid on the host,
445 /// return true.
446 static bool getX86CpuIDAndInfoEx(unsigned value, unsigned subleaf,
447                                  unsigned *rEAX, unsigned *rEBX, unsigned *rECX,
448                                  unsigned *rEDX) {
449 #if defined(__x86_64__) || defined(_M_X64)
450 #if defined(__GNUC__) || defined(__clang__)
451   // gcc doesn't know cpuid would clobber ebx/rbx. Preserve it manually.
452   // FIXME: should we save this for Clang?
453   __asm__("movq\t%%rbx, %%rsi\n\t"
454           "cpuid\n\t"
455           "xchgq\t%%rbx, %%rsi\n\t"
456           : "=a"(*rEAX), "=S"(*rEBX), "=c"(*rECX), "=d"(*rEDX)
457           : "a"(value), "c"(subleaf));
458   return false;
459 #elif defined(_MSC_VER)
460   int registers[4];
461   __cpuidex(registers, value, subleaf);
462   *rEAX = registers[0];
463   *rEBX = registers[1];
464   *rECX = registers[2];
465   *rEDX = registers[3];
466   return false;
467 #else
468   return true;
469 #endif
470 #elif defined(__i386__) || defined(_M_IX86)
471 #if defined(__GNUC__) || defined(__clang__)
472   __asm__("movl\t%%ebx, %%esi\n\t"
473           "cpuid\n\t"
474           "xchgl\t%%ebx, %%esi\n\t"
475           : "=a"(*rEAX), "=S"(*rEBX), "=c"(*rECX), "=d"(*rEDX)
476           : "a"(value), "c"(subleaf));
477   return false;
478 #elif defined(_MSC_VER)
479   __asm {
480       mov   eax,value
481       mov   ecx,subleaf
482       cpuid
483       mov   esi,rEAX
484       mov   dword ptr [esi],eax
485       mov   esi,rEBX
486       mov   dword ptr [esi],ebx
487       mov   esi,rECX
488       mov   dword ptr [esi],ecx
489       mov   esi,rEDX
490       mov   dword ptr [esi],edx
491   }
492   return false;
493 #else
494   return true;
495 #endif
496 #else
497   return true;
498 #endif
499 }
500 
501 static bool getX86XCR0(unsigned *rEAX, unsigned *rEDX) {
502 #if defined(__GNUC__) || defined(__clang__)
503   // Check xgetbv; this uses a .byte sequence instead of the instruction
504   // directly because older assemblers do not include support for xgetbv and
505   // there is no easy way to conditionally compile based on the assembler used.
506   __asm__(".byte 0x0f, 0x01, 0xd0" : "=a"(*rEAX), "=d"(*rEDX) : "c"(0));
507   return false;
508 #elif defined(_MSC_FULL_VER) && defined(_XCR_XFEATURE_ENABLED_MASK)
509   unsigned long long Result = _xgetbv(_XCR_XFEATURE_ENABLED_MASK);
510   *rEAX = Result;
511   *rEDX = Result >> 32;
512   return false;
513 #else
514   return true;
515 #endif
516 }
517 
518 static void detectX86FamilyModel(unsigned EAX, unsigned *Family,
519                                  unsigned *Model) {
520   *Family = (EAX >> 8) & 0xf; // Bits 8 - 11
521   *Model = (EAX >> 4) & 0xf;  // Bits 4 - 7
522   if (*Family == 6 || *Family == 0xf) {
523     if (*Family == 0xf)
524       // Examine extended family ID if family ID is F.
525       *Family += (EAX >> 20) & 0xff; // Bits 20 - 27
526     // Examine extended model ID if family ID is 6 or F.
527     *Model += ((EAX >> 16) & 0xf) << 4; // Bits 16 - 19
528   }
529 }
530 
531 static void
532 getIntelProcessorTypeAndSubtype(unsigned Family, unsigned Model,
533                                 unsigned Brand_id, unsigned Features,
534                                 unsigned *Type, unsigned *Subtype) {
535   if (Brand_id != 0)
536     return;
537   switch (Family) {
538   case 3:
539     *Type = INTEL_i386;
540     break;
541   case 4:
542     switch (Model) {
543     case 0: // Intel486 DX processors
544     case 1: // Intel486 DX processors
545     case 2: // Intel486 SX processors
546     case 3: // Intel487 processors, IntelDX2 OverDrive processors,
547             // IntelDX2 processors
548     case 4: // Intel486 SL processor
549     case 5: // IntelSX2 processors
550     case 7: // Write-Back Enhanced IntelDX2 processors
551     case 8: // IntelDX4 OverDrive processors, IntelDX4 processors
552     default:
553       *Type = INTEL_i486;
554       break;
555     }
556     break;
557   case 5:
558     switch (Model) {
559     case 1: // Pentium OverDrive processor for Pentium processor (60, 66),
560             // Pentium processors (60, 66)
561     case 2: // Pentium OverDrive processor for Pentium processor (75, 90,
562             // 100, 120, 133), Pentium processors (75, 90, 100, 120, 133,
563             // 150, 166, 200)
564     case 3: // Pentium OverDrive processors for Intel486 processor-based
565             // systems
566       *Type = INTEL_PENTIUM;
567       break;
568     case 4: // Pentium OverDrive processor with MMX technology for Pentium
569             // processor (75, 90, 100, 120, 133), Pentium processor with
570             // MMX technology (166, 200)
571       *Type = INTEL_PENTIUM;
572       *Subtype = INTEL_PENTIUM_MMX;
573       break;
574     default:
575       *Type = INTEL_PENTIUM;
576       break;
577     }
578     break;
579   case 6:
580     switch (Model) {
581     case 0x01: // Pentium Pro processor
582       *Type = INTEL_PENTIUM_PRO;
583       break;
584     case 0x03: // Intel Pentium II OverDrive processor, Pentium II processor,
585                // model 03
586     case 0x05: // Pentium II processor, model 05, Pentium II Xeon processor,
587                // model 05, and Intel Celeron processor, model 05
588     case 0x06: // Celeron processor, model 06
589       *Type = INTEL_PENTIUM_II;
590       break;
591     case 0x07: // Pentium III processor, model 07, and Pentium III Xeon
592                // processor, model 07
593     case 0x08: // Pentium III processor, model 08, Pentium III Xeon processor,
594                // model 08, and Celeron processor, model 08
595     case 0x0a: // Pentium III Xeon processor, model 0Ah
596     case 0x0b: // Pentium III processor, model 0Bh
597       *Type = INTEL_PENTIUM_III;
598       break;
599     case 0x09: // Intel Pentium M processor, Intel Celeron M processor model 09.
600     case 0x0d: // Intel Pentium M processor, Intel Celeron M processor, model
601                // 0Dh. All processors are manufactured using the 90 nm process.
602     case 0x15: // Intel EP80579 Integrated Processor and Intel EP80579
603                // Integrated Processor with Intel QuickAssist Technology
604       *Type = INTEL_PENTIUM_M;
605       break;
606     case 0x0e: // Intel Core Duo processor, Intel Core Solo processor, model
607                // 0Eh. All processors are manufactured using the 65 nm process.
608       *Type = INTEL_CORE_DUO;
609       break;   // yonah
610     case 0x0f: // Intel Core 2 Duo processor, Intel Core 2 Duo mobile
611                // processor, Intel Core 2 Quad processor, Intel Core 2 Quad
612                // mobile processor, Intel Core 2 Extreme processor, Intel
613                // Pentium Dual-Core processor, Intel Xeon processor, model
614                // 0Fh. All processors are manufactured using the 65 nm process.
615     case 0x16: // Intel Celeron processor model 16h. All processors are
616                // manufactured using the 65 nm process
617       *Type = INTEL_CORE2; // "core2"
618       *Subtype = INTEL_CORE2_65;
619       break;
620     case 0x17: // Intel Core 2 Extreme processor, Intel Xeon processor, model
621                // 17h. All processors are manufactured using the 45 nm process.
622                //
623                // 45nm: Penryn , Wolfdale, Yorkfield (XE)
624     case 0x1d: // Intel Xeon processor MP. All processors are manufactured using
625                // the 45 nm process.
626       *Type = INTEL_CORE2; // "penryn"
627       *Subtype = INTEL_CORE2_45;
628       break;
629     case 0x1a: // Intel Core i7 processor and Intel Xeon processor. All
630                // processors are manufactured using the 45 nm process.
631     case 0x1e: // Intel(R) Core(TM) i7 CPU         870  @ 2.93GHz.
632                // As found in a Summer 2010 model iMac.
633     case 0x1f:
634     case 0x2e:             // Nehalem EX
635       *Type = INTEL_COREI7; // "nehalem"
636       *Subtype = INTEL_COREI7_NEHALEM;
637       break;
638     case 0x25: // Intel Core i7, laptop version.
639     case 0x2c: // Intel Core i7 processor and Intel Xeon processor. All
640                // processors are manufactured using the 32 nm process.
641     case 0x2f: // Westmere EX
642       *Type = INTEL_COREI7; // "westmere"
643       *Subtype = INTEL_COREI7_WESTMERE;
644       break;
645     case 0x2a: // Intel Core i7 processor. All processors are manufactured
646                // using the 32 nm process.
647     case 0x2d:
648       *Type = INTEL_COREI7; //"sandybridge"
649       *Subtype = INTEL_COREI7_SANDYBRIDGE;
650       break;
651     case 0x3a:
652     case 0x3e:             // Ivy Bridge EP
653       *Type = INTEL_COREI7; // "ivybridge"
654       *Subtype = INTEL_COREI7_IVYBRIDGE;
655       break;
656 
657     // Haswell:
658     case 0x3c:
659     case 0x3f:
660     case 0x45:
661     case 0x46:
662       *Type = INTEL_COREI7; // "haswell"
663       *Subtype = INTEL_COREI7_HASWELL;
664       break;
665 
666     // Broadwell:
667     case 0x3d:
668     case 0x47:
669     case 0x4f:
670     case 0x56:
671       *Type = INTEL_COREI7; // "broadwell"
672       *Subtype = INTEL_COREI7_BROADWELL;
673       break;
674 
675     // Skylake:
676     case 0x4e: // Skylake mobile
677     case 0x5e: // Skylake desktop
678     case 0x8e: // Kaby Lake mobile
679     case 0x9e: // Kaby Lake desktop
680       *Type = INTEL_COREI7; // "skylake"
681       *Subtype = INTEL_COREI7_SKYLAKE;
682       break;
683 
684     // Skylake Xeon:
685     case 0x55:
686       *Type = INTEL_COREI7;
687       *Subtype = INTEL_COREI7_SKYLAKE_AVX512; // "skylake-avx512"
688       break;
689 
690     case 0x1c: // Most 45 nm Intel Atom processors
691     case 0x26: // 45 nm Atom Lincroft
692     case 0x27: // 32 nm Atom Medfield
693     case 0x35: // 32 nm Atom Midview
694     case 0x36: // 32 nm Atom Midview
695       *Type = INTEL_ATOM;
696       *Subtype = INTEL_ATOM_BONNELL;
697       break; // "bonnell"
698 
699     // Atom Silvermont codes from the Intel software optimization guide.
700     case 0x37:
701     case 0x4a:
702     case 0x4d:
703     case 0x5a:
704     case 0x5d:
705     case 0x4c: // really airmont
706       *Type = INTEL_ATOM;
707       *Subtype = INTEL_ATOM_SILVERMONT;
708       break; // "silvermont"
709     // Goldmont:
710     case 0x5c:
711     case 0x5f:
712       *Type = INTEL_ATOM;
713       *Subtype = INTEL_ATOM_GOLDMONT;
714       break; // "goldmont"
715     case 0x57:
716       *Type = INTEL_XEONPHI; // knl
717       *Subtype = INTEL_KNIGHTS_LANDING;
718       break;
719 
720     default: // Unknown family 6 CPU, try to guess.
721       if (Features & (1 << FEATURE_AVX512)) {
722         *Type = INTEL_XEONPHI; // knl
723         *Subtype = INTEL_KNIGHTS_LANDING;
724         break;
725       }
726       if (Features & (1 << FEATURE_ADX)) {
727         *Type = INTEL_COREI7;
728         *Subtype = INTEL_COREI7_BROADWELL;
729         break;
730       }
731       if (Features & (1 << FEATURE_AVX2)) {
732         *Type = INTEL_COREI7;
733         *Subtype = INTEL_COREI7_HASWELL;
734         break;
735       }
736       if (Features & (1 << FEATURE_AVX)) {
737         *Type = INTEL_COREI7;
738         *Subtype = INTEL_COREI7_SANDYBRIDGE;
739         break;
740       }
741       if (Features & (1 << FEATURE_SSE4_2)) {
742         if (Features & (1 << FEATURE_MOVBE)) {
743           *Type = INTEL_ATOM;
744           *Subtype = INTEL_ATOM_SILVERMONT;
745         } else {
746           *Type = INTEL_COREI7;
747           *Subtype = INTEL_COREI7_NEHALEM;
748         }
749         break;
750       }
751       if (Features & (1 << FEATURE_SSE4_1)) {
752         *Type = INTEL_CORE2; // "penryn"
753         *Subtype = INTEL_CORE2_45;
754         break;
755       }
756       if (Features & (1 << FEATURE_SSSE3)) {
757         if (Features & (1 << FEATURE_MOVBE)) {
758           *Type = INTEL_ATOM;
759           *Subtype = INTEL_ATOM_BONNELL; // "bonnell"
760         } else {
761           *Type = INTEL_CORE2; // "core2"
762           *Subtype = INTEL_CORE2_65;
763         }
764         break;
765       }
766       if (Features & (1 << FEATURE_EM64T)) {
767         *Type = INTEL_X86_64;
768         break; // x86-64
769       }
770       if (Features & (1 << FEATURE_SSE2)) {
771         *Type = INTEL_PENTIUM_M;
772         break;
773       }
774       if (Features & (1 << FEATURE_SSE)) {
775         *Type = INTEL_PENTIUM_III;
776         break;
777       }
778       if (Features & (1 << FEATURE_MMX)) {
779         *Type = INTEL_PENTIUM_II;
780         break;
781       }
782       *Type = INTEL_PENTIUM_PRO;
783       break;
784     }
785     break;
786   case 15: {
787     switch (Model) {
788     case 0: // Pentium 4 processor, Intel Xeon processor. All processors are
789             // model 00h and manufactured using the 0.18 micron process.
790     case 1: // Pentium 4 processor, Intel Xeon processor, Intel Xeon
791             // processor MP, and Intel Celeron processor. All processors are
792             // model 01h and manufactured using the 0.18 micron process.
793     case 2: // Pentium 4 processor, Mobile Intel Pentium 4 processor - M,
794             // Intel Xeon processor, Intel Xeon processor MP, Intel Celeron
795             // processor, and Mobile Intel Celeron processor. All processors
796             // are model 02h and manufactured using the 0.13 micron process.
797       *Type =
798           ((Features & (1 << FEATURE_EM64T)) ? INTEL_X86_64 : INTEL_PENTIUM_IV);
799       break;
800 
801     case 3: // Pentium 4 processor, Intel Xeon processor, Intel Celeron D
802             // processor. All processors are model 03h and manufactured using
803             // the 90 nm process.
804     case 4: // Pentium 4 processor, Pentium 4 processor Extreme Edition,
805             // Pentium D processor, Intel Xeon processor, Intel Xeon
806             // processor MP, Intel Celeron D processor. All processors are
807             // model 04h and manufactured using the 90 nm process.
808     case 6: // Pentium 4 processor, Pentium D processor, Pentium processor
809             // Extreme Edition, Intel Xeon processor, Intel Xeon processor
810             // MP, Intel Celeron D processor. All processors are model 06h
811             // and manufactured using the 65 nm process.
812       *Type =
813           ((Features & (1 << FEATURE_EM64T)) ? INTEL_NOCONA : INTEL_PRESCOTT);
814       break;
815 
816     default:
817       *Type =
818           ((Features & (1 << FEATURE_EM64T)) ? INTEL_X86_64 : INTEL_PENTIUM_IV);
819       break;
820     }
821     break;
822   }
823   default:
824     break; /*"generic"*/
825   }
826 }
827 
828 static void getAMDProcessorTypeAndSubtype(unsigned Family, unsigned Model,
829                                           unsigned Features, unsigned *Type,
830                                           unsigned *Subtype) {
831   // FIXME: this poorly matches the generated SubtargetFeatureKV table.  There
832   // appears to be no way to generate the wide variety of AMD-specific targets
833   // from the information returned from CPUID.
834   switch (Family) {
835   case 4:
836     *Type = AMD_i486;
837     break;
838   case 5:
839     *Type = AMDPENTIUM;
840     switch (Model) {
841     case 6:
842     case 7:
843       *Subtype = AMDPENTIUM_K6;
844       break; // "k6"
845     case 8:
846       *Subtype = AMDPENTIUM_K62;
847       break; // "k6-2"
848     case 9:
849     case 13:
850       *Subtype = AMDPENTIUM_K63;
851       break; // "k6-3"
852     case 10:
853       *Subtype = AMDPENTIUM_GEODE;
854       break; // "geode"
855     }
856     break;
857   case 6:
858     *Type = AMDATHLON;
859     switch (Model) {
860     case 4:
861       *Subtype = AMDATHLON_TBIRD;
862       break; // "athlon-tbird"
863     case 6:
864     case 7:
865     case 8:
866       *Subtype = AMDATHLON_MP;
867       break; // "athlon-mp"
868     case 10:
869       *Subtype = AMDATHLON_XP;
870       break; // "athlon-xp"
871     }
872     break;
873   case 15:
874     *Type = AMDATHLON;
875     if (Features & (1 << FEATURE_SSE3)) {
876       *Subtype = AMDATHLON_K8SSE3;
877       break; // "k8-sse3"
878     }
879     switch (Model) {
880     case 1:
881       *Subtype = AMDATHLON_OPTERON;
882       break; // "opteron"
883     case 5:
884       *Subtype = AMDATHLON_FX;
885       break; // "athlon-fx"; also opteron
886     default:
887       *Subtype = AMDATHLON_64;
888       break; // "athlon64"
889     }
890     break;
891   case 16:
892     *Type = AMDFAM10H; // "amdfam10"
893     switch (Model) {
894     case 2:
895       *Subtype = AMDFAM10H_BARCELONA;
896       break;
897     case 4:
898       *Subtype = AMDFAM10H_SHANGHAI;
899       break;
900     case 8:
901       *Subtype = AMDFAM10H_ISTANBUL;
902       break;
903     }
904     break;
905   case 20:
906     *Type = AMDFAM14H;
907     *Subtype = AMD_BTVER1;
908     break; // "btver1";
909   case 21:
910     *Type = AMDFAM15H;
911     if (Model >= 0x60 && Model <= 0x7f) {
912       *Subtype = AMDFAM15H_BDVER4;
913       break; // "bdver4"; 50h-6Fh: Excavator
914     }
915     if (Model >= 0x30 && Model <= 0x3f) {
916       *Subtype = AMDFAM15H_BDVER3;
917       break; // "bdver3"; 30h-3Fh: Steamroller
918     }
919     if (Model >= 0x10 && Model <= 0x1f) {
920       *Subtype = AMDFAM15H_BDVER2;
921       break; // "bdver2"; 10h-1Fh: Piledriver
922     }
923     if (Model <= 0x0f) {
924       *Subtype = AMDFAM15H_BDVER1;
925       break; // "bdver1"; 00h-0Fh: Bulldozer
926     }
927     break;
928   case 22:
929     *Type = AMDFAM16H;
930     *Subtype = AMD_BTVER2;
931     break; // "btver2"
932   case 23:
933     *Type = AMDFAM17H;
934     *Subtype = AMDFAM17H_ZNVER1;
935     break;
936   default:
937     break; // "generic"
938   }
939 }
940 
941 static unsigned getAvailableFeatures(unsigned ECX, unsigned EDX,
942                                      unsigned MaxLeaf) {
943   unsigned Features = 0;
944   unsigned EAX, EBX;
945   Features |= (((EDX >> 23) & 1) << FEATURE_MMX);
946   Features |= (((EDX >> 25) & 1) << FEATURE_SSE);
947   Features |= (((EDX >> 26) & 1) << FEATURE_SSE2);
948   Features |= (((ECX >> 0) & 1) << FEATURE_SSE3);
949   Features |= (((ECX >> 9) & 1) << FEATURE_SSSE3);
950   Features |= (((ECX >> 19) & 1) << FEATURE_SSE4_1);
951   Features |= (((ECX >> 20) & 1) << FEATURE_SSE4_2);
952   Features |= (((ECX >> 22) & 1) << FEATURE_MOVBE);
953 
954   // If CPUID indicates support for XSAVE, XRESTORE and AVX, and XGETBV
955   // indicates that the AVX registers will be saved and restored on context
956   // switch, then we have full AVX support.
957   const unsigned AVXBits = (1 << 27) | (1 << 28);
958   bool HasAVX = ((ECX & AVXBits) == AVXBits) && !getX86XCR0(&EAX, &EDX) &&
959                 ((EAX & 0x6) == 0x6);
960   bool HasAVX512Save = HasAVX && ((EAX & 0xe0) == 0xe0);
961   bool HasLeaf7 =
962       MaxLeaf >= 0x7 && !getX86CpuIDAndInfoEx(0x7, 0x0, &EAX, &EBX, &ECX, &EDX);
963   bool HasADX = HasLeaf7 && ((EBX >> 19) & 1);
964   bool HasAVX2 = HasAVX && HasLeaf7 && (EBX & 0x20);
965   bool HasAVX512 = HasLeaf7 && HasAVX512Save && ((EBX >> 16) & 1);
966   Features |= (HasAVX << FEATURE_AVX);
967   Features |= (HasAVX2 << FEATURE_AVX2);
968   Features |= (HasAVX512 << FEATURE_AVX512);
969   Features |= (HasAVX512Save << FEATURE_AVX512SAVE);
970   Features |= (HasADX << FEATURE_ADX);
971 
972   unsigned MaxExtLevel;
973   getX86CpuIDAndInfo(0x80000000, &MaxExtLevel, &EBX, &ECX, &EDX);
974 
975   bool HasExtLeaf1 = MaxExtLevel >= 0x80000001 &&
976                      !getX86CpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
977   if (HasExtLeaf1)
978     Features |= (((EDX >> 29) & 0x1) << FEATURE_EM64T);
979 
980   return Features;
981 }
982 
983 StringRef sys::getHostCPUName() {
984   unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
985   unsigned MaxLeaf, Vendor;
986 
987 #if defined(__GNUC__) || defined(__clang__)
988   //FIXME: include cpuid.h from clang or copy __get_cpuid_max here
989   // and simplify it to not invoke __cpuid (like cpu_model.c in
990   // compiler-rt/lib/builtins/cpu_model.c?
991   // Opting for the second option.
992   if(!isCpuIdSupported())
993     return "generic";
994 #endif
995   if (getX86CpuIDAndInfo(0, &MaxLeaf, &Vendor, &ECX, &EDX) || MaxLeaf < 1)
996     return "generic";
997   getX86CpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
998 
999   unsigned Brand_id = EBX & 0xff;
1000   unsigned Family = 0, Model = 0;
1001   unsigned Features = 0;
1002   detectX86FamilyModel(EAX, &Family, &Model);
1003   Features = getAvailableFeatures(ECX, EDX, MaxLeaf);
1004 
1005   unsigned Type;
1006   unsigned Subtype;
1007 
1008   if (Vendor == SIG_INTEL) {
1009     getIntelProcessorTypeAndSubtype(Family, Model, Brand_id, Features, &Type,
1010                                     &Subtype);
1011     switch (Type) {
1012     case INTEL_i386:
1013       return "i386";
1014     case INTEL_i486:
1015       return "i486";
1016     case INTEL_PENTIUM:
1017       if (Subtype == INTEL_PENTIUM_MMX)
1018         return "pentium-mmx";
1019       return "pentium";
1020     case INTEL_PENTIUM_PRO:
1021       return "pentiumpro";
1022     case INTEL_PENTIUM_II:
1023       return "pentium2";
1024     case INTEL_PENTIUM_III:
1025       return "pentium3";
1026     case INTEL_PENTIUM_IV:
1027       return "pentium4";
1028     case INTEL_PENTIUM_M:
1029       return "pentium-m";
1030     case INTEL_CORE_DUO:
1031       return "yonah";
1032     case INTEL_CORE2:
1033       switch (Subtype) {
1034       case INTEL_CORE2_65:
1035         return "core2";
1036       case INTEL_CORE2_45:
1037         return "penryn";
1038       default:
1039         return "core2";
1040       }
1041     case INTEL_COREI7:
1042       switch (Subtype) {
1043       case INTEL_COREI7_NEHALEM:
1044         return "nehalem";
1045       case INTEL_COREI7_WESTMERE:
1046         return "westmere";
1047       case INTEL_COREI7_SANDYBRIDGE:
1048         return "sandybridge";
1049       case INTEL_COREI7_IVYBRIDGE:
1050         return "ivybridge";
1051       case INTEL_COREI7_HASWELL:
1052         return "haswell";
1053       case INTEL_COREI7_BROADWELL:
1054         return "broadwell";
1055       case INTEL_COREI7_SKYLAKE:
1056         return "skylake";
1057       case INTEL_COREI7_SKYLAKE_AVX512:
1058         return "skylake-avx512";
1059       default:
1060         return "corei7";
1061       }
1062     case INTEL_ATOM:
1063       switch (Subtype) {
1064       case INTEL_ATOM_BONNELL:
1065         return "bonnell";
1066       case INTEL_ATOM_GOLDMONT:
1067         return "goldmont";
1068       case INTEL_ATOM_SILVERMONT:
1069         return "silvermont";
1070       default:
1071         return "atom";
1072       }
1073     case INTEL_XEONPHI:
1074       return "knl"; /*update for more variants added*/
1075     case INTEL_X86_64:
1076       return "x86-64";
1077     case INTEL_NOCONA:
1078       return "nocona";
1079     case INTEL_PRESCOTT:
1080       return "prescott";
1081     default:
1082       return "generic";
1083     }
1084   } else if (Vendor == SIG_AMD) {
1085     getAMDProcessorTypeAndSubtype(Family, Model, Features, &Type, &Subtype);
1086     switch (Type) {
1087     case AMD_i486:
1088       return "i486";
1089     case AMDPENTIUM:
1090       switch (Subtype) {
1091       case AMDPENTIUM_K6:
1092         return "k6";
1093       case AMDPENTIUM_K62:
1094         return "k6-2";
1095       case AMDPENTIUM_K63:
1096         return "k6-3";
1097       case AMDPENTIUM_GEODE:
1098         return "geode";
1099       default:
1100         return "pentium";
1101       }
1102     case AMDATHLON:
1103       switch (Subtype) {
1104       case AMDATHLON_TBIRD:
1105         return "athlon-tbird";
1106       case AMDATHLON_MP:
1107         return "athlon-mp";
1108       case AMDATHLON_XP:
1109         return "athlon-xp";
1110       case AMDATHLON_K8SSE3:
1111         return "k8-sse3";
1112       case AMDATHLON_OPTERON:
1113         return "opteron";
1114       case AMDATHLON_FX:
1115         return "athlon-fx";
1116       case AMDATHLON_64:
1117         return "athlon64";
1118       default:
1119         return "athlon";
1120       }
1121     case AMDFAM10H:
1122       if(Subtype == AMDFAM10H_BARCELONA)
1123         return "barcelona";
1124       return "amdfam10";
1125     case AMDFAM14H:
1126       return "btver1";
1127     case AMDFAM15H:
1128       switch (Subtype) {
1129       case AMDFAM15H_BDVER1:
1130         return "bdver1";
1131       case AMDFAM15H_BDVER2:
1132         return "bdver2";
1133       case AMDFAM15H_BDVER3:
1134         return "bdver3";
1135       case AMDFAM15H_BDVER4:
1136         return "bdver4";
1137       case AMD_BTVER1:
1138         return "btver1";
1139       default:
1140         return "amdfam15";
1141       }
1142     case AMDFAM16H:
1143       switch (Subtype) {
1144       case AMD_BTVER1:
1145         return "btver1";
1146       case AMD_BTVER2:
1147         return "btver2";
1148       default:
1149         return "amdfam16";
1150       }
1151     case AMDFAM17H:
1152       switch (Subtype) {
1153       case AMD_BTVER1:
1154         return "btver1";
1155       case AMDFAM17H_ZNVER1:
1156         return "znver1";
1157       default:
1158         return "amdfam17";
1159       }
1160     default:
1161       return "generic";
1162     }
1163   }
1164   return "generic";
1165 }
1166 
1167 #elif defined(__APPLE__) && (defined(__ppc__) || defined(__powerpc__))
1168 StringRef sys::getHostCPUName() {
1169   host_basic_info_data_t hostInfo;
1170   mach_msg_type_number_t infoCount;
1171 
1172   infoCount = HOST_BASIC_INFO_COUNT;
1173   host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo,
1174             &infoCount);
1175 
1176   if (hostInfo.cpu_type != CPU_TYPE_POWERPC)
1177     return "generic";
1178 
1179   switch (hostInfo.cpu_subtype) {
1180   case CPU_SUBTYPE_POWERPC_601:
1181     return "601";
1182   case CPU_SUBTYPE_POWERPC_602:
1183     return "602";
1184   case CPU_SUBTYPE_POWERPC_603:
1185     return "603";
1186   case CPU_SUBTYPE_POWERPC_603e:
1187     return "603e";
1188   case CPU_SUBTYPE_POWERPC_603ev:
1189     return "603ev";
1190   case CPU_SUBTYPE_POWERPC_604:
1191     return "604";
1192   case CPU_SUBTYPE_POWERPC_604e:
1193     return "604e";
1194   case CPU_SUBTYPE_POWERPC_620:
1195     return "620";
1196   case CPU_SUBTYPE_POWERPC_750:
1197     return "750";
1198   case CPU_SUBTYPE_POWERPC_7400:
1199     return "7400";
1200   case CPU_SUBTYPE_POWERPC_7450:
1201     return "7450";
1202   case CPU_SUBTYPE_POWERPC_970:
1203     return "970";
1204   default:;
1205   }
1206 
1207   return "generic";
1208 }
1209 #elif defined(__linux__) && (defined(__ppc__) || defined(__powerpc__))
1210 StringRef sys::getHostCPUName() {
1211   std::unique_ptr<llvm::MemoryBuffer> P = getProcCpuinfoContent();
1212   const StringRef& Content = P ? P->getBuffer() : "";
1213   return detail::getHostCPUNameForPowerPC(Content);
1214 }
1215 #elif defined(__linux__) && (defined(__arm__) || defined(__aarch64__))
1216 StringRef sys::getHostCPUName() {
1217   std::unique_ptr<llvm::MemoryBuffer> P = getProcCpuinfoContent();
1218   const StringRef& Content = P ? P->getBuffer() : "";
1219   return detail::getHostCPUNameForARM(Content);
1220 }
1221 #elif defined(__linux__) && defined(__s390x__)
1222 StringRef sys::getHostCPUName() {
1223   std::unique_ptr<llvm::MemoryBuffer> P = getProcCpuinfoContent();
1224   const StringRef& Content = P ? P->getBuffer() : "";
1225   return detail::getHostCPUNameForS390x(Content);
1226 }
1227 #else
1228 StringRef sys::getHostCPUName() { return "generic"; }
1229 #endif
1230 
1231 #if defined(__linux__) && defined(__x86_64__)
1232 // On Linux, the number of physical cores can be computed from /proc/cpuinfo,
1233 // using the number of unique physical/core id pairs. The following
1234 // implementation reads the /proc/cpuinfo format on an x86_64 system.
1235 static int computeHostNumPhysicalCores() {
1236   // Read /proc/cpuinfo as a stream (until EOF reached). It cannot be
1237   // mmapped because it appears to have 0 size.
1238   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1239       llvm::MemoryBuffer::getFileAsStream("/proc/cpuinfo");
1240   if (std::error_code EC = Text.getError()) {
1241     llvm::errs() << "Can't read "
1242                  << "/proc/cpuinfo: " << EC.message() << "\n";
1243     return -1;
1244   }
1245   SmallVector<StringRef, 8> strs;
1246   (*Text)->getBuffer().split(strs, "\n", /*MaxSplit=*/-1,
1247                              /*KeepEmpty=*/false);
1248   int CurPhysicalId = -1;
1249   int CurCoreId = -1;
1250   SmallSet<std::pair<int, int>, 32> UniqueItems;
1251   for (auto &Line : strs) {
1252     Line = Line.trim();
1253     if (!Line.startswith("physical id") && !Line.startswith("core id"))
1254       continue;
1255     std::pair<StringRef, StringRef> Data = Line.split(':');
1256     auto Name = Data.first.trim();
1257     auto Val = Data.second.trim();
1258     if (Name == "physical id") {
1259       assert(CurPhysicalId == -1 &&
1260              "Expected a core id before seeing another physical id");
1261       Val.getAsInteger(10, CurPhysicalId);
1262     }
1263     if (Name == "core id") {
1264       assert(CurCoreId == -1 &&
1265              "Expected a physical id before seeing another core id");
1266       Val.getAsInteger(10, CurCoreId);
1267     }
1268     if (CurPhysicalId != -1 && CurCoreId != -1) {
1269       UniqueItems.insert(std::make_pair(CurPhysicalId, CurCoreId));
1270       CurPhysicalId = -1;
1271       CurCoreId = -1;
1272     }
1273   }
1274   return UniqueItems.size();
1275 }
1276 #elif defined(__APPLE__) && defined(__x86_64__)
1277 #include <sys/param.h>
1278 #include <sys/sysctl.h>
1279 
1280 // Gets the number of *physical cores* on the machine.
1281 static int computeHostNumPhysicalCores() {
1282   uint32_t count;
1283   size_t len = sizeof(count);
1284   sysctlbyname("hw.physicalcpu", &count, &len, NULL, 0);
1285   if (count < 1) {
1286     int nm[2];
1287     nm[0] = CTL_HW;
1288     nm[1] = HW_AVAILCPU;
1289     sysctl(nm, 2, &count, &len, NULL, 0);
1290     if (count < 1)
1291       return -1;
1292   }
1293   return count;
1294 }
1295 #else
1296 // On other systems, return -1 to indicate unknown.
1297 static int computeHostNumPhysicalCores() { return -1; }
1298 #endif
1299 
1300 int sys::getHostNumPhysicalCores() {
1301   static int NumCores = computeHostNumPhysicalCores();
1302   return NumCores;
1303 }
1304 
1305 #if defined(__i386__) || defined(_M_IX86) || \
1306     defined(__x86_64__) || defined(_M_X64)
1307 bool sys::getHostCPUFeatures(StringMap<bool> &Features) {
1308   unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
1309   unsigned MaxLevel;
1310   union {
1311     unsigned u[3];
1312     char c[12];
1313   } text;
1314 
1315   if (getX86CpuIDAndInfo(0, &MaxLevel, text.u + 0, text.u + 2, text.u + 1) ||
1316       MaxLevel < 1)
1317     return false;
1318 
1319   getX86CpuIDAndInfo(1, &EAX, &EBX, &ECX, &EDX);
1320 
1321   Features["cmov"] = (EDX >> 15) & 1;
1322   Features["mmx"] = (EDX >> 23) & 1;
1323   Features["sse"] = (EDX >> 25) & 1;
1324   Features["sse2"] = (EDX >> 26) & 1;
1325   Features["sse3"] = (ECX >> 0) & 1;
1326   Features["ssse3"] = (ECX >> 9) & 1;
1327   Features["sse4.1"] = (ECX >> 19) & 1;
1328   Features["sse4.2"] = (ECX >> 20) & 1;
1329 
1330   Features["pclmul"] = (ECX >> 1) & 1;
1331   Features["cx16"] = (ECX >> 13) & 1;
1332   Features["movbe"] = (ECX >> 22) & 1;
1333   Features["popcnt"] = (ECX >> 23) & 1;
1334   Features["aes"] = (ECX >> 25) & 1;
1335   Features["rdrnd"] = (ECX >> 30) & 1;
1336 
1337   // If CPUID indicates support for XSAVE, XRESTORE and AVX, and XGETBV
1338   // indicates that the AVX registers will be saved and restored on context
1339   // switch, then we have full AVX support.
1340   bool HasAVXSave = ((ECX >> 27) & 1) && ((ECX >> 28) & 1) &&
1341                     !getX86XCR0(&EAX, &EDX) && ((EAX & 0x6) == 0x6);
1342   Features["avx"] = HasAVXSave;
1343   Features["fma"] = HasAVXSave && (ECX >> 12) & 1;
1344   Features["f16c"] = HasAVXSave && (ECX >> 29) & 1;
1345 
1346   // Only enable XSAVE if OS has enabled support for saving YMM state.
1347   Features["xsave"] = HasAVXSave && (ECX >> 26) & 1;
1348 
1349   // AVX512 requires additional context to be saved by the OS.
1350   bool HasAVX512Save = HasAVXSave && ((EAX & 0xe0) == 0xe0);
1351 
1352   unsigned MaxExtLevel;
1353   getX86CpuIDAndInfo(0x80000000, &MaxExtLevel, &EBX, &ECX, &EDX);
1354 
1355   bool HasExtLeaf1 = MaxExtLevel >= 0x80000001 &&
1356                      !getX86CpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
1357   Features["lzcnt"] = HasExtLeaf1 && ((ECX >> 5) & 1);
1358   Features["sse4a"] = HasExtLeaf1 && ((ECX >> 6) & 1);
1359   Features["prfchw"] = HasExtLeaf1 && ((ECX >> 8) & 1);
1360   Features["xop"] = HasExtLeaf1 && ((ECX >> 11) & 1) && HasAVXSave;
1361   Features["lwp"] = HasExtLeaf1 && ((ECX >> 15) & 1);
1362   Features["fma4"] = HasExtLeaf1 && ((ECX >> 16) & 1) && HasAVXSave;
1363   Features["tbm"] = HasExtLeaf1 && ((ECX >> 21) & 1);
1364   Features["mwaitx"] = HasExtLeaf1 && ((ECX >> 29) & 1);
1365 
1366   bool HasExtLeaf8 = MaxExtLevel >= 0x80000008 &&
1367                      !getX86CpuIDAndInfoEx(0x80000008,0x0, &EAX, &EBX, &ECX, &EDX);
1368   Features["clzero"] = HasExtLeaf8 && ((EBX >> 0) & 1);
1369 
1370   bool HasLeaf7 =
1371       MaxLevel >= 7 && !getX86CpuIDAndInfoEx(0x7, 0x0, &EAX, &EBX, &ECX, &EDX);
1372 
1373   // AVX2 is only supported if we have the OS save support from AVX.
1374   Features["avx2"] = HasAVXSave && HasLeaf7 && ((EBX >> 5) & 1);
1375 
1376   Features["fsgsbase"] = HasLeaf7 && ((EBX >> 0) & 1);
1377   Features["sgx"] = HasLeaf7 && ((EBX >> 2) & 1);
1378   Features["bmi"] = HasLeaf7 && ((EBX >> 3) & 1);
1379   Features["bmi2"] = HasLeaf7 && ((EBX >> 8) & 1);
1380   Features["rtm"] = HasLeaf7 && ((EBX >> 11) & 1);
1381   Features["rdseed"] = HasLeaf7 && ((EBX >> 18) & 1);
1382   Features["adx"] = HasLeaf7 && ((EBX >> 19) & 1);
1383   Features["clflushopt"] = HasLeaf7 && ((EBX >> 23) & 1);
1384   Features["clwb"] = HasLeaf7 && ((EBX >> 24) & 1);
1385   Features["sha"] = HasLeaf7 && ((EBX >> 29) & 1);
1386 
1387   // AVX512 is only supported if the OS supports the context save for it.
1388   Features["avx512f"] = HasLeaf7 && ((EBX >> 16) & 1) && HasAVX512Save;
1389   Features["avx512dq"] = HasLeaf7 && ((EBX >> 17) & 1) && HasAVX512Save;
1390   Features["avx512ifma"] = HasLeaf7 && ((EBX >> 21) & 1) && HasAVX512Save;
1391   Features["avx512pf"] = HasLeaf7 && ((EBX >> 26) & 1) && HasAVX512Save;
1392   Features["avx512er"] = HasLeaf7 && ((EBX >> 27) & 1) && HasAVX512Save;
1393   Features["avx512cd"] = HasLeaf7 && ((EBX >> 28) & 1) && HasAVX512Save;
1394   Features["avx512bw"] = HasLeaf7 && ((EBX >> 30) & 1) && HasAVX512Save;
1395   Features["avx512vl"] = HasLeaf7 && ((EBX >> 31) & 1) && HasAVX512Save;
1396 
1397   Features["prefetchwt1"] = HasLeaf7 && (ECX & 1);
1398   Features["avx512vbmi"] = HasLeaf7 && ((ECX >> 1) & 1) && HasAVX512Save;
1399   Features["avx512vpopcntdq"] = HasLeaf7 && ((ECX >> 14) & 1) && HasAVX512Save;
1400   // Enable protection keys
1401   Features["pku"] = HasLeaf7 && ((ECX >> 4) & 1);
1402 
1403   bool HasLeafD = MaxLevel >= 0xd &&
1404                   !getX86CpuIDAndInfoEx(0xd, 0x1, &EAX, &EBX, &ECX, &EDX);
1405 
1406   // Only enable XSAVE if OS has enabled support for saving YMM state.
1407   Features["xsaveopt"] = HasAVXSave && HasLeafD && ((EAX >> 0) & 1);
1408   Features["xsavec"] = HasAVXSave && HasLeafD && ((EAX >> 1) & 1);
1409   Features["xsaves"] = HasAVXSave && HasLeafD && ((EAX >> 3) & 1);
1410 
1411   return true;
1412 }
1413 #elif defined(__linux__) && (defined(__arm__) || defined(__aarch64__))
1414 bool sys::getHostCPUFeatures(StringMap<bool> &Features) {
1415   std::unique_ptr<llvm::MemoryBuffer> P = getProcCpuinfoContent();
1416   if (!P)
1417     return false;
1418 
1419   SmallVector<StringRef, 32> Lines;
1420   P->getBuffer().split(Lines, "\n");
1421 
1422   SmallVector<StringRef, 32> CPUFeatures;
1423 
1424   // Look for the CPU features.
1425   for (unsigned I = 0, E = Lines.size(); I != E; ++I)
1426     if (Lines[I].startswith("Features")) {
1427       Lines[I].split(CPUFeatures, ' ');
1428       break;
1429     }
1430 
1431 #if defined(__aarch64__)
1432   // Keep track of which crypto features we have seen
1433   enum { CAP_AES = 0x1, CAP_PMULL = 0x2, CAP_SHA1 = 0x4, CAP_SHA2 = 0x8 };
1434   uint32_t crypto = 0;
1435 #endif
1436 
1437   for (unsigned I = 0, E = CPUFeatures.size(); I != E; ++I) {
1438     StringRef LLVMFeatureStr = StringSwitch<StringRef>(CPUFeatures[I])
1439 #if defined(__aarch64__)
1440                                    .Case("asimd", "neon")
1441                                    .Case("fp", "fp-armv8")
1442                                    .Case("crc32", "crc")
1443 #else
1444                                    .Case("half", "fp16")
1445                                    .Case("neon", "neon")
1446                                    .Case("vfpv3", "vfp3")
1447                                    .Case("vfpv3d16", "d16")
1448                                    .Case("vfpv4", "vfp4")
1449                                    .Case("idiva", "hwdiv-arm")
1450                                    .Case("idivt", "hwdiv")
1451 #endif
1452                                    .Default("");
1453 
1454 #if defined(__aarch64__)
1455     // We need to check crypto separately since we need all of the crypto
1456     // extensions to enable the subtarget feature
1457     if (CPUFeatures[I] == "aes")
1458       crypto |= CAP_AES;
1459     else if (CPUFeatures[I] == "pmull")
1460       crypto |= CAP_PMULL;
1461     else if (CPUFeatures[I] == "sha1")
1462       crypto |= CAP_SHA1;
1463     else if (CPUFeatures[I] == "sha2")
1464       crypto |= CAP_SHA2;
1465 #endif
1466 
1467     if (LLVMFeatureStr != "")
1468       Features[LLVMFeatureStr] = true;
1469   }
1470 
1471 #if defined(__aarch64__)
1472   // If we have all crypto bits we can add the feature
1473   if (crypto == (CAP_AES | CAP_PMULL | CAP_SHA1 | CAP_SHA2))
1474     Features["crypto"] = true;
1475 #endif
1476 
1477   return true;
1478 }
1479 #else
1480 bool sys::getHostCPUFeatures(StringMap<bool> &Features) { return false; }
1481 #endif
1482 
1483 std::string sys::getProcessTriple() {
1484   std::string TargetTripleString = updateTripleOSVersion(LLVM_HOST_TRIPLE);
1485   Triple PT(Triple::normalize(TargetTripleString));
1486 
1487   if (sizeof(void *) == 8 && PT.isArch32Bit())
1488     PT = PT.get64BitArchVariant();
1489   if (sizeof(void *) == 4 && PT.isArch64Bit())
1490     PT = PT.get32BitArchVariant();
1491 
1492   return PT.str();
1493 }
1494