• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- Targets.cpp - Implement target feature support -------------------===//
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 construction of a TargetInfo object from a
11 // target triple.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Basic/Builtins.h"
16 #include "clang/Basic/Cuda.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/MacroBuilder.h"
20 #include "clang/Basic/TargetBuiltins.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Basic/TargetOptions.h"
23 #include "clang/Basic/Version.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/TargetParser.h"
33 #include <algorithm>
34 #include <memory>
35 
36 using namespace clang;
37 
38 //===----------------------------------------------------------------------===//
39 //  Common code shared among targets.
40 //===----------------------------------------------------------------------===//
41 
42 /// DefineStd - Define a macro name and standard variants.  For example if
43 /// MacroName is "unix", then this will define "__unix", "__unix__", and "unix"
44 /// when in GNU mode.
DefineStd(MacroBuilder & Builder,StringRef MacroName,const LangOptions & Opts)45 static void DefineStd(MacroBuilder &Builder, StringRef MacroName,
46                       const LangOptions &Opts) {
47   assert(MacroName[0] != '_' && "Identifier should be in the user's namespace");
48 
49   // If in GNU mode (e.g. -std=gnu99 but not -std=c99) define the raw identifier
50   // in the user's namespace.
51   if (Opts.GNUMode)
52     Builder.defineMacro(MacroName);
53 
54   // Define __unix.
55   Builder.defineMacro("__" + MacroName);
56 
57   // Define __unix__.
58   Builder.defineMacro("__" + MacroName + "__");
59 }
60 
defineCPUMacros(MacroBuilder & Builder,StringRef CPUName,bool Tuning=true)61 static void defineCPUMacros(MacroBuilder &Builder, StringRef CPUName,
62                             bool Tuning = true) {
63   Builder.defineMacro("__" + CPUName);
64   Builder.defineMacro("__" + CPUName + "__");
65   if (Tuning)
66     Builder.defineMacro("__tune_" + CPUName + "__");
67 }
68 
69 static TargetInfo *AllocateTarget(const llvm::Triple &Triple,
70                                   const TargetOptions &Opts);
71 
72 //===----------------------------------------------------------------------===//
73 // Defines specific to certain operating systems.
74 //===----------------------------------------------------------------------===//
75 
76 namespace {
77 template<typename TgtInfo>
78 class OSTargetInfo : public TgtInfo {
79 protected:
80   virtual void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
81                             MacroBuilder &Builder) const=0;
82 public:
OSTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)83   OSTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
84       : TgtInfo(Triple, Opts) {}
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const85   void getTargetDefines(const LangOptions &Opts,
86                         MacroBuilder &Builder) const override {
87     TgtInfo::getTargetDefines(Opts, Builder);
88     getOSDefines(Opts, TgtInfo::getTriple(), Builder);
89   }
90 
91 };
92 
93 // CloudABI Target
94 template <typename Target>
95 class CloudABITargetInfo : public OSTargetInfo<Target> {
96 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const97   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
98                     MacroBuilder &Builder) const override {
99     Builder.defineMacro("__CloudABI__");
100     Builder.defineMacro("__ELF__");
101 
102     // CloudABI uses ISO/IEC 10646:2012 for wchar_t, char16_t and char32_t.
103     Builder.defineMacro("__STDC_ISO_10646__", "201206L");
104     Builder.defineMacro("__STDC_UTF_16__");
105     Builder.defineMacro("__STDC_UTF_32__");
106   }
107 
108 public:
CloudABITargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)109   CloudABITargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
110       : OSTargetInfo<Target>(Triple, Opts) {}
111 };
112 
getDarwinDefines(MacroBuilder & Builder,const LangOptions & Opts,const llvm::Triple & Triple,StringRef & PlatformName,VersionTuple & PlatformMinVersion)113 static void getDarwinDefines(MacroBuilder &Builder, const LangOptions &Opts,
114                              const llvm::Triple &Triple,
115                              StringRef &PlatformName,
116                              VersionTuple &PlatformMinVersion) {
117   Builder.defineMacro("__APPLE_CC__", "6000");
118   Builder.defineMacro("__APPLE__");
119   Builder.defineMacro("OBJC_NEW_PROPERTIES");
120   // AddressSanitizer doesn't play well with source fortification, which is on
121   // by default on Darwin.
122   if (Opts.Sanitize.has(SanitizerKind::Address))
123     Builder.defineMacro("_FORTIFY_SOURCE", "0");
124 
125   // Darwin defines __weak, __strong, and __unsafe_unretained even in C mode.
126   if (!Opts.ObjC1) {
127     // __weak is always defined, for use in blocks and with objc pointers.
128     Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
129     Builder.defineMacro("__strong", "");
130     Builder.defineMacro("__unsafe_unretained", "");
131   }
132 
133   if (Opts.Static)
134     Builder.defineMacro("__STATIC__");
135   else
136     Builder.defineMacro("__DYNAMIC__");
137 
138   if (Opts.POSIXThreads)
139     Builder.defineMacro("_REENTRANT");
140 
141   // Get the platform type and version number from the triple.
142   unsigned Maj, Min, Rev;
143   if (Triple.isMacOSX()) {
144     Triple.getMacOSXVersion(Maj, Min, Rev);
145     PlatformName = "macos";
146   } else {
147     Triple.getOSVersion(Maj, Min, Rev);
148     PlatformName = llvm::Triple::getOSTypeName(Triple.getOS());
149   }
150 
151   // If -target arch-pc-win32-macho option specified, we're
152   // generating code for Win32 ABI. No need to emit
153   // __ENVIRONMENT_XX_OS_VERSION_MIN_REQUIRED__.
154   if (PlatformName == "win32") {
155     PlatformMinVersion = VersionTuple(Maj, Min, Rev);
156     return;
157   }
158 
159   // Set the appropriate OS version define.
160   if (Triple.isiOS()) {
161     assert(Maj < 10 && Min < 100 && Rev < 100 && "Invalid version!");
162     char Str[6];
163     Str[0] = '0' + Maj;
164     Str[1] = '0' + (Min / 10);
165     Str[2] = '0' + (Min % 10);
166     Str[3] = '0' + (Rev / 10);
167     Str[4] = '0' + (Rev % 10);
168     Str[5] = '\0';
169     if (Triple.isTvOS())
170       Builder.defineMacro("__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__", Str);
171     else
172       Builder.defineMacro("__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__",
173                           Str);
174 
175   } else if (Triple.isWatchOS()) {
176     assert(Maj < 10 && Min < 100 && Rev < 100 && "Invalid version!");
177     char Str[6];
178     Str[0] = '0' + Maj;
179     Str[1] = '0' + (Min / 10);
180     Str[2] = '0' + (Min % 10);
181     Str[3] = '0' + (Rev / 10);
182     Str[4] = '0' + (Rev % 10);
183     Str[5] = '\0';
184     Builder.defineMacro("__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__", Str);
185   } else if (Triple.isMacOSX()) {
186     // Note that the Driver allows versions which aren't representable in the
187     // define (because we only get a single digit for the minor and micro
188     // revision numbers). So, we limit them to the maximum representable
189     // version.
190     assert(Maj < 100 && Min < 100 && Rev < 100 && "Invalid version!");
191     char Str[7];
192     if (Maj < 10 || (Maj == 10 && Min < 10)) {
193       Str[0] = '0' + (Maj / 10);
194       Str[1] = '0' + (Maj % 10);
195       Str[2] = '0' + std::min(Min, 9U);
196       Str[3] = '0' + std::min(Rev, 9U);
197       Str[4] = '\0';
198     } else {
199       // Handle versions > 10.9.
200       Str[0] = '0' + (Maj / 10);
201       Str[1] = '0' + (Maj % 10);
202       Str[2] = '0' + (Min / 10);
203       Str[3] = '0' + (Min % 10);
204       Str[4] = '0' + (Rev / 10);
205       Str[5] = '0' + (Rev % 10);
206       Str[6] = '\0';
207     }
208     Builder.defineMacro("__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__", Str);
209   }
210 
211   // Tell users about the kernel if there is one.
212   if (Triple.isOSDarwin())
213     Builder.defineMacro("__MACH__");
214 
215   // The Watch ABI uses Dwarf EH.
216   if(Triple.isWatchABI())
217     Builder.defineMacro("__ARM_DWARF_EH__");
218 
219   PlatformMinVersion = VersionTuple(Maj, Min, Rev);
220 }
221 
222 template<typename Target>
223 class DarwinTargetInfo : public OSTargetInfo<Target> {
224 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const225   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
226                     MacroBuilder &Builder) const override {
227     getDarwinDefines(Builder, Opts, Triple, this->PlatformName,
228                      this->PlatformMinVersion);
229   }
230 
231 public:
DarwinTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)232   DarwinTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
233       : OSTargetInfo<Target>(Triple, Opts) {
234     // By default, no TLS, and we whitelist permitted architecture/OS
235     // combinations.
236     this->TLSSupported = false;
237 
238     if (Triple.isMacOSX())
239       this->TLSSupported = !Triple.isMacOSXVersionLT(10, 7);
240     else if (Triple.isiOS()) {
241       // 64-bit iOS supported it from 8 onwards, 32-bit from 9 onwards.
242       if (Triple.getArch() == llvm::Triple::x86_64 ||
243           Triple.getArch() == llvm::Triple::aarch64)
244         this->TLSSupported = !Triple.isOSVersionLT(8);
245       else if (Triple.getArch() == llvm::Triple::x86 ||
246                Triple.getArch() == llvm::Triple::arm ||
247                Triple.getArch() == llvm::Triple::thumb)
248         this->TLSSupported = !Triple.isOSVersionLT(9);
249     } else if (Triple.isWatchOS())
250       this->TLSSupported = !Triple.isOSVersionLT(2);
251 
252     this->MCountName = "\01mcount";
253   }
254 
isValidSectionSpecifier(StringRef SR) const255   std::string isValidSectionSpecifier(StringRef SR) const override {
256     // Let MCSectionMachO validate this.
257     StringRef Segment, Section;
258     unsigned TAA, StubSize;
259     bool HasTAA;
260     return llvm::MCSectionMachO::ParseSectionSpecifier(SR, Segment, Section,
261                                                        TAA, HasTAA, StubSize);
262   }
263 
getStaticInitSectionSpecifier() const264   const char *getStaticInitSectionSpecifier() const override {
265     // FIXME: We should return 0 when building kexts.
266     return "__TEXT,__StaticInit,regular,pure_instructions";
267   }
268 
269   /// Darwin does not support protected visibility.  Darwin's "default"
270   /// is very similar to ELF's "protected";  Darwin requires a "weak"
271   /// attribute on declarations that can be dynamically replaced.
hasProtectedVisibility() const272   bool hasProtectedVisibility() const override {
273     return false;
274   }
275 
getExnObjectAlignment() const276   unsigned getExnObjectAlignment() const override {
277     // The alignment of an exception object is 8-bytes for darwin since
278     // libc++abi doesn't declare _Unwind_Exception with __attribute__((aligned))
279     // and therefore doesn't guarantee 16-byte alignment.
280     return  64;
281   }
282 };
283 
284 
285 // DragonFlyBSD Target
286 template<typename Target>
287 class DragonFlyBSDTargetInfo : public OSTargetInfo<Target> {
288 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const289   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
290                     MacroBuilder &Builder) const override {
291     // DragonFly defines; list based off of gcc output
292     Builder.defineMacro("__DragonFly__");
293     Builder.defineMacro("__DragonFly_cc_version", "100001");
294     Builder.defineMacro("__ELF__");
295     Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
296     Builder.defineMacro("__tune_i386__");
297     DefineStd(Builder, "unix", Opts);
298   }
299 public:
DragonFlyBSDTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)300   DragonFlyBSDTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
301       : OSTargetInfo<Target>(Triple, Opts) {
302     switch (Triple.getArch()) {
303     default:
304     case llvm::Triple::x86:
305     case llvm::Triple::x86_64:
306       this->MCountName = ".mcount";
307       break;
308     }
309   }
310 };
311 
312 #ifndef FREEBSD_CC_VERSION
313 #define FREEBSD_CC_VERSION 0U
314 #endif
315 
316 // FreeBSD Target
317 template<typename Target>
318 class FreeBSDTargetInfo : public OSTargetInfo<Target> {
319 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const320   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
321                     MacroBuilder &Builder) const override {
322     // FreeBSD defines; list based off of gcc output
323 
324     unsigned Release = Triple.getOSMajorVersion();
325     if (Release == 0U)
326       Release = 8U;
327     unsigned CCVersion = FREEBSD_CC_VERSION;
328     if (CCVersion == 0U)
329       CCVersion = Release * 100000U + 1U;
330 
331     Builder.defineMacro("__FreeBSD__", Twine(Release));
332     Builder.defineMacro("__FreeBSD_cc_version", Twine(CCVersion));
333     Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
334     DefineStd(Builder, "unix", Opts);
335     Builder.defineMacro("__ELF__");
336 
337     // On FreeBSD, wchar_t contains the number of the code point as
338     // used by the character set of the locale. These character sets are
339     // not necessarily a superset of ASCII.
340     //
341     // FIXME: This is wrong; the macro refers to the numerical values
342     // of wchar_t *literals*, which are not locale-dependent. However,
343     // FreeBSD systems apparently depend on us getting this wrong, and
344     // setting this to 1 is conforming even if all the basic source
345     // character literals have the same encoding as char and wchar_t.
346     Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
347   }
348 public:
FreeBSDTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)349   FreeBSDTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
350       : OSTargetInfo<Target>(Triple, Opts) {
351     switch (Triple.getArch()) {
352     default:
353     case llvm::Triple::x86:
354     case llvm::Triple::x86_64:
355       this->MCountName = ".mcount";
356       break;
357     case llvm::Triple::mips:
358     case llvm::Triple::mipsel:
359     case llvm::Triple::ppc:
360     case llvm::Triple::ppc64:
361     case llvm::Triple::ppc64le:
362       this->MCountName = "_mcount";
363       break;
364     case llvm::Triple::arm:
365       this->MCountName = "__mcount";
366       break;
367     }
368   }
369 };
370 
371 // GNU/kFreeBSD Target
372 template<typename Target>
373 class KFreeBSDTargetInfo : public OSTargetInfo<Target> {
374 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const375   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
376                     MacroBuilder &Builder) const override {
377     // GNU/kFreeBSD defines; list based off of gcc output
378 
379     DefineStd(Builder, "unix", Opts);
380     Builder.defineMacro("__FreeBSD_kernel__");
381     Builder.defineMacro("__GLIBC__");
382     Builder.defineMacro("__ELF__");
383     if (Opts.POSIXThreads)
384       Builder.defineMacro("_REENTRANT");
385     if (Opts.CPlusPlus)
386       Builder.defineMacro("_GNU_SOURCE");
387   }
388 public:
KFreeBSDTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)389   KFreeBSDTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
390       : OSTargetInfo<Target>(Triple, Opts) {}
391 };
392 
393 // Haiku Target
394 template<typename Target>
395 class HaikuTargetInfo : public OSTargetInfo<Target> {
396 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const397   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
398                     MacroBuilder &Builder) const override {
399     // Haiku defines; list based off of gcc output
400     Builder.defineMacro("__HAIKU__");
401     Builder.defineMacro("__ELF__");
402     DefineStd(Builder, "unix", Opts);
403   }
404 public:
HaikuTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)405   HaikuTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
406       : OSTargetInfo<Target>(Triple, Opts) {
407     this->SizeType = TargetInfo::UnsignedLong;
408     this->IntPtrType = TargetInfo::SignedLong;
409     this->PtrDiffType = TargetInfo::SignedLong;
410     this->ProcessIDType = TargetInfo::SignedLong;
411     this->TLSSupported = false;
412 
413   }
414 };
415 
416 // Minix Target
417 template<typename Target>
418 class MinixTargetInfo : public OSTargetInfo<Target> {
419 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const420   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
421                     MacroBuilder &Builder) const override {
422     // Minix defines
423 
424     Builder.defineMacro("__minix", "3");
425     Builder.defineMacro("_EM_WSIZE", "4");
426     Builder.defineMacro("_EM_PSIZE", "4");
427     Builder.defineMacro("_EM_SSIZE", "2");
428     Builder.defineMacro("_EM_LSIZE", "4");
429     Builder.defineMacro("_EM_FSIZE", "4");
430     Builder.defineMacro("_EM_DSIZE", "8");
431     Builder.defineMacro("__ELF__");
432     DefineStd(Builder, "unix", Opts);
433   }
434 public:
MinixTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)435   MinixTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
436       : OSTargetInfo<Target>(Triple, Opts) {}
437 };
438 
439 // Linux target
440 template<typename Target>
441 class LinuxTargetInfo : public OSTargetInfo<Target> {
442 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const443   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
444                     MacroBuilder &Builder) const override {
445     // Linux defines; list based off of gcc output
446     DefineStd(Builder, "unix", Opts);
447     DefineStd(Builder, "linux", Opts);
448     Builder.defineMacro("__gnu_linux__");
449     Builder.defineMacro("__ELF__");
450     if (Triple.isAndroid()) {
451       Builder.defineMacro("__ANDROID__", "1");
452       unsigned Maj, Min, Rev;
453       Triple.getEnvironmentVersion(Maj, Min, Rev);
454       this->PlatformName = "android";
455       this->PlatformMinVersion = VersionTuple(Maj, Min, Rev);
456     }
457     if (Opts.POSIXThreads)
458       Builder.defineMacro("_REENTRANT");
459     if (Opts.CPlusPlus)
460       Builder.defineMacro("_GNU_SOURCE");
461     if (this->HasFloat128)
462       Builder.defineMacro("__FLOAT128__");
463   }
464 public:
LinuxTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)465   LinuxTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
466       : OSTargetInfo<Target>(Triple, Opts) {
467     this->WIntType = TargetInfo::UnsignedInt;
468 
469     switch (Triple.getArch()) {
470     default:
471       break;
472     case llvm::Triple::ppc:
473     case llvm::Triple::ppc64:
474     case llvm::Triple::ppc64le:
475       this->MCountName = "_mcount";
476       break;
477     case llvm::Triple::x86:
478     case llvm::Triple::x86_64:
479     case llvm::Triple::systemz:
480       this->HasFloat128 = true;
481       break;
482     }
483   }
484 
getStaticInitSectionSpecifier() const485   const char *getStaticInitSectionSpecifier() const override {
486     return ".text.startup";
487   }
488 };
489 
490 // NetBSD Target
491 template<typename Target>
492 class NetBSDTargetInfo : public OSTargetInfo<Target> {
493 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const494   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
495                     MacroBuilder &Builder) const override {
496     // NetBSD defines; list based off of gcc output
497     Builder.defineMacro("__NetBSD__");
498     Builder.defineMacro("__unix__");
499     Builder.defineMacro("__ELF__");
500     if (Opts.POSIXThreads)
501       Builder.defineMacro("_POSIX_THREADS");
502 
503     switch (Triple.getArch()) {
504     default:
505       break;
506     case llvm::Triple::arm:
507     case llvm::Triple::armeb:
508     case llvm::Triple::thumb:
509     case llvm::Triple::thumbeb:
510       Builder.defineMacro("__ARM_DWARF_EH__");
511       break;
512     }
513   }
514 public:
NetBSDTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)515   NetBSDTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
516       : OSTargetInfo<Target>(Triple, Opts) {
517     this->MCountName = "_mcount";
518   }
519 };
520 
521 // OpenBSD Target
522 template<typename Target>
523 class OpenBSDTargetInfo : public OSTargetInfo<Target> {
524 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const525   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
526                     MacroBuilder &Builder) const override {
527     // OpenBSD defines; list based off of gcc output
528 
529     Builder.defineMacro("__OpenBSD__");
530     DefineStd(Builder, "unix", Opts);
531     Builder.defineMacro("__ELF__");
532     if (Opts.POSIXThreads)
533       Builder.defineMacro("_REENTRANT");
534   }
535 public:
OpenBSDTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)536   OpenBSDTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
537       : OSTargetInfo<Target>(Triple, Opts) {
538     this->TLSSupported = false;
539 
540       switch (Triple.getArch()) {
541         default:
542         case llvm::Triple::x86:
543         case llvm::Triple::x86_64:
544         case llvm::Triple::arm:
545         case llvm::Triple::sparc:
546           this->MCountName = "__mcount";
547           break;
548         case llvm::Triple::mips64:
549         case llvm::Triple::mips64el:
550         case llvm::Triple::ppc:
551         case llvm::Triple::sparcv9:
552           this->MCountName = "_mcount";
553           break;
554       }
555   }
556 };
557 
558 // Bitrig Target
559 template<typename Target>
560 class BitrigTargetInfo : public OSTargetInfo<Target> {
561 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const562   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
563                     MacroBuilder &Builder) const override {
564     // Bitrig defines; list based off of gcc output
565 
566     Builder.defineMacro("__Bitrig__");
567     DefineStd(Builder, "unix", Opts);
568     Builder.defineMacro("__ELF__");
569     if (Opts.POSIXThreads)
570       Builder.defineMacro("_REENTRANT");
571 
572     switch (Triple.getArch()) {
573     default:
574       break;
575     case llvm::Triple::arm:
576     case llvm::Triple::armeb:
577     case llvm::Triple::thumb:
578     case llvm::Triple::thumbeb:
579       Builder.defineMacro("__ARM_DWARF_EH__");
580       break;
581     }
582   }
583 public:
BitrigTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)584   BitrigTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
585       : OSTargetInfo<Target>(Triple, Opts) {
586     this->MCountName = "__mcount";
587   }
588 };
589 
590 // PSP Target
591 template<typename Target>
592 class PSPTargetInfo : public OSTargetInfo<Target> {
593 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const594   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
595                     MacroBuilder &Builder) const override {
596     // PSP defines; list based on the output of the pspdev gcc toolchain.
597     Builder.defineMacro("PSP");
598     Builder.defineMacro("_PSP");
599     Builder.defineMacro("__psp__");
600     Builder.defineMacro("__ELF__");
601   }
602 public:
PSPTargetInfo(const llvm::Triple & Triple)603   PSPTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {}
604 };
605 
606 // PS3 PPU Target
607 template<typename Target>
608 class PS3PPUTargetInfo : public OSTargetInfo<Target> {
609 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const610   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
611                     MacroBuilder &Builder) const override {
612     // PS3 PPU defines.
613     Builder.defineMacro("__PPC__");
614     Builder.defineMacro("__PPU__");
615     Builder.defineMacro("__CELLOS_LV2__");
616     Builder.defineMacro("__ELF__");
617     Builder.defineMacro("__LP32__");
618     Builder.defineMacro("_ARCH_PPC64");
619     Builder.defineMacro("__powerpc64__");
620   }
621 public:
PS3PPUTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)622   PS3PPUTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
623       : OSTargetInfo<Target>(Triple, Opts) {
624     this->LongWidth = this->LongAlign = 32;
625     this->PointerWidth = this->PointerAlign = 32;
626     this->IntMaxType = TargetInfo::SignedLongLong;
627     this->Int64Type = TargetInfo::SignedLongLong;
628     this->SizeType = TargetInfo::UnsignedInt;
629     this->resetDataLayout("E-m:e-p:32:32-i64:64-n32:64");
630   }
631 };
632 
633 template <typename Target>
634 class PS4OSTargetInfo : public OSTargetInfo<Target> {
635 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const636   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
637                     MacroBuilder &Builder) const override {
638     Builder.defineMacro("__FreeBSD__", "9");
639     Builder.defineMacro("__FreeBSD_cc_version", "900001");
640     Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
641     DefineStd(Builder, "unix", Opts);
642     Builder.defineMacro("__ELF__");
643     Builder.defineMacro("__ORBIS__");
644   }
645 public:
PS4OSTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)646   PS4OSTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
647       : OSTargetInfo<Target>(Triple, Opts) {
648     this->WCharType = this->UnsignedShort;
649 
650     // On PS4, TLS variable cannot be aligned to more than 32 bytes (256 bits).
651     this->MaxTLSAlign = 256;
652 
653     // On PS4, do not honor explicit bit field alignment,
654     // as in "__attribute__((aligned(2))) int b : 1;".
655     this->UseExplicitBitFieldAlignment = false;
656 
657     switch (Triple.getArch()) {
658     default:
659     case llvm::Triple::x86_64:
660       this->MCountName = ".mcount";
661       break;
662     }
663   }
664 };
665 
666 // Solaris target
667 template<typename Target>
668 class SolarisTargetInfo : public OSTargetInfo<Target> {
669 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const670   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
671                     MacroBuilder &Builder) const override {
672     DefineStd(Builder, "sun", Opts);
673     DefineStd(Builder, "unix", Opts);
674     Builder.defineMacro("__ELF__");
675     Builder.defineMacro("__svr4__");
676     Builder.defineMacro("__SVR4");
677     // Solaris headers require _XOPEN_SOURCE to be set to 600 for C99 and
678     // newer, but to 500 for everything else.  feature_test.h has a check to
679     // ensure that you are not using C99 with an old version of X/Open or C89
680     // with a new version.
681     if (Opts.C99)
682       Builder.defineMacro("_XOPEN_SOURCE", "600");
683     else
684       Builder.defineMacro("_XOPEN_SOURCE", "500");
685     if (Opts.CPlusPlus)
686       Builder.defineMacro("__C99FEATURES__");
687     Builder.defineMacro("_LARGEFILE_SOURCE");
688     Builder.defineMacro("_LARGEFILE64_SOURCE");
689     Builder.defineMacro("__EXTENSIONS__");
690     Builder.defineMacro("_REENTRANT");
691   }
692 public:
SolarisTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)693   SolarisTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
694       : OSTargetInfo<Target>(Triple, Opts) {
695     this->WCharType = this->SignedInt;
696     // FIXME: WIntType should be SignedLong
697   }
698 };
699 
700 // Windows target
701 template<typename Target>
702 class WindowsTargetInfo : public OSTargetInfo<Target> {
703 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const704   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
705                     MacroBuilder &Builder) const override {
706     Builder.defineMacro("_WIN32");
707   }
getVisualStudioDefines(const LangOptions & Opts,MacroBuilder & Builder) const708   void getVisualStudioDefines(const LangOptions &Opts,
709                               MacroBuilder &Builder) const {
710     if (Opts.CPlusPlus) {
711       if (Opts.RTTIData)
712         Builder.defineMacro("_CPPRTTI");
713 
714       if (Opts.CXXExceptions)
715         Builder.defineMacro("_CPPUNWIND");
716     }
717 
718     if (Opts.Bool)
719       Builder.defineMacro("__BOOL_DEFINED");
720 
721     if (!Opts.CharIsSigned)
722       Builder.defineMacro("_CHAR_UNSIGNED");
723 
724     // FIXME: POSIXThreads isn't exactly the option this should be defined for,
725     //        but it works for now.
726     if (Opts.POSIXThreads)
727       Builder.defineMacro("_MT");
728 
729     if (Opts.MSCompatibilityVersion) {
730       Builder.defineMacro("_MSC_VER",
731                           Twine(Opts.MSCompatibilityVersion / 100000));
732       Builder.defineMacro("_MSC_FULL_VER", Twine(Opts.MSCompatibilityVersion));
733       // FIXME We cannot encode the revision information into 32-bits
734       Builder.defineMacro("_MSC_BUILD", Twine(1));
735 
736       if (Opts.CPlusPlus11 && Opts.isCompatibleWithMSVC(LangOptions::MSVC2015))
737         Builder.defineMacro("_HAS_CHAR16_T_LANGUAGE_SUPPORT", Twine(1));
738 
739       if (Opts.isCompatibleWithMSVC(LangOptions::MSVC2015)) {
740         if (Opts.CPlusPlus1z)
741           Builder.defineMacro("_MSVC_LANG", "201403L");
742         else if (Opts.CPlusPlus14)
743           Builder.defineMacro("_MSVC_LANG", "201402L");
744       }
745     }
746 
747     if (Opts.MicrosoftExt) {
748       Builder.defineMacro("_MSC_EXTENSIONS");
749 
750       if (Opts.CPlusPlus11) {
751         Builder.defineMacro("_RVALUE_REFERENCES_V2_SUPPORTED");
752         Builder.defineMacro("_RVALUE_REFERENCES_SUPPORTED");
753         Builder.defineMacro("_NATIVE_NULLPTR_SUPPORTED");
754       }
755     }
756 
757     Builder.defineMacro("_INTEGRAL_MAX_BITS", "64");
758   }
759 
760 public:
WindowsTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)761   WindowsTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
762       : OSTargetInfo<Target>(Triple, Opts) {}
763 };
764 
765 template <typename Target>
766 class NaClTargetInfo : public OSTargetInfo<Target> {
767 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const768   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
769                     MacroBuilder &Builder) const override {
770     if (Opts.POSIXThreads)
771       Builder.defineMacro("_REENTRANT");
772     if (Opts.CPlusPlus)
773       Builder.defineMacro("_GNU_SOURCE");
774 
775     DefineStd(Builder, "unix", Opts);
776     Builder.defineMacro("__ELF__");
777     Builder.defineMacro("__native_client__");
778   }
779 
780 public:
NaClTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)781   NaClTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
782       : OSTargetInfo<Target>(Triple, Opts) {
783     this->LongAlign = 32;
784     this->LongWidth = 32;
785     this->PointerAlign = 32;
786     this->PointerWidth = 32;
787     this->IntMaxType = TargetInfo::SignedLongLong;
788     this->Int64Type = TargetInfo::SignedLongLong;
789     this->DoubleAlign = 64;
790     this->LongDoubleWidth = 64;
791     this->LongDoubleAlign = 64;
792     this->LongLongWidth = 64;
793     this->LongLongAlign = 64;
794     this->SizeType = TargetInfo::UnsignedInt;
795     this->PtrDiffType = TargetInfo::SignedInt;
796     this->IntPtrType = TargetInfo::SignedInt;
797     // RegParmMax is inherited from the underlying architecture
798     this->LongDoubleFormat = &llvm::APFloat::IEEEdouble;
799     if (Triple.getArch() == llvm::Triple::arm) {
800       // Handled in ARM's setABI().
801     } else if (Triple.getArch() == llvm::Triple::x86) {
802       this->resetDataLayout("e-m:e-p:32:32-i64:64-n8:16:32-S128");
803     } else if (Triple.getArch() == llvm::Triple::x86_64) {
804       this->resetDataLayout("e-m:e-p:32:32-i64:64-n8:16:32:64-S128");
805     } else if (Triple.getArch() == llvm::Triple::mipsel) {
806       // Handled on mips' setDataLayout.
807     } else {
808       assert(Triple.getArch() == llvm::Triple::le32);
809       this->resetDataLayout("e-p:32:32-i64:64");
810     }
811   }
812 };
813 
814 // WebAssembly target
815 template <typename Target>
816 class WebAssemblyOSTargetInfo : public OSTargetInfo<Target> {
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const817   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
818                     MacroBuilder &Builder) const final {
819     // A common platform macro.
820     if (Opts.POSIXThreads)
821       Builder.defineMacro("_REENTRANT");
822     // Follow g++ convention and predefine _GNU_SOURCE for C++.
823     if (Opts.CPlusPlus)
824       Builder.defineMacro("_GNU_SOURCE");
825   }
826 
827   // As an optimization, group static init code together in a section.
getStaticInitSectionSpecifier() const828   const char *getStaticInitSectionSpecifier() const final {
829     return ".text.__startup";
830   }
831 
832 public:
WebAssemblyOSTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)833   explicit WebAssemblyOSTargetInfo(const llvm::Triple &Triple,
834                                    const TargetOptions &Opts)
835       : OSTargetInfo<Target>(Triple, Opts) {
836     this->MCountName = "__mcount";
837     this->TheCXXABI.set(TargetCXXABI::WebAssembly);
838   }
839 };
840 
841 //===----------------------------------------------------------------------===//
842 // Specific target implementations.
843 //===----------------------------------------------------------------------===//
844 
845 // PPC abstract base class
846 class PPCTargetInfo : public TargetInfo {
847   static const Builtin::Info BuiltinInfo[];
848   static const char * const GCCRegNames[];
849   static const TargetInfo::GCCRegAlias GCCRegAliases[];
850   std::string CPU;
851 
852   // Target cpu features.
853   bool HasVSX;
854   bool HasP8Vector;
855   bool HasP8Crypto;
856   bool HasDirectMove;
857   bool HasQPX;
858   bool HasHTM;
859   bool HasBPERMD;
860   bool HasExtDiv;
861 
862 protected:
863   std::string ABI;
864 
865 public:
PPCTargetInfo(const llvm::Triple & Triple,const TargetOptions &)866   PPCTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
867     : TargetInfo(Triple), HasVSX(false), HasP8Vector(false),
868       HasP8Crypto(false), HasDirectMove(false), HasQPX(false), HasHTM(false),
869       HasBPERMD(false), HasExtDiv(false) {
870     BigEndian = (Triple.getArch() != llvm::Triple::ppc64le);
871     SimdDefaultAlign = 128;
872     LongDoubleWidth = LongDoubleAlign = 128;
873     LongDoubleFormat = &llvm::APFloat::PPCDoubleDouble;
874   }
875 
876   /// \brief Flags for architecture specific defines.
877   typedef enum {
878     ArchDefineNone  = 0,
879     ArchDefineName  = 1 << 0, // <name> is substituted for arch name.
880     ArchDefinePpcgr = 1 << 1,
881     ArchDefinePpcsq = 1 << 2,
882     ArchDefine440   = 1 << 3,
883     ArchDefine603   = 1 << 4,
884     ArchDefine604   = 1 << 5,
885     ArchDefinePwr4  = 1 << 6,
886     ArchDefinePwr5  = 1 << 7,
887     ArchDefinePwr5x = 1 << 8,
888     ArchDefinePwr6  = 1 << 9,
889     ArchDefinePwr6x = 1 << 10,
890     ArchDefinePwr7  = 1 << 11,
891     ArchDefinePwr8  = 1 << 12,
892     ArchDefinePwr9  = 1 << 13,
893     ArchDefineA2    = 1 << 14,
894     ArchDefineA2q   = 1 << 15
895   } ArchDefineTypes;
896 
897   // Note: GCC recognizes the following additional cpus:
898   //  401, 403, 405, 405fp, 440fp, 464, 464fp, 476, 476fp, 505, 740, 801,
899   //  821, 823, 8540, 8548, e300c2, e300c3, e500mc64, e6500, 860, cell,
900   //  titan, rs64.
setCPU(const std::string & Name)901   bool setCPU(const std::string &Name) override {
902     bool CPUKnown = llvm::StringSwitch<bool>(Name)
903       .Case("generic", true)
904       .Case("440", true)
905       .Case("450", true)
906       .Case("601", true)
907       .Case("602", true)
908       .Case("603", true)
909       .Case("603e", true)
910       .Case("603ev", true)
911       .Case("604", true)
912       .Case("604e", true)
913       .Case("620", true)
914       .Case("630", true)
915       .Case("g3", true)
916       .Case("7400", true)
917       .Case("g4", true)
918       .Case("7450", true)
919       .Case("g4+", true)
920       .Case("750", true)
921       .Case("970", true)
922       .Case("g5", true)
923       .Case("a2", true)
924       .Case("a2q", true)
925       .Case("e500mc", true)
926       .Case("e5500", true)
927       .Case("power3", true)
928       .Case("pwr3", true)
929       .Case("power4", true)
930       .Case("pwr4", true)
931       .Case("power5", true)
932       .Case("pwr5", true)
933       .Case("power5x", true)
934       .Case("pwr5x", true)
935       .Case("power6", true)
936       .Case("pwr6", true)
937       .Case("power6x", true)
938       .Case("pwr6x", true)
939       .Case("power7", true)
940       .Case("pwr7", true)
941       .Case("power8", true)
942       .Case("pwr8", true)
943       .Case("power9", true)
944       .Case("pwr9", true)
945       .Case("powerpc", true)
946       .Case("ppc", true)
947       .Case("powerpc64", true)
948       .Case("ppc64", true)
949       .Case("powerpc64le", true)
950       .Case("ppc64le", true)
951       .Default(false);
952 
953     if (CPUKnown)
954       CPU = Name;
955 
956     return CPUKnown;
957   }
958 
959 
getABI() const960   StringRef getABI() const override { return ABI; }
961 
getTargetBuiltins() const962   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
963     return llvm::makeArrayRef(BuiltinInfo,
964                              clang::PPC::LastTSBuiltin-Builtin::FirstTSBuiltin);
965   }
966 
isCLZForZeroUndef() const967   bool isCLZForZeroUndef() const override { return false; }
968 
969   void getTargetDefines(const LangOptions &Opts,
970                         MacroBuilder &Builder) const override;
971 
972   bool
973   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
974                  StringRef CPU,
975                  const std::vector<std::string> &FeaturesVec) const override;
976 
977   bool handleTargetFeatures(std::vector<std::string> &Features,
978                             DiagnosticsEngine &Diags) override;
979   bool hasFeature(StringRef Feature) const override;
980   void setFeatureEnabled(llvm::StringMap<bool> &Features, StringRef Name,
981                          bool Enabled) const override;
982 
983   ArrayRef<const char *> getGCCRegNames() const override;
984   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const985   bool validateAsmConstraint(const char *&Name,
986                              TargetInfo::ConstraintInfo &Info) const override {
987     switch (*Name) {
988     default: return false;
989     case 'O': // Zero
990       break;
991     case 'b': // Base register
992     case 'f': // Floating point register
993       Info.setAllowsRegister();
994       break;
995     // FIXME: The following are added to allow parsing.
996     // I just took a guess at what the actions should be.
997     // Also, is more specific checking needed?  I.e. specific registers?
998     case 'd': // Floating point register (containing 64-bit value)
999     case 'v': // Altivec vector register
1000       Info.setAllowsRegister();
1001       break;
1002     case 'w':
1003       switch (Name[1]) {
1004         case 'd':// VSX vector register to hold vector double data
1005         case 'f':// VSX vector register to hold vector float data
1006         case 's':// VSX vector register to hold scalar float data
1007         case 'a':// Any VSX register
1008         case 'c':// An individual CR bit
1009           break;
1010         default:
1011           return false;
1012       }
1013       Info.setAllowsRegister();
1014       Name++; // Skip over 'w'.
1015       break;
1016     case 'h': // `MQ', `CTR', or `LINK' register
1017     case 'q': // `MQ' register
1018     case 'c': // `CTR' register
1019     case 'l': // `LINK' register
1020     case 'x': // `CR' register (condition register) number 0
1021     case 'y': // `CR' register (condition register)
1022     case 'z': // `XER[CA]' carry bit (part of the XER register)
1023       Info.setAllowsRegister();
1024       break;
1025     case 'I': // Signed 16-bit constant
1026     case 'J': // Unsigned 16-bit constant shifted left 16 bits
1027               //  (use `L' instead for SImode constants)
1028     case 'K': // Unsigned 16-bit constant
1029     case 'L': // Signed 16-bit constant shifted left 16 bits
1030     case 'M': // Constant larger than 31
1031     case 'N': // Exact power of 2
1032     case 'P': // Constant whose negation is a signed 16-bit constant
1033     case 'G': // Floating point constant that can be loaded into a
1034               // register with one instruction per word
1035     case 'H': // Integer/Floating point constant that can be loaded
1036               // into a register using three instructions
1037       break;
1038     case 'm': // Memory operand. Note that on PowerPC targets, m can
1039               // include addresses that update the base register. It
1040               // is therefore only safe to use `m' in an asm statement
1041               // if that asm statement accesses the operand exactly once.
1042               // The asm statement must also use `%U<opno>' as a
1043               // placeholder for the "update" flag in the corresponding
1044               // load or store instruction. For example:
1045               // asm ("st%U0 %1,%0" : "=m" (mem) : "r" (val));
1046               // is correct but:
1047               // asm ("st %1,%0" : "=m" (mem) : "r" (val));
1048               // is not. Use es rather than m if you don't want the base
1049               // register to be updated.
1050     case 'e':
1051       if (Name[1] != 's')
1052           return false;
1053               // es: A "stable" memory operand; that is, one which does not
1054               // include any automodification of the base register. Unlike
1055               // `m', this constraint can be used in asm statements that
1056               // might access the operand several times, or that might not
1057               // access it at all.
1058       Info.setAllowsMemory();
1059       Name++; // Skip over 'e'.
1060       break;
1061     case 'Q': // Memory operand that is an offset from a register (it is
1062               // usually better to use `m' or `es' in asm statements)
1063     case 'Z': // Memory operand that is an indexed or indirect from a
1064               // register (it is usually better to use `m' or `es' in
1065               // asm statements)
1066       Info.setAllowsMemory();
1067       Info.setAllowsRegister();
1068       break;
1069     case 'R': // AIX TOC entry
1070     case 'a': // Address operand that is an indexed or indirect from a
1071               // register (`p' is preferable for asm statements)
1072     case 'S': // Constant suitable as a 64-bit mask operand
1073     case 'T': // Constant suitable as a 32-bit mask operand
1074     case 'U': // System V Release 4 small data area reference
1075     case 't': // AND masks that can be performed by two rldic{l, r}
1076               // instructions
1077     case 'W': // Vector constant that does not require memory
1078     case 'j': // Vector constant that is all zeros.
1079       break;
1080     // End FIXME.
1081     }
1082     return true;
1083   }
convertConstraint(const char * & Constraint) const1084   std::string convertConstraint(const char *&Constraint) const override {
1085     std::string R;
1086     switch (*Constraint) {
1087     case 'e':
1088     case 'w':
1089       // Two-character constraint; add "^" hint for later parsing.
1090       R = std::string("^") + std::string(Constraint, 2);
1091       Constraint++;
1092       break;
1093     default:
1094       return TargetInfo::convertConstraint(Constraint);
1095     }
1096     return R;
1097   }
getClobbers() const1098   const char *getClobbers() const override {
1099     return "";
1100   }
getEHDataRegisterNumber(unsigned RegNo) const1101   int getEHDataRegisterNumber(unsigned RegNo) const override {
1102     if (RegNo == 0) return 3;
1103     if (RegNo == 1) return 4;
1104     return -1;
1105   }
1106 
hasSjLjLowering() const1107   bool hasSjLjLowering() const override {
1108     return true;
1109   }
1110 
useFloat128ManglingForLongDouble() const1111   bool useFloat128ManglingForLongDouble() const override {
1112     return LongDoubleWidth == 128 &&
1113            LongDoubleFormat == &llvm::APFloat::PPCDoubleDouble &&
1114            getTriple().isOSBinFormatELF();
1115   }
1116 };
1117 
1118 const Builtin::Info PPCTargetInfo::BuiltinInfo[] = {
1119 #define BUILTIN(ID, TYPE, ATTRS) \
1120   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
1121 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
1122   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
1123 #include "clang/Basic/BuiltinsPPC.def"
1124 };
1125 
1126 /// handleTargetFeatures - Perform initialization based on the user
1127 /// configured set of features.
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)1128 bool PPCTargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
1129                                          DiagnosticsEngine &Diags) {
1130   for (const auto &Feature : Features) {
1131     if (Feature == "+vsx") {
1132       HasVSX = true;
1133     } else if (Feature == "+bpermd") {
1134       HasBPERMD = true;
1135     } else if (Feature == "+extdiv") {
1136       HasExtDiv = true;
1137     } else if (Feature == "+power8-vector") {
1138       HasP8Vector = true;
1139     } else if (Feature == "+crypto") {
1140       HasP8Crypto = true;
1141     } else if (Feature == "+direct-move") {
1142       HasDirectMove = true;
1143     } else if (Feature == "+qpx") {
1144       HasQPX = true;
1145     } else if (Feature == "+htm") {
1146       HasHTM = true;
1147     } else if (Feature == "+float128") {
1148       HasFloat128 = true;
1149     }
1150     // TODO: Finish this list and add an assert that we've handled them
1151     // all.
1152   }
1153 
1154   return true;
1155 }
1156 
1157 /// PPCTargetInfo::getTargetDefines - Return a set of the PowerPC-specific
1158 /// #defines that are not tied to a specific subtarget.
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const1159 void PPCTargetInfo::getTargetDefines(const LangOptions &Opts,
1160                                      MacroBuilder &Builder) const {
1161   // Target identification.
1162   Builder.defineMacro("__ppc__");
1163   Builder.defineMacro("__PPC__");
1164   Builder.defineMacro("_ARCH_PPC");
1165   Builder.defineMacro("__powerpc__");
1166   Builder.defineMacro("__POWERPC__");
1167   if (PointerWidth == 64) {
1168     Builder.defineMacro("_ARCH_PPC64");
1169     Builder.defineMacro("__powerpc64__");
1170     Builder.defineMacro("__ppc64__");
1171     Builder.defineMacro("__PPC64__");
1172   }
1173 
1174   // Target properties.
1175   if (getTriple().getArch() == llvm::Triple::ppc64le) {
1176     Builder.defineMacro("_LITTLE_ENDIAN");
1177   } else {
1178     if (getTriple().getOS() != llvm::Triple::NetBSD &&
1179         getTriple().getOS() != llvm::Triple::OpenBSD)
1180       Builder.defineMacro("_BIG_ENDIAN");
1181   }
1182 
1183   // ABI options.
1184   if (ABI == "elfv1" || ABI == "elfv1-qpx")
1185     Builder.defineMacro("_CALL_ELF", "1");
1186   if (ABI == "elfv2")
1187     Builder.defineMacro("_CALL_ELF", "2");
1188 
1189   // Subtarget options.
1190   Builder.defineMacro("__NATURAL_ALIGNMENT__");
1191   Builder.defineMacro("__REGISTER_PREFIX__", "");
1192 
1193   // FIXME: Should be controlled by command line option.
1194   if (LongDoubleWidth == 128)
1195     Builder.defineMacro("__LONG_DOUBLE_128__");
1196 
1197   if (Opts.AltiVec) {
1198     Builder.defineMacro("__VEC__", "10206");
1199     Builder.defineMacro("__ALTIVEC__");
1200   }
1201 
1202   // CPU identification.
1203   ArchDefineTypes defs = (ArchDefineTypes)llvm::StringSwitch<int>(CPU)
1204     .Case("440",   ArchDefineName)
1205     .Case("450",   ArchDefineName | ArchDefine440)
1206     .Case("601",   ArchDefineName)
1207     .Case("602",   ArchDefineName | ArchDefinePpcgr)
1208     .Case("603",   ArchDefineName | ArchDefinePpcgr)
1209     .Case("603e",  ArchDefineName | ArchDefine603 | ArchDefinePpcgr)
1210     .Case("603ev", ArchDefineName | ArchDefine603 | ArchDefinePpcgr)
1211     .Case("604",   ArchDefineName | ArchDefinePpcgr)
1212     .Case("604e",  ArchDefineName | ArchDefine604 | ArchDefinePpcgr)
1213     .Case("620",   ArchDefineName | ArchDefinePpcgr)
1214     .Case("630",   ArchDefineName | ArchDefinePpcgr)
1215     .Case("7400",  ArchDefineName | ArchDefinePpcgr)
1216     .Case("7450",  ArchDefineName | ArchDefinePpcgr)
1217     .Case("750",   ArchDefineName | ArchDefinePpcgr)
1218     .Case("970",   ArchDefineName | ArchDefinePwr4 | ArchDefinePpcgr
1219                      | ArchDefinePpcsq)
1220     .Case("a2",    ArchDefineA2)
1221     .Case("a2q",   ArchDefineName | ArchDefineA2 | ArchDefineA2q)
1222     .Case("pwr3",  ArchDefinePpcgr)
1223     .Case("pwr4",  ArchDefineName | ArchDefinePpcgr | ArchDefinePpcsq)
1224     .Case("pwr5",  ArchDefineName | ArchDefinePwr4 | ArchDefinePpcgr
1225                      | ArchDefinePpcsq)
1226     .Case("pwr5x", ArchDefineName | ArchDefinePwr5 | ArchDefinePwr4
1227                      | ArchDefinePpcgr | ArchDefinePpcsq)
1228     .Case("pwr6",  ArchDefineName | ArchDefinePwr5x | ArchDefinePwr5
1229                      | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1230     .Case("pwr6x", ArchDefineName | ArchDefinePwr6 | ArchDefinePwr5x
1231                      | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr
1232                      | ArchDefinePpcsq)
1233     .Case("pwr7",  ArchDefineName | ArchDefinePwr6x | ArchDefinePwr6
1234                      | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4
1235                      | ArchDefinePpcgr | ArchDefinePpcsq)
1236     .Case("pwr8",  ArchDefineName | ArchDefinePwr7 | ArchDefinePwr6x
1237                      | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5
1238                      | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1239     .Case("pwr9",  ArchDefineName | ArchDefinePwr8 | ArchDefinePwr7
1240                      | ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x
1241                      | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr
1242                      | ArchDefinePpcsq)
1243     .Case("power3",  ArchDefinePpcgr)
1244     .Case("power4",  ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1245     .Case("power5",  ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr
1246                        | ArchDefinePpcsq)
1247     .Case("power5x", ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4
1248                        | ArchDefinePpcgr | ArchDefinePpcsq)
1249     .Case("power6",  ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5
1250                        | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1251     .Case("power6x", ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x
1252                        | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr
1253                        | ArchDefinePpcsq)
1254     .Case("power7",  ArchDefinePwr7 | ArchDefinePwr6x | ArchDefinePwr6
1255                        | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4
1256                        | ArchDefinePpcgr | ArchDefinePpcsq)
1257     .Case("power8",  ArchDefinePwr8 | ArchDefinePwr7 | ArchDefinePwr6x
1258                        | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5
1259                        | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1260     .Case("power9",  ArchDefinePwr9 | ArchDefinePwr8 | ArchDefinePwr7
1261                        | ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x
1262                        | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr
1263                        | ArchDefinePpcsq)
1264     .Default(ArchDefineNone);
1265 
1266   if (defs & ArchDefineName)
1267     Builder.defineMacro(Twine("_ARCH_", StringRef(CPU).upper()));
1268   if (defs & ArchDefinePpcgr)
1269     Builder.defineMacro("_ARCH_PPCGR");
1270   if (defs & ArchDefinePpcsq)
1271     Builder.defineMacro("_ARCH_PPCSQ");
1272   if (defs & ArchDefine440)
1273     Builder.defineMacro("_ARCH_440");
1274   if (defs & ArchDefine603)
1275     Builder.defineMacro("_ARCH_603");
1276   if (defs & ArchDefine604)
1277     Builder.defineMacro("_ARCH_604");
1278   if (defs & ArchDefinePwr4)
1279     Builder.defineMacro("_ARCH_PWR4");
1280   if (defs & ArchDefinePwr5)
1281     Builder.defineMacro("_ARCH_PWR5");
1282   if (defs & ArchDefinePwr5x)
1283     Builder.defineMacro("_ARCH_PWR5X");
1284   if (defs & ArchDefinePwr6)
1285     Builder.defineMacro("_ARCH_PWR6");
1286   if (defs & ArchDefinePwr6x)
1287     Builder.defineMacro("_ARCH_PWR6X");
1288   if (defs & ArchDefinePwr7)
1289     Builder.defineMacro("_ARCH_PWR7");
1290   if (defs & ArchDefinePwr8)
1291     Builder.defineMacro("_ARCH_PWR8");
1292   if (defs & ArchDefinePwr9)
1293     Builder.defineMacro("_ARCH_PWR9");
1294   if (defs & ArchDefineA2)
1295     Builder.defineMacro("_ARCH_A2");
1296   if (defs & ArchDefineA2q) {
1297     Builder.defineMacro("_ARCH_A2Q");
1298     Builder.defineMacro("_ARCH_QP");
1299   }
1300 
1301   if (getTriple().getVendor() == llvm::Triple::BGQ) {
1302     Builder.defineMacro("__bg__");
1303     Builder.defineMacro("__THW_BLUEGENE__");
1304     Builder.defineMacro("__bgq__");
1305     Builder.defineMacro("__TOS_BGQ__");
1306   }
1307 
1308   if (HasVSX)
1309     Builder.defineMacro("__VSX__");
1310   if (HasP8Vector)
1311     Builder.defineMacro("__POWER8_VECTOR__");
1312   if (HasP8Crypto)
1313     Builder.defineMacro("__CRYPTO__");
1314   if (HasHTM)
1315     Builder.defineMacro("__HTM__");
1316   if (HasFloat128)
1317     Builder.defineMacro("__FLOAT128__");
1318 
1319   Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
1320   Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
1321   Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
1322   if (PointerWidth == 64)
1323     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
1324 
1325   // FIXME: The following are not yet generated here by Clang, but are
1326   //        generated by GCC:
1327   //
1328   //   _SOFT_FLOAT_
1329   //   __RECIP_PRECISION__
1330   //   __APPLE_ALTIVEC__
1331   //   __RECIP__
1332   //   __RECIPF__
1333   //   __RSQRTE__
1334   //   __RSQRTEF__
1335   //   _SOFT_DOUBLE_
1336   //   __NO_LWSYNC__
1337   //   __HAVE_BSWAP__
1338   //   __LONGDOUBLE128
1339   //   __CMODEL_MEDIUM__
1340   //   __CMODEL_LARGE__
1341   //   _CALL_SYSV
1342   //   _CALL_DARWIN
1343   //   __NO_FPRS__
1344 }
1345 
1346 // Handle explicit options being passed to the compiler here: if we've
1347 // explicitly turned off vsx and turned on power8-vector or direct-move then
1348 // go ahead and error since the customer has expressed a somewhat incompatible
1349 // set of options.
ppcUserFeaturesCheck(DiagnosticsEngine & Diags,const std::vector<std::string> & FeaturesVec)1350 static bool ppcUserFeaturesCheck(DiagnosticsEngine &Diags,
1351                                  const std::vector<std::string> &FeaturesVec) {
1352 
1353   if (std::find(FeaturesVec.begin(), FeaturesVec.end(), "-vsx") !=
1354       FeaturesVec.end()) {
1355     if (std::find(FeaturesVec.begin(), FeaturesVec.end(), "+power8-vector") !=
1356         FeaturesVec.end()) {
1357       Diags.Report(diag::err_opt_not_valid_with_opt) << "-mpower8-vector"
1358                                                      << "-mno-vsx";
1359       return false;
1360     }
1361 
1362     if (std::find(FeaturesVec.begin(), FeaturesVec.end(), "+direct-move") !=
1363         FeaturesVec.end()) {
1364       Diags.Report(diag::err_opt_not_valid_with_opt) << "-mdirect-move"
1365                                                      << "-mno-vsx";
1366       return false;
1367     }
1368 
1369     if (std::find(FeaturesVec.begin(), FeaturesVec.end(), "+float128") !=
1370         FeaturesVec.end()) {
1371       Diags.Report(diag::err_opt_not_valid_with_opt) << "-mfloat128"
1372                                                      << "-mno-vsx";
1373       return false;
1374     }
1375   }
1376 
1377   return true;
1378 }
1379 
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const1380 bool PPCTargetInfo::initFeatureMap(
1381     llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
1382     const std::vector<std::string> &FeaturesVec) const {
1383   Features["altivec"] = llvm::StringSwitch<bool>(CPU)
1384     .Case("7400", true)
1385     .Case("g4", true)
1386     .Case("7450", true)
1387     .Case("g4+", true)
1388     .Case("970", true)
1389     .Case("g5", true)
1390     .Case("pwr6", true)
1391     .Case("pwr7", true)
1392     .Case("pwr8", true)
1393     .Case("pwr9", true)
1394     .Case("ppc64", true)
1395     .Case("ppc64le", true)
1396     .Default(false);
1397 
1398   Features["qpx"] = (CPU == "a2q");
1399   Features["crypto"] = llvm::StringSwitch<bool>(CPU)
1400     .Case("ppc64le", true)
1401     .Case("pwr9", true)
1402     .Case("pwr8", true)
1403     .Default(false);
1404   Features["power8-vector"] = llvm::StringSwitch<bool>(CPU)
1405     .Case("ppc64le", true)
1406     .Case("pwr9", true)
1407     .Case("pwr8", true)
1408     .Default(false);
1409   Features["bpermd"] = llvm::StringSwitch<bool>(CPU)
1410     .Case("ppc64le", true)
1411     .Case("pwr9", true)
1412     .Case("pwr8", true)
1413     .Case("pwr7", true)
1414     .Default(false);
1415   Features["extdiv"] = llvm::StringSwitch<bool>(CPU)
1416     .Case("ppc64le", true)
1417     .Case("pwr9", true)
1418     .Case("pwr8", true)
1419     .Case("pwr7", true)
1420     .Default(false);
1421   Features["direct-move"] = llvm::StringSwitch<bool>(CPU)
1422     .Case("ppc64le", true)
1423     .Case("pwr9", true)
1424     .Case("pwr8", true)
1425     .Default(false);
1426   Features["vsx"] = llvm::StringSwitch<bool>(CPU)
1427     .Case("ppc64le", true)
1428     .Case("pwr9", true)
1429     .Case("pwr8", true)
1430     .Case("pwr7", true)
1431     .Default(false);
1432 
1433   if (!ppcUserFeaturesCheck(Diags, FeaturesVec))
1434     return false;
1435 
1436   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
1437 }
1438 
hasFeature(StringRef Feature) const1439 bool PPCTargetInfo::hasFeature(StringRef Feature) const {
1440   return llvm::StringSwitch<bool>(Feature)
1441     .Case("powerpc", true)
1442     .Case("vsx", HasVSX)
1443     .Case("power8-vector", HasP8Vector)
1444     .Case("crypto", HasP8Crypto)
1445     .Case("direct-move", HasDirectMove)
1446     .Case("qpx", HasQPX)
1447     .Case("htm", HasHTM)
1448     .Case("bpermd", HasBPERMD)
1449     .Case("extdiv", HasExtDiv)
1450     .Case("float128", HasFloat128)
1451     .Default(false);
1452 }
1453 
setFeatureEnabled(llvm::StringMap<bool> & Features,StringRef Name,bool Enabled) const1454 void PPCTargetInfo::setFeatureEnabled(llvm::StringMap<bool> &Features,
1455                                       StringRef Name, bool Enabled) const {
1456   // If we're enabling direct-move or power8-vector go ahead and enable vsx
1457   // as well. Do the inverse if we're disabling vsx. We'll diagnose any user
1458   // incompatible options.
1459   if (Enabled) {
1460     if (Name == "direct-move") {
1461       Features[Name] = Features["vsx"] = true;
1462     } else if (Name == "power8-vector") {
1463       Features[Name] = Features["vsx"] = true;
1464     } else if (Name == "float128") {
1465       Features[Name] = Features["vsx"] = true;
1466     } else {
1467       Features[Name] = true;
1468     }
1469   } else {
1470     if (Name == "vsx") {
1471       Features[Name] = Features["direct-move"] = Features["power8-vector"] =
1472           Features["float128"] = false;
1473     } else {
1474       Features[Name] = false;
1475     }
1476   }
1477 }
1478 
1479 const char * const PPCTargetInfo::GCCRegNames[] = {
1480   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
1481   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
1482   "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
1483   "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
1484   "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
1485   "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
1486   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
1487   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
1488   "mq", "lr", "ctr", "ap",
1489   "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7",
1490   "xer",
1491   "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
1492   "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
1493   "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
1494   "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
1495   "vrsave", "vscr",
1496   "spe_acc", "spefscr",
1497   "sfp"
1498 };
1499 
getGCCRegNames() const1500 ArrayRef<const char*> PPCTargetInfo::getGCCRegNames() const {
1501   return llvm::makeArrayRef(GCCRegNames);
1502 }
1503 
1504 const TargetInfo::GCCRegAlias PPCTargetInfo::GCCRegAliases[] = {
1505   // While some of these aliases do map to different registers
1506   // they still share the same register name.
1507   { { "0" }, "r0" },
1508   { { "1"}, "r1" },
1509   { { "2" }, "r2" },
1510   { { "3" }, "r3" },
1511   { { "4" }, "r4" },
1512   { { "5" }, "r5" },
1513   { { "6" }, "r6" },
1514   { { "7" }, "r7" },
1515   { { "8" }, "r8" },
1516   { { "9" }, "r9" },
1517   { { "10" }, "r10" },
1518   { { "11" }, "r11" },
1519   { { "12" }, "r12" },
1520   { { "13" }, "r13" },
1521   { { "14" }, "r14" },
1522   { { "15" }, "r15" },
1523   { { "16" }, "r16" },
1524   { { "17" }, "r17" },
1525   { { "18" }, "r18" },
1526   { { "19" }, "r19" },
1527   { { "20" }, "r20" },
1528   { { "21" }, "r21" },
1529   { { "22" }, "r22" },
1530   { { "23" }, "r23" },
1531   { { "24" }, "r24" },
1532   { { "25" }, "r25" },
1533   { { "26" }, "r26" },
1534   { { "27" }, "r27" },
1535   { { "28" }, "r28" },
1536   { { "29" }, "r29" },
1537   { { "30" }, "r30" },
1538   { { "31" }, "r31" },
1539   { { "fr0" }, "f0" },
1540   { { "fr1" }, "f1" },
1541   { { "fr2" }, "f2" },
1542   { { "fr3" }, "f3" },
1543   { { "fr4" }, "f4" },
1544   { { "fr5" }, "f5" },
1545   { { "fr6" }, "f6" },
1546   { { "fr7" }, "f7" },
1547   { { "fr8" }, "f8" },
1548   { { "fr9" }, "f9" },
1549   { { "fr10" }, "f10" },
1550   { { "fr11" }, "f11" },
1551   { { "fr12" }, "f12" },
1552   { { "fr13" }, "f13" },
1553   { { "fr14" }, "f14" },
1554   { { "fr15" }, "f15" },
1555   { { "fr16" }, "f16" },
1556   { { "fr17" }, "f17" },
1557   { { "fr18" }, "f18" },
1558   { { "fr19" }, "f19" },
1559   { { "fr20" }, "f20" },
1560   { { "fr21" }, "f21" },
1561   { { "fr22" }, "f22" },
1562   { { "fr23" }, "f23" },
1563   { { "fr24" }, "f24" },
1564   { { "fr25" }, "f25" },
1565   { { "fr26" }, "f26" },
1566   { { "fr27" }, "f27" },
1567   { { "fr28" }, "f28" },
1568   { { "fr29" }, "f29" },
1569   { { "fr30" }, "f30" },
1570   { { "fr31" }, "f31" },
1571   { { "cc" }, "cr0" },
1572 };
1573 
getGCCRegAliases() const1574 ArrayRef<TargetInfo::GCCRegAlias> PPCTargetInfo::getGCCRegAliases() const {
1575   return llvm::makeArrayRef(GCCRegAliases);
1576 }
1577 
1578 class PPC32TargetInfo : public PPCTargetInfo {
1579 public:
PPC32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)1580   PPC32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
1581       : PPCTargetInfo(Triple, Opts) {
1582     resetDataLayout("E-m:e-p:32:32-i64:64-n32");
1583 
1584     switch (getTriple().getOS()) {
1585     case llvm::Triple::Linux:
1586     case llvm::Triple::FreeBSD:
1587     case llvm::Triple::NetBSD:
1588       SizeType = UnsignedInt;
1589       PtrDiffType = SignedInt;
1590       IntPtrType = SignedInt;
1591       break;
1592     default:
1593       break;
1594     }
1595 
1596     if (getTriple().getOS() == llvm::Triple::FreeBSD) {
1597       LongDoubleWidth = LongDoubleAlign = 64;
1598       LongDoubleFormat = &llvm::APFloat::IEEEdouble;
1599     }
1600 
1601     // PPC32 supports atomics up to 4 bytes.
1602     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32;
1603   }
1604 
getBuiltinVaListKind() const1605   BuiltinVaListKind getBuiltinVaListKind() const override {
1606     // This is the ELF definition, and is overridden by the Darwin sub-target
1607     return TargetInfo::PowerABIBuiltinVaList;
1608   }
1609 };
1610 
1611 // Note: ABI differences may eventually require us to have a separate
1612 // TargetInfo for little endian.
1613 class PPC64TargetInfo : public PPCTargetInfo {
1614 public:
PPC64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)1615   PPC64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
1616       : PPCTargetInfo(Triple, Opts) {
1617     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
1618     IntMaxType = SignedLong;
1619     Int64Type = SignedLong;
1620 
1621     if ((Triple.getArch() == llvm::Triple::ppc64le)) {
1622       resetDataLayout("e-m:e-i64:64-n32:64");
1623       ABI = "elfv2";
1624     } else {
1625       resetDataLayout("E-m:e-i64:64-n32:64");
1626       ABI = "elfv1";
1627     }
1628 
1629     switch (getTriple().getOS()) {
1630     case llvm::Triple::FreeBSD:
1631       LongDoubleWidth = LongDoubleAlign = 64;
1632       LongDoubleFormat = &llvm::APFloat::IEEEdouble;
1633       break;
1634     case llvm::Triple::NetBSD:
1635       IntMaxType = SignedLongLong;
1636       Int64Type = SignedLongLong;
1637       break;
1638     default:
1639       break;
1640     }
1641 
1642     // PPC64 supports atomics up to 8 bytes.
1643     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
1644   }
getBuiltinVaListKind() const1645   BuiltinVaListKind getBuiltinVaListKind() const override {
1646     return TargetInfo::CharPtrBuiltinVaList;
1647   }
1648   // PPC64 Linux-specific ABI options.
setABI(const std::string & Name)1649   bool setABI(const std::string &Name) override {
1650     if (Name == "elfv1" || Name == "elfv1-qpx" || Name == "elfv2") {
1651       ABI = Name;
1652       return true;
1653     }
1654     return false;
1655   }
1656 };
1657 
1658 class DarwinPPC32TargetInfo : public DarwinTargetInfo<PPC32TargetInfo> {
1659 public:
DarwinPPC32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)1660   DarwinPPC32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
1661       : DarwinTargetInfo<PPC32TargetInfo>(Triple, Opts) {
1662     HasAlignMac68kSupport = true;
1663     BoolWidth = BoolAlign = 32; //XXX support -mone-byte-bool?
1664     PtrDiffType = SignedInt; // for http://llvm.org/bugs/show_bug.cgi?id=15726
1665     LongLongAlign = 32;
1666     SuitableAlign = 128;
1667     resetDataLayout("E-m:o-p:32:32-f64:32:64-n32");
1668   }
getBuiltinVaListKind() const1669   BuiltinVaListKind getBuiltinVaListKind() const override {
1670     return TargetInfo::CharPtrBuiltinVaList;
1671   }
1672 };
1673 
1674 class DarwinPPC64TargetInfo : public DarwinTargetInfo<PPC64TargetInfo> {
1675 public:
DarwinPPC64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)1676   DarwinPPC64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
1677       : DarwinTargetInfo<PPC64TargetInfo>(Triple, Opts) {
1678     HasAlignMac68kSupport = true;
1679     SuitableAlign = 128;
1680     resetDataLayout("E-m:o-i64:64-n32:64");
1681   }
1682 };
1683 
1684 static const unsigned NVPTXAddrSpaceMap[] = {
1685     1, // opencl_global
1686     3, // opencl_local
1687     4, // opencl_constant
1688     // FIXME: generic has to be added to the target
1689     0, // opencl_generic
1690     1, // cuda_device
1691     4, // cuda_constant
1692     3, // cuda_shared
1693 };
1694 
1695 class NVPTXTargetInfo : public TargetInfo {
1696   static const char *const GCCRegNames[];
1697   static const Builtin::Info BuiltinInfo[];
1698   CudaArch GPU;
1699 
1700 public:
NVPTXTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)1701   NVPTXTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
1702       : TargetInfo(Triple) {
1703     BigEndian = false;
1704     TLSSupported = false;
1705     LongWidth = LongAlign = 64;
1706     AddrSpaceMap = &NVPTXAddrSpaceMap;
1707     UseAddrSpaceMapMangling = true;
1708     // Define available target features
1709     // These must be defined in sorted order!
1710     NoAsmVariants = true;
1711     GPU = CudaArch::SM_20;
1712 
1713     // If possible, get a TargetInfo for our host triple, so we can match its
1714     // types.
1715     llvm::Triple HostTriple(Opts.HostTriple);
1716     if (HostTriple.isNVPTX())
1717       return;
1718     std::unique_ptr<TargetInfo> HostTarget(
1719         AllocateTarget(llvm::Triple(Opts.HostTriple), Opts));
1720     if (!HostTarget) {
1721       return;
1722     }
1723 
1724     PointerWidth = HostTarget->getPointerWidth(/* AddrSpace = */ 0);
1725     PointerAlign = HostTarget->getPointerAlign(/* AddrSpace = */ 0);
1726     BoolWidth = HostTarget->getBoolWidth();
1727     BoolAlign = HostTarget->getBoolAlign();
1728     IntWidth = HostTarget->getIntWidth();
1729     IntAlign = HostTarget->getIntAlign();
1730     HalfWidth = HostTarget->getHalfWidth();
1731     HalfAlign = HostTarget->getHalfAlign();
1732     FloatWidth = HostTarget->getFloatWidth();
1733     FloatAlign = HostTarget->getFloatAlign();
1734     DoubleWidth = HostTarget->getDoubleWidth();
1735     DoubleAlign = HostTarget->getDoubleAlign();
1736     LongWidth = HostTarget->getLongWidth();
1737     LongAlign = HostTarget->getLongAlign();
1738     LongLongWidth = HostTarget->getLongLongWidth();
1739     LongLongAlign = HostTarget->getLongLongAlign();
1740     MinGlobalAlign = HostTarget->getMinGlobalAlign();
1741     DefaultAlignForAttributeAligned =
1742         HostTarget->getDefaultAlignForAttributeAligned();
1743     SizeType = HostTarget->getSizeType();
1744     IntMaxType = HostTarget->getIntMaxType();
1745     PtrDiffType = HostTarget->getPtrDiffType(/* AddrSpace = */ 0);
1746     IntPtrType = HostTarget->getIntPtrType();
1747     WCharType = HostTarget->getWCharType();
1748     WIntType = HostTarget->getWIntType();
1749     Char16Type = HostTarget->getChar16Type();
1750     Char32Type = HostTarget->getChar32Type();
1751     Int64Type = HostTarget->getInt64Type();
1752     SigAtomicType = HostTarget->getSigAtomicType();
1753     ProcessIDType = HostTarget->getProcessIDType();
1754 
1755     UseBitFieldTypeAlignment = HostTarget->useBitFieldTypeAlignment();
1756     UseZeroLengthBitfieldAlignment =
1757         HostTarget->useZeroLengthBitfieldAlignment();
1758     UseExplicitBitFieldAlignment = HostTarget->useExplicitBitFieldAlignment();
1759     ZeroLengthBitfieldBoundary = HostTarget->getZeroLengthBitfieldBoundary();
1760 
1761     // Properties intentionally not copied from host:
1762     // - LargeArrayMinWidth, LargeArrayAlign: Not visible across the
1763     //   host/device boundary.
1764     // - SuitableAlign: Not visible across the host/device boundary, and may
1765     //   correctly be different on host/device, e.g. if host has wider vector
1766     //   types than device.
1767     // - LongDoubleWidth, LongDoubleAlign: nvptx's long double type is the same
1768     //   as its double type, but that's not necessarily true on the host.
1769     //   TODO: nvcc emits a warning when using long double on device; we should
1770     //   do the same.
1771   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const1772   void getTargetDefines(const LangOptions &Opts,
1773                         MacroBuilder &Builder) const override {
1774     Builder.defineMacro("__PTX__");
1775     Builder.defineMacro("__NVPTX__");
1776     if (Opts.CUDAIsDevice) {
1777       // Set __CUDA_ARCH__ for the GPU specified.
1778       std::string CUDAArchCode = [this] {
1779         switch (GPU) {
1780         case CudaArch::UNKNOWN:
1781           assert(false && "No GPU arch when compiling CUDA device code.");
1782           return "";
1783         case CudaArch::SM_20:
1784           return "200";
1785         case CudaArch::SM_21:
1786           return "210";
1787         case CudaArch::SM_30:
1788           return "300";
1789         case CudaArch::SM_32:
1790           return "320";
1791         case CudaArch::SM_35:
1792           return "350";
1793         case CudaArch::SM_37:
1794           return "370";
1795         case CudaArch::SM_50:
1796           return "500";
1797         case CudaArch::SM_52:
1798           return "520";
1799         case CudaArch::SM_53:
1800           return "530";
1801         case CudaArch::SM_60:
1802           return "600";
1803         case CudaArch::SM_61:
1804           return "610";
1805         case CudaArch::SM_62:
1806           return "620";
1807         }
1808         llvm_unreachable("unhandled CudaArch");
1809       }();
1810       Builder.defineMacro("__CUDA_ARCH__", CUDAArchCode);
1811     }
1812   }
getTargetBuiltins() const1813   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
1814     return llvm::makeArrayRef(BuiltinInfo,
1815                          clang::NVPTX::LastTSBuiltin - Builtin::FirstTSBuiltin);
1816   }
hasFeature(StringRef Feature) const1817   bool hasFeature(StringRef Feature) const override {
1818     return Feature == "ptx" || Feature == "nvptx";
1819   }
1820 
1821   ArrayRef<const char *> getGCCRegNames() const override;
getGCCRegAliases() const1822   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
1823     // No aliases.
1824     return None;
1825   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const1826   bool validateAsmConstraint(const char *&Name,
1827                              TargetInfo::ConstraintInfo &Info) const override {
1828     switch (*Name) {
1829     default:
1830       return false;
1831     case 'c':
1832     case 'h':
1833     case 'r':
1834     case 'l':
1835     case 'f':
1836     case 'd':
1837       Info.setAllowsRegister();
1838       return true;
1839     }
1840   }
getClobbers() const1841   const char *getClobbers() const override {
1842     // FIXME: Is this really right?
1843     return "";
1844   }
getBuiltinVaListKind() const1845   BuiltinVaListKind getBuiltinVaListKind() const override {
1846     // FIXME: implement
1847     return TargetInfo::CharPtrBuiltinVaList;
1848   }
setCPU(const std::string & Name)1849   bool setCPU(const std::string &Name) override {
1850     GPU = StringToCudaArch(Name);
1851     return GPU != CudaArch::UNKNOWN;
1852   }
setSupportedOpenCLOpts()1853   void setSupportedOpenCLOpts() override {
1854     auto &Opts = getSupportedOpenCLOpts();
1855     Opts.cl_clang_storage_class_specifiers = 1;
1856     Opts.cl_khr_gl_sharing = 1;
1857     Opts.cl_khr_icd = 1;
1858 
1859     Opts.cl_khr_fp64 = 1;
1860     Opts.cl_khr_byte_addressable_store = 1;
1861     Opts.cl_khr_global_int32_base_atomics = 1;
1862     Opts.cl_khr_global_int32_extended_atomics = 1;
1863     Opts.cl_khr_local_int32_base_atomics = 1;
1864     Opts.cl_khr_local_int32_extended_atomics = 1;
1865   }
1866 };
1867 
1868 const Builtin::Info NVPTXTargetInfo::BuiltinInfo[] = {
1869 #define BUILTIN(ID, TYPE, ATTRS)                                               \
1870   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
1871 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER)                                    \
1872   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
1873 #include "clang/Basic/BuiltinsNVPTX.def"
1874 };
1875 
1876 const char *const NVPTXTargetInfo::GCCRegNames[] = {"r0"};
1877 
getGCCRegNames() const1878 ArrayRef<const char *> NVPTXTargetInfo::getGCCRegNames() const {
1879   return llvm::makeArrayRef(GCCRegNames);
1880 }
1881 
1882 class NVPTX32TargetInfo : public NVPTXTargetInfo {
1883 public:
NVPTX32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)1884   NVPTX32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
1885       : NVPTXTargetInfo(Triple, Opts) {
1886     LongWidth = LongAlign = 32;
1887     PointerWidth = PointerAlign = 32;
1888     SizeType = TargetInfo::UnsignedInt;
1889     PtrDiffType = TargetInfo::SignedInt;
1890     IntPtrType = TargetInfo::SignedInt;
1891     resetDataLayout("e-p:32:32-i64:64-v16:16-v32:32-n16:32:64");
1892   }
1893 };
1894 
1895 class NVPTX64TargetInfo : public NVPTXTargetInfo {
1896 public:
NVPTX64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)1897   NVPTX64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
1898       : NVPTXTargetInfo(Triple, Opts) {
1899     PointerWidth = PointerAlign = 64;
1900     SizeType = TargetInfo::UnsignedLong;
1901     PtrDiffType = TargetInfo::SignedLong;
1902     IntPtrType = TargetInfo::SignedLong;
1903     resetDataLayout("e-i64:64-v16:16-v32:32-n16:32:64");
1904   }
1905 };
1906 
1907 static const unsigned AMDGPUAddrSpaceMap[] = {
1908   1,    // opencl_global
1909   3,    // opencl_local
1910   2,    // opencl_constant
1911   4,    // opencl_generic
1912   1,    // cuda_device
1913   2,    // cuda_constant
1914   3     // cuda_shared
1915 };
1916 
1917 // If you edit the description strings, make sure you update
1918 // getPointerWidthV().
1919 
1920 static const char *const DataLayoutStringR600 =
1921   "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
1922   "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
1923 
1924 static const char *const DataLayoutStringSI =
1925   "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32"
1926   "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
1927   "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
1928 
1929 class AMDGPUTargetInfo final : public TargetInfo {
1930   static const Builtin::Info BuiltinInfo[];
1931   static const char * const GCCRegNames[];
1932 
1933   /// \brief The GPU profiles supported by the AMDGPU target.
1934   enum GPUKind {
1935     GK_NONE,
1936     GK_R600,
1937     GK_R600_DOUBLE_OPS,
1938     GK_R700,
1939     GK_R700_DOUBLE_OPS,
1940     GK_EVERGREEN,
1941     GK_EVERGREEN_DOUBLE_OPS,
1942     GK_NORTHERN_ISLANDS,
1943     GK_CAYMAN,
1944     GK_SOUTHERN_ISLANDS,
1945     GK_SEA_ISLANDS,
1946     GK_VOLCANIC_ISLANDS
1947   } GPU;
1948 
1949   bool hasFP64:1;
1950   bool hasFMAF:1;
1951   bool hasLDEXPF:1;
1952 
isAMDGCN(const llvm::Triple & TT)1953   static bool isAMDGCN(const llvm::Triple &TT) {
1954     return TT.getArch() == llvm::Triple::amdgcn;
1955   }
1956 
1957 public:
AMDGPUTargetInfo(const llvm::Triple & Triple,const TargetOptions &)1958   AMDGPUTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
1959     : TargetInfo(Triple) ,
1960       GPU(isAMDGCN(Triple) ? GK_SOUTHERN_ISLANDS : GK_R600),
1961       hasFP64(false),
1962       hasFMAF(false),
1963       hasLDEXPF(false) {
1964     if (getTriple().getArch() == llvm::Triple::amdgcn) {
1965       hasFP64 = true;
1966       hasFMAF = true;
1967       hasLDEXPF = true;
1968     }
1969 
1970     resetDataLayout(getTriple().getArch() == llvm::Triple::amdgcn ?
1971                     DataLayoutStringSI : DataLayoutStringR600);
1972 
1973     AddrSpaceMap = &AMDGPUAddrSpaceMap;
1974     UseAddrSpaceMapMangling = true;
1975   }
1976 
getPointerWidthV(unsigned AddrSpace) const1977   uint64_t getPointerWidthV(unsigned AddrSpace) const override {
1978     if (GPU <= GK_CAYMAN)
1979       return 32;
1980 
1981     switch(AddrSpace) {
1982       default:
1983         return 64;
1984       case 0:
1985       case 3:
1986       case 5:
1987         return 32;
1988     }
1989   }
1990 
getClobbers() const1991   const char * getClobbers() const override {
1992     return "";
1993   }
1994 
1995   ArrayRef<const char *> getGCCRegNames() const override;
1996 
getGCCRegAliases() const1997   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
1998     return None;
1999   }
2000 
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const2001   bool validateAsmConstraint(const char *&Name,
2002                              TargetInfo::ConstraintInfo &Info) const override {
2003     switch (*Name) {
2004     default: break;
2005     case 'v': // vgpr
2006     case 's': // sgpr
2007       Info.setAllowsRegister();
2008       return true;
2009     }
2010     return false;
2011   }
2012 
2013   bool initFeatureMap(llvm::StringMap<bool> &Features,
2014                       DiagnosticsEngine &Diags, StringRef CPU,
2015                       const std::vector<std::string> &FeatureVec) const override;
2016 
getTargetBuiltins() const2017   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
2018     return llvm::makeArrayRef(BuiltinInfo,
2019                         clang::AMDGPU::LastTSBuiltin - Builtin::FirstTSBuiltin);
2020   }
2021 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const2022   void getTargetDefines(const LangOptions &Opts,
2023                         MacroBuilder &Builder) const override {
2024     if (getTriple().getArch() == llvm::Triple::amdgcn)
2025       Builder.defineMacro("__AMDGCN__");
2026     else
2027       Builder.defineMacro("__R600__");
2028 
2029     if (hasFMAF)
2030       Builder.defineMacro("__HAS_FMAF__");
2031     if (hasLDEXPF)
2032       Builder.defineMacro("__HAS_LDEXPF__");
2033     if (hasFP64)
2034       Builder.defineMacro("__HAS_FP64__");
2035   }
2036 
getBuiltinVaListKind() const2037   BuiltinVaListKind getBuiltinVaListKind() const override {
2038     return TargetInfo::CharPtrBuiltinVaList;
2039   }
2040 
parseR600Name(StringRef Name)2041   static GPUKind parseR600Name(StringRef Name) {
2042     return llvm::StringSwitch<GPUKind>(Name)
2043       .Case("r600" ,    GK_R600)
2044       .Case("rv610",    GK_R600)
2045       .Case("rv620",    GK_R600)
2046       .Case("rv630",    GK_R600)
2047       .Case("rv635",    GK_R600)
2048       .Case("rs780",    GK_R600)
2049       .Case("rs880",    GK_R600)
2050       .Case("rv670",    GK_R600_DOUBLE_OPS)
2051       .Case("rv710",    GK_R700)
2052       .Case("rv730",    GK_R700)
2053       .Case("rv740",    GK_R700_DOUBLE_OPS)
2054       .Case("rv770",    GK_R700_DOUBLE_OPS)
2055       .Case("palm",     GK_EVERGREEN)
2056       .Case("cedar",    GK_EVERGREEN)
2057       .Case("sumo",     GK_EVERGREEN)
2058       .Case("sumo2",    GK_EVERGREEN)
2059       .Case("redwood",  GK_EVERGREEN)
2060       .Case("juniper",  GK_EVERGREEN)
2061       .Case("hemlock",  GK_EVERGREEN_DOUBLE_OPS)
2062       .Case("cypress",  GK_EVERGREEN_DOUBLE_OPS)
2063       .Case("barts",    GK_NORTHERN_ISLANDS)
2064       .Case("turks",    GK_NORTHERN_ISLANDS)
2065       .Case("caicos",   GK_NORTHERN_ISLANDS)
2066       .Case("cayman",   GK_CAYMAN)
2067       .Case("aruba",    GK_CAYMAN)
2068       .Default(GK_NONE);
2069   }
2070 
parseAMDGCNName(StringRef Name)2071   static GPUKind parseAMDGCNName(StringRef Name) {
2072     return llvm::StringSwitch<GPUKind>(Name)
2073       .Case("tahiti",   GK_SOUTHERN_ISLANDS)
2074       .Case("pitcairn", GK_SOUTHERN_ISLANDS)
2075       .Case("verde",    GK_SOUTHERN_ISLANDS)
2076       .Case("oland",    GK_SOUTHERN_ISLANDS)
2077       .Case("hainan",   GK_SOUTHERN_ISLANDS)
2078       .Case("bonaire",  GK_SEA_ISLANDS)
2079       .Case("kabini",   GK_SEA_ISLANDS)
2080       .Case("kaveri",   GK_SEA_ISLANDS)
2081       .Case("hawaii",   GK_SEA_ISLANDS)
2082       .Case("mullins",  GK_SEA_ISLANDS)
2083       .Case("tonga",    GK_VOLCANIC_ISLANDS)
2084       .Case("iceland",  GK_VOLCANIC_ISLANDS)
2085       .Case("carrizo",  GK_VOLCANIC_ISLANDS)
2086       .Case("fiji",     GK_VOLCANIC_ISLANDS)
2087       .Case("stoney",   GK_VOLCANIC_ISLANDS)
2088       .Default(GK_NONE);
2089   }
2090 
setCPU(const std::string & Name)2091   bool setCPU(const std::string &Name) override {
2092     if (getTriple().getArch() == llvm::Triple::amdgcn)
2093       GPU = parseAMDGCNName(Name);
2094     else
2095       GPU = parseR600Name(Name);
2096 
2097     return GPU != GK_NONE;
2098   }
2099 
setSupportedOpenCLOpts()2100   void setSupportedOpenCLOpts() override {
2101     auto &Opts = getSupportedOpenCLOpts();
2102     Opts.cl_clang_storage_class_specifiers = 1;
2103     Opts.cl_khr_icd = 1;
2104 
2105     if (hasFP64)
2106       Opts.cl_khr_fp64 = 1;
2107     if (GPU >= GK_EVERGREEN) {
2108       Opts.cl_khr_byte_addressable_store = 1;
2109       Opts.cl_khr_global_int32_base_atomics = 1;
2110       Opts.cl_khr_global_int32_extended_atomics = 1;
2111       Opts.cl_khr_local_int32_base_atomics = 1;
2112       Opts.cl_khr_local_int32_extended_atomics = 1;
2113     }
2114     if (GPU >= GK_SOUTHERN_ISLANDS) {
2115       Opts.cl_khr_fp16 = 1;
2116       Opts.cl_khr_int64_base_atomics = 1;
2117       Opts.cl_khr_int64_extended_atomics = 1;
2118       Opts.cl_khr_3d_image_writes = 1;
2119     }
2120   }
2121 
checkCallingConvention(CallingConv CC) const2122   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
2123     switch (CC) {
2124       default:
2125         return CCCR_Warning;
2126       case CC_C:
2127       case CC_OpenCLKernel:
2128         return CCCR_OK;
2129     }
2130   }
2131 };
2132 
2133 const Builtin::Info AMDGPUTargetInfo::BuiltinInfo[] = {
2134 #define BUILTIN(ID, TYPE, ATTRS)                \
2135   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
2136 #define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE)                               \
2137   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, FEATURE },
2138 #include "clang/Basic/BuiltinsAMDGPU.def"
2139 };
2140 const char * const AMDGPUTargetInfo::GCCRegNames[] = {
2141   "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
2142   "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
2143   "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
2144   "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
2145   "v32", "v33", "v34", "v35", "v36", "v37", "v38", "v39",
2146   "v40", "v41", "v42", "v43", "v44", "v45", "v46", "v47",
2147   "v48", "v49", "v50", "v51", "v52", "v53", "v54", "v55",
2148   "v56", "v57", "v58", "v59", "v60", "v61", "v62", "v63",
2149   "v64", "v65", "v66", "v67", "v68", "v69", "v70", "v71",
2150   "v72", "v73", "v74", "v75", "v76", "v77", "v78", "v79",
2151   "v80", "v81", "v82", "v83", "v84", "v85", "v86", "v87",
2152   "v88", "v89", "v90", "v91", "v92", "v93", "v94", "v95",
2153   "v96", "v97", "v98", "v99", "v100", "v101", "v102", "v103",
2154   "v104", "v105", "v106", "v107", "v108", "v109", "v110", "v111",
2155   "v112", "v113", "v114", "v115", "v116", "v117", "v118", "v119",
2156   "v120", "v121", "v122", "v123", "v124", "v125", "v126", "v127",
2157   "v128", "v129", "v130", "v131", "v132", "v133", "v134", "v135",
2158   "v136", "v137", "v138", "v139", "v140", "v141", "v142", "v143",
2159   "v144", "v145", "v146", "v147", "v148", "v149", "v150", "v151",
2160   "v152", "v153", "v154", "v155", "v156", "v157", "v158", "v159",
2161   "v160", "v161", "v162", "v163", "v164", "v165", "v166", "v167",
2162   "v168", "v169", "v170", "v171", "v172", "v173", "v174", "v175",
2163   "v176", "v177", "v178", "v179", "v180", "v181", "v182", "v183",
2164   "v184", "v185", "v186", "v187", "v188", "v189", "v190", "v191",
2165   "v192", "v193", "v194", "v195", "v196", "v197", "v198", "v199",
2166   "v200", "v201", "v202", "v203", "v204", "v205", "v206", "v207",
2167   "v208", "v209", "v210", "v211", "v212", "v213", "v214", "v215",
2168   "v216", "v217", "v218", "v219", "v220", "v221", "v222", "v223",
2169   "v224", "v225", "v226", "v227", "v228", "v229", "v230", "v231",
2170   "v232", "v233", "v234", "v235", "v236", "v237", "v238", "v239",
2171   "v240", "v241", "v242", "v243", "v244", "v245", "v246", "v247",
2172   "v248", "v249", "v250", "v251", "v252", "v253", "v254", "v255",
2173   "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
2174   "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
2175   "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
2176   "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
2177   "s32", "s33", "s34", "s35", "s36", "s37", "s38", "s39",
2178   "s40", "s41", "s42", "s43", "s44", "s45", "s46", "s47",
2179   "s48", "s49", "s50", "s51", "s52", "s53", "s54", "s55",
2180   "s56", "s57", "s58", "s59", "s60", "s61", "s62", "s63",
2181   "s64", "s65", "s66", "s67", "s68", "s69", "s70", "s71",
2182   "s72", "s73", "s74", "s75", "s76", "s77", "s78", "s79",
2183   "s80", "s81", "s82", "s83", "s84", "s85", "s86", "s87",
2184   "s88", "s89", "s90", "s91", "s92", "s93", "s94", "s95",
2185   "s96", "s97", "s98", "s99", "s100", "s101", "s102", "s103",
2186   "s104", "s105", "s106", "s107", "s108", "s109", "s110", "s111",
2187   "s112", "s113", "s114", "s115", "s116", "s117", "s118", "s119",
2188   "s120", "s121", "s122", "s123", "s124", "s125", "s126", "s127",
2189   "exec", "vcc", "scc", "m0", "flat_scratch", "exec_lo", "exec_hi",
2190   "vcc_lo", "vcc_hi", "flat_scratch_lo", "flat_scratch_hi"
2191 };
2192 
getGCCRegNames() const2193 ArrayRef<const char *> AMDGPUTargetInfo::getGCCRegNames() const {
2194   return llvm::makeArrayRef(GCCRegNames);
2195 }
2196 
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeatureVec) const2197 bool AMDGPUTargetInfo::initFeatureMap(
2198   llvm::StringMap<bool> &Features,
2199   DiagnosticsEngine &Diags, StringRef CPU,
2200   const std::vector<std::string> &FeatureVec) const {
2201 
2202   // XXX - What does the member GPU mean if device name string passed here?
2203   if (getTriple().getArch() == llvm::Triple::amdgcn) {
2204     if (CPU.empty())
2205       CPU = "tahiti";
2206 
2207     switch (parseAMDGCNName(CPU)) {
2208     case GK_SOUTHERN_ISLANDS:
2209     case GK_SEA_ISLANDS:
2210       break;
2211 
2212     case GK_VOLCANIC_ISLANDS:
2213       Features["s-memrealtime"] = true;
2214       Features["16-bit-insts"] = true;
2215       break;
2216 
2217     case GK_NONE:
2218       return false;
2219     default:
2220       llvm_unreachable("unhandled subtarget");
2221     }
2222   } else {
2223     if (CPU.empty())
2224       CPU = "r600";
2225 
2226     switch (parseR600Name(CPU)) {
2227     case GK_R600:
2228     case GK_R700:
2229     case GK_EVERGREEN:
2230     case GK_NORTHERN_ISLANDS:
2231       break;
2232     case GK_R600_DOUBLE_OPS:
2233     case GK_R700_DOUBLE_OPS:
2234     case GK_EVERGREEN_DOUBLE_OPS:
2235     case GK_CAYMAN:
2236       Features["fp64"] = true;
2237       break;
2238     case GK_NONE:
2239       return false;
2240     default:
2241       llvm_unreachable("unhandled subtarget");
2242     }
2243   }
2244 
2245   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeatureVec);
2246 }
2247 
2248 // Namespace for x86 abstract base class
2249 const Builtin::Info BuiltinInfo[] = {
2250 #define BUILTIN(ID, TYPE, ATTRS)                                               \
2251   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
2252 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER)                                    \
2253   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
2254 #define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE)                               \
2255   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, FEATURE },
2256 #include "clang/Basic/BuiltinsX86.def"
2257 };
2258 
2259 static const char* const GCCRegNames[] = {
2260   "ax", "dx", "cx", "bx", "si", "di", "bp", "sp",
2261   "st", "st(1)", "st(2)", "st(3)", "st(4)", "st(5)", "st(6)", "st(7)",
2262   "argp", "flags", "fpcr", "fpsr", "dirflag", "frame",
2263   "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
2264   "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
2265   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
2266   "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15",
2267   "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7",
2268   "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15",
2269   "xmm16", "xmm17", "xmm18", "xmm19", "xmm20", "xmm21", "xmm22", "xmm23",
2270   "xmm24", "xmm25", "xmm26", "xmm27", "xmm28", "xmm29", "xmm30", "xmm31",
2271   "ymm16", "ymm17", "ymm18", "ymm19", "ymm20", "ymm21", "ymm22", "ymm23",
2272   "ymm24", "ymm25", "ymm26", "ymm27", "ymm28", "ymm29", "ymm30", "ymm31",
2273   "zmm0", "zmm1", "zmm2", "zmm3", "zmm4", "zmm5", "zmm6", "zmm7",
2274   "zmm8", "zmm9", "zmm10", "zmm11", "zmm12", "zmm13", "zmm14", "zmm15",
2275   "zmm16", "zmm17", "zmm18", "zmm19", "zmm20", "zmm21", "zmm22", "zmm23",
2276   "zmm24", "zmm25", "zmm26", "zmm27", "zmm28", "zmm29", "zmm30", "zmm31",
2277 };
2278 
2279 const TargetInfo::AddlRegName AddlRegNames[] = {
2280   { { "al", "ah", "eax", "rax" }, 0 },
2281   { { "bl", "bh", "ebx", "rbx" }, 3 },
2282   { { "cl", "ch", "ecx", "rcx" }, 2 },
2283   { { "dl", "dh", "edx", "rdx" }, 1 },
2284   { { "esi", "rsi" }, 4 },
2285   { { "edi", "rdi" }, 5 },
2286   { { "esp", "rsp" }, 7 },
2287   { { "ebp", "rbp" }, 6 },
2288   { { "r8d", "r8w", "r8b" }, 38 },
2289   { { "r9d", "r9w", "r9b" }, 39 },
2290   { { "r10d", "r10w", "r10b" }, 40 },
2291   { { "r11d", "r11w", "r11b" }, 41 },
2292   { { "r12d", "r12w", "r12b" }, 42 },
2293   { { "r13d", "r13w", "r13b" }, 43 },
2294   { { "r14d", "r14w", "r14b" }, 44 },
2295   { { "r15d", "r15w", "r15b" }, 45 },
2296 };
2297 
2298 // X86 target abstract base class; x86-32 and x86-64 are very close, so
2299 // most of the implementation can be shared.
2300 class X86TargetInfo : public TargetInfo {
2301   enum X86SSEEnum {
2302     NoSSE, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42, AVX, AVX2, AVX512F
2303   } SSELevel = NoSSE;
2304   enum MMX3DNowEnum {
2305     NoMMX3DNow, MMX, AMD3DNow, AMD3DNowAthlon
2306   } MMX3DNowLevel = NoMMX3DNow;
2307   enum XOPEnum {
2308     NoXOP,
2309     SSE4A,
2310     FMA4,
2311     XOP
2312   } XOPLevel = NoXOP;
2313 
2314   bool HasAES = false;
2315   bool HasPCLMUL = false;
2316   bool HasLZCNT = false;
2317   bool HasRDRND = false;
2318   bool HasFSGSBASE = false;
2319   bool HasBMI = false;
2320   bool HasBMI2 = false;
2321   bool HasPOPCNT = false;
2322   bool HasRTM = false;
2323   bool HasPRFCHW = false;
2324   bool HasRDSEED = false;
2325   bool HasADX = false;
2326   bool HasTBM = false;
2327   bool HasFMA = false;
2328   bool HasF16C = false;
2329   bool HasAVX512CD = false;
2330   bool HasAVX512ER = false;
2331   bool HasAVX512PF = false;
2332   bool HasAVX512DQ = false;
2333   bool HasAVX512BW = false;
2334   bool HasAVX512VL = false;
2335   bool HasAVX512VBMI = false;
2336   bool HasAVX512IFMA = false;
2337   bool HasSHA = false;
2338   bool HasMPX = false;
2339   bool HasSGX = false;
2340   bool HasCX16 = false;
2341   bool HasFXSR = false;
2342   bool HasXSAVE = false;
2343   bool HasXSAVEOPT = false;
2344   bool HasXSAVEC = false;
2345   bool HasXSAVES = false;
2346   bool HasMWAITX = false;
2347   bool HasPKU = false;
2348   bool HasCLFLUSHOPT = false;
2349   bool HasPCOMMIT = false;
2350   bool HasCLWB = false;
2351   bool HasUMIP = false;
2352   bool HasMOVBE = false;
2353   bool HasPREFETCHWT1 = false;
2354 
2355   /// \brief Enumeration of all of the X86 CPUs supported by Clang.
2356   ///
2357   /// Each enumeration represents a particular CPU supported by Clang. These
2358   /// loosely correspond to the options passed to '-march' or '-mtune' flags.
2359   enum CPUKind {
2360     CK_Generic,
2361 
2362     /// \name i386
2363     /// i386-generation processors.
2364     //@{
2365     CK_i386,
2366     //@}
2367 
2368     /// \name i486
2369     /// i486-generation processors.
2370     //@{
2371     CK_i486,
2372     CK_WinChipC6,
2373     CK_WinChip2,
2374     CK_C3,
2375     //@}
2376 
2377     /// \name i586
2378     /// i586-generation processors, P5 microarchitecture based.
2379     //@{
2380     CK_i586,
2381     CK_Pentium,
2382     CK_PentiumMMX,
2383     //@}
2384 
2385     /// \name i686
2386     /// i686-generation processors, P6 / Pentium M microarchitecture based.
2387     //@{
2388     CK_i686,
2389     CK_PentiumPro,
2390     CK_Pentium2,
2391     CK_Pentium3,
2392     CK_Pentium3M,
2393     CK_PentiumM,
2394     CK_C3_2,
2395 
2396     /// This enumerator is a bit odd, as GCC no longer accepts -march=yonah.
2397     /// Clang however has some logic to suport this.
2398     // FIXME: Warn, deprecate, and potentially remove this.
2399     CK_Yonah,
2400     //@}
2401 
2402     /// \name Netburst
2403     /// Netburst microarchitecture based processors.
2404     //@{
2405     CK_Pentium4,
2406     CK_Pentium4M,
2407     CK_Prescott,
2408     CK_Nocona,
2409     //@}
2410 
2411     /// \name Core
2412     /// Core microarchitecture based processors.
2413     //@{
2414     CK_Core2,
2415 
2416     /// This enumerator, like \see CK_Yonah, is a bit odd. It is another
2417     /// codename which GCC no longer accepts as an option to -march, but Clang
2418     /// has some logic for recognizing it.
2419     // FIXME: Warn, deprecate, and potentially remove this.
2420     CK_Penryn,
2421     //@}
2422 
2423     /// \name Atom
2424     /// Atom processors
2425     //@{
2426     CK_Bonnell,
2427     CK_Silvermont,
2428     //@}
2429 
2430     /// \name Nehalem
2431     /// Nehalem microarchitecture based processors.
2432     CK_Nehalem,
2433 
2434     /// \name Westmere
2435     /// Westmere microarchitecture based processors.
2436     CK_Westmere,
2437 
2438     /// \name Sandy Bridge
2439     /// Sandy Bridge microarchitecture based processors.
2440     CK_SandyBridge,
2441 
2442     /// \name Ivy Bridge
2443     /// Ivy Bridge microarchitecture based processors.
2444     CK_IvyBridge,
2445 
2446     /// \name Haswell
2447     /// Haswell microarchitecture based processors.
2448     CK_Haswell,
2449 
2450     /// \name Broadwell
2451     /// Broadwell microarchitecture based processors.
2452     CK_Broadwell,
2453 
2454     /// \name Skylake Client
2455     /// Skylake client microarchitecture based processors.
2456     CK_SkylakeClient,
2457 
2458     /// \name Skylake Server
2459     /// Skylake server microarchitecture based processors.
2460     CK_SkylakeServer,
2461 
2462     /// \name Cannonlake Client
2463     /// Cannonlake client microarchitecture based processors.
2464     CK_Cannonlake,
2465 
2466     /// \name Knights Landing
2467     /// Knights Landing processor.
2468     CK_KNL,
2469 
2470     /// \name Lakemont
2471     /// Lakemont microarchitecture based processors.
2472     CK_Lakemont,
2473 
2474     /// \name K6
2475     /// K6 architecture processors.
2476     //@{
2477     CK_K6,
2478     CK_K6_2,
2479     CK_K6_3,
2480     //@}
2481 
2482     /// \name K7
2483     /// K7 architecture processors.
2484     //@{
2485     CK_Athlon,
2486     CK_AthlonThunderbird,
2487     CK_Athlon4,
2488     CK_AthlonXP,
2489     CK_AthlonMP,
2490     //@}
2491 
2492     /// \name K8
2493     /// K8 architecture processors.
2494     //@{
2495     CK_Athlon64,
2496     CK_Athlon64SSE3,
2497     CK_AthlonFX,
2498     CK_K8,
2499     CK_K8SSE3,
2500     CK_Opteron,
2501     CK_OpteronSSE3,
2502     CK_AMDFAM10,
2503     //@}
2504 
2505     /// \name Bobcat
2506     /// Bobcat architecture processors.
2507     //@{
2508     CK_BTVER1,
2509     CK_BTVER2,
2510     //@}
2511 
2512     /// \name Bulldozer
2513     /// Bulldozer architecture processors.
2514     //@{
2515     CK_BDVER1,
2516     CK_BDVER2,
2517     CK_BDVER3,
2518     CK_BDVER4,
2519     //@}
2520 
2521     /// This specification is deprecated and will be removed in the future.
2522     /// Users should prefer \see CK_K8.
2523     // FIXME: Warn on this when the CPU is set to it.
2524     //@{
2525     CK_x86_64,
2526     //@}
2527 
2528     /// \name Geode
2529     /// Geode processors.
2530     //@{
2531     CK_Geode
2532     //@}
2533   } CPU = CK_Generic;
2534 
getCPUKind(StringRef CPU) const2535   CPUKind getCPUKind(StringRef CPU) const {
2536     return llvm::StringSwitch<CPUKind>(CPU)
2537         .Case("i386", CK_i386)
2538         .Case("i486", CK_i486)
2539         .Case("winchip-c6", CK_WinChipC6)
2540         .Case("winchip2", CK_WinChip2)
2541         .Case("c3", CK_C3)
2542         .Case("i586", CK_i586)
2543         .Case("pentium", CK_Pentium)
2544         .Case("pentium-mmx", CK_PentiumMMX)
2545         .Case("i686", CK_i686)
2546         .Case("pentiumpro", CK_PentiumPro)
2547         .Case("pentium2", CK_Pentium2)
2548         .Case("pentium3", CK_Pentium3)
2549         .Case("pentium3m", CK_Pentium3M)
2550         .Case("pentium-m", CK_PentiumM)
2551         .Case("c3-2", CK_C3_2)
2552         .Case("yonah", CK_Yonah)
2553         .Case("pentium4", CK_Pentium4)
2554         .Case("pentium4m", CK_Pentium4M)
2555         .Case("prescott", CK_Prescott)
2556         .Case("nocona", CK_Nocona)
2557         .Case("core2", CK_Core2)
2558         .Case("penryn", CK_Penryn)
2559         .Case("bonnell", CK_Bonnell)
2560         .Case("atom", CK_Bonnell) // Legacy name.
2561         .Case("silvermont", CK_Silvermont)
2562         .Case("slm", CK_Silvermont) // Legacy name.
2563         .Case("nehalem", CK_Nehalem)
2564         .Case("corei7", CK_Nehalem) // Legacy name.
2565         .Case("westmere", CK_Westmere)
2566         .Case("sandybridge", CK_SandyBridge)
2567         .Case("corei7-avx", CK_SandyBridge) // Legacy name.
2568         .Case("ivybridge", CK_IvyBridge)
2569         .Case("core-avx-i", CK_IvyBridge) // Legacy name.
2570         .Case("haswell", CK_Haswell)
2571         .Case("core-avx2", CK_Haswell) // Legacy name.
2572         .Case("broadwell", CK_Broadwell)
2573         .Case("skylake", CK_SkylakeClient)
2574         .Case("skylake-avx512", CK_SkylakeServer)
2575         .Case("skx", CK_SkylakeServer) // Legacy name.
2576         .Case("cannonlake", CK_Cannonlake)
2577         .Case("knl", CK_KNL)
2578         .Case("lakemont", CK_Lakemont)
2579         .Case("k6", CK_K6)
2580         .Case("k6-2", CK_K6_2)
2581         .Case("k6-3", CK_K6_3)
2582         .Case("athlon", CK_Athlon)
2583         .Case("athlon-tbird", CK_AthlonThunderbird)
2584         .Case("athlon-4", CK_Athlon4)
2585         .Case("athlon-xp", CK_AthlonXP)
2586         .Case("athlon-mp", CK_AthlonMP)
2587         .Case("athlon64", CK_Athlon64)
2588         .Case("athlon64-sse3", CK_Athlon64SSE3)
2589         .Case("athlon-fx", CK_AthlonFX)
2590         .Case("k8", CK_K8)
2591         .Case("k8-sse3", CK_K8SSE3)
2592         .Case("opteron", CK_Opteron)
2593         .Case("opteron-sse3", CK_OpteronSSE3)
2594         .Case("barcelona", CK_AMDFAM10)
2595         .Case("amdfam10", CK_AMDFAM10)
2596         .Case("btver1", CK_BTVER1)
2597         .Case("btver2", CK_BTVER2)
2598         .Case("bdver1", CK_BDVER1)
2599         .Case("bdver2", CK_BDVER2)
2600         .Case("bdver3", CK_BDVER3)
2601         .Case("bdver4", CK_BDVER4)
2602         .Case("x86-64", CK_x86_64)
2603         .Case("geode", CK_Geode)
2604         .Default(CK_Generic);
2605   }
2606 
2607   enum FPMathKind {
2608     FP_Default,
2609     FP_SSE,
2610     FP_387
2611   } FPMath = FP_Default;
2612 
2613 public:
X86TargetInfo(const llvm::Triple & Triple,const TargetOptions &)2614   X86TargetInfo(const llvm::Triple &Triple, const TargetOptions &)
2615       : TargetInfo(Triple) {
2616     BigEndian = false;
2617     LongDoubleFormat = &llvm::APFloat::x87DoubleExtended;
2618   }
getFloatEvalMethod() const2619   unsigned getFloatEvalMethod() const override {
2620     // X87 evaluates with 80 bits "long double" precision.
2621     return SSELevel == NoSSE ? 2 : 0;
2622   }
getTargetBuiltins() const2623   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
2624     return llvm::makeArrayRef(BuiltinInfo,
2625                              clang::X86::LastTSBuiltin-Builtin::FirstTSBuiltin);
2626   }
getGCCRegNames() const2627   ArrayRef<const char *> getGCCRegNames() const override {
2628     return llvm::makeArrayRef(GCCRegNames);
2629   }
getGCCRegAliases() const2630   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
2631     return None;
2632   }
getGCCAddlRegNames() const2633   ArrayRef<TargetInfo::AddlRegName> getGCCAddlRegNames() const override {
2634     return llvm::makeArrayRef(AddlRegNames);
2635   }
2636   bool validateCpuSupports(StringRef Name) const override;
2637   bool validateAsmConstraint(const char *&Name,
2638                              TargetInfo::ConstraintInfo &info) const override;
2639 
validateGlobalRegisterVariable(StringRef RegName,unsigned RegSize,bool & HasSizeMismatch) const2640   bool validateGlobalRegisterVariable(StringRef RegName,
2641                                       unsigned RegSize,
2642                                       bool &HasSizeMismatch) const override {
2643     // esp and ebp are the only 32-bit registers the x86 backend can currently
2644     // handle.
2645     if (RegName.equals("esp") || RegName.equals("ebp")) {
2646       // Check that the register size is 32-bit.
2647       HasSizeMismatch = RegSize != 32;
2648       return true;
2649     }
2650 
2651     return false;
2652   }
2653 
2654   bool validateOutputSize(StringRef Constraint, unsigned Size) const override;
2655 
2656   bool validateInputSize(StringRef Constraint, unsigned Size) const override;
2657 
2658   virtual bool validateOperandSize(StringRef Constraint, unsigned Size) const;
2659 
2660   std::string convertConstraint(const char *&Constraint) const override;
getClobbers() const2661   const char *getClobbers() const override {
2662     return "~{dirflag},~{fpsr},~{flags}";
2663   }
2664   void getTargetDefines(const LangOptions &Opts,
2665                         MacroBuilder &Builder) const override;
2666   static void setSSELevel(llvm::StringMap<bool> &Features, X86SSEEnum Level,
2667                           bool Enabled);
2668   static void setMMXLevel(llvm::StringMap<bool> &Features, MMX3DNowEnum Level,
2669                           bool Enabled);
2670   static void setXOPLevel(llvm::StringMap<bool> &Features, XOPEnum Level,
2671                           bool Enabled);
setFeatureEnabled(llvm::StringMap<bool> & Features,StringRef Name,bool Enabled) const2672   void setFeatureEnabled(llvm::StringMap<bool> &Features,
2673                          StringRef Name, bool Enabled) const override {
2674     setFeatureEnabledImpl(Features, Name, Enabled);
2675   }
2676   // This exists purely to cut down on the number of virtual calls in
2677   // initFeatureMap which calls this repeatedly.
2678   static void setFeatureEnabledImpl(llvm::StringMap<bool> &Features,
2679                                     StringRef Name, bool Enabled);
2680   bool
2681   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
2682                  StringRef CPU,
2683                  const std::vector<std::string> &FeaturesVec) const override;
2684   bool hasFeature(StringRef Feature) const override;
2685   bool handleTargetFeatures(std::vector<std::string> &Features,
2686                             DiagnosticsEngine &Diags) override;
getABI() const2687   StringRef getABI() const override {
2688     if (getTriple().getArch() == llvm::Triple::x86_64 && SSELevel >= AVX512F)
2689       return "avx512";
2690     if (getTriple().getArch() == llvm::Triple::x86_64 && SSELevel >= AVX)
2691       return "avx";
2692     if (getTriple().getArch() == llvm::Triple::x86 &&
2693              MMX3DNowLevel == NoMMX3DNow)
2694       return "no-mmx";
2695     return "";
2696   }
setCPU(const std::string & Name)2697   bool setCPU(const std::string &Name) override {
2698     CPU = getCPUKind(Name);
2699 
2700     // Perform any per-CPU checks necessary to determine if this CPU is
2701     // acceptable.
2702     // FIXME: This results in terrible diagnostics. Clang just says the CPU is
2703     // invalid without explaining *why*.
2704     switch (CPU) {
2705     case CK_Generic:
2706       // No processor selected!
2707       return false;
2708 
2709     case CK_i386:
2710     case CK_i486:
2711     case CK_WinChipC6:
2712     case CK_WinChip2:
2713     case CK_C3:
2714     case CK_i586:
2715     case CK_Pentium:
2716     case CK_PentiumMMX:
2717     case CK_i686:
2718     case CK_PentiumPro:
2719     case CK_Pentium2:
2720     case CK_Pentium3:
2721     case CK_Pentium3M:
2722     case CK_PentiumM:
2723     case CK_Yonah:
2724     case CK_C3_2:
2725     case CK_Pentium4:
2726     case CK_Pentium4M:
2727     case CK_Lakemont:
2728     case CK_Prescott:
2729     case CK_K6:
2730     case CK_K6_2:
2731     case CK_K6_3:
2732     case CK_Athlon:
2733     case CK_AthlonThunderbird:
2734     case CK_Athlon4:
2735     case CK_AthlonXP:
2736     case CK_AthlonMP:
2737     case CK_Geode:
2738       // Only accept certain architectures when compiling in 32-bit mode.
2739       if (getTriple().getArch() != llvm::Triple::x86)
2740         return false;
2741 
2742       // Fallthrough
2743     case CK_Nocona:
2744     case CK_Core2:
2745     case CK_Penryn:
2746     case CK_Bonnell:
2747     case CK_Silvermont:
2748     case CK_Nehalem:
2749     case CK_Westmere:
2750     case CK_SandyBridge:
2751     case CK_IvyBridge:
2752     case CK_Haswell:
2753     case CK_Broadwell:
2754     case CK_SkylakeClient:
2755     case CK_SkylakeServer:
2756     case CK_Cannonlake:
2757     case CK_KNL:
2758     case CK_Athlon64:
2759     case CK_Athlon64SSE3:
2760     case CK_AthlonFX:
2761     case CK_K8:
2762     case CK_K8SSE3:
2763     case CK_Opteron:
2764     case CK_OpteronSSE3:
2765     case CK_AMDFAM10:
2766     case CK_BTVER1:
2767     case CK_BTVER2:
2768     case CK_BDVER1:
2769     case CK_BDVER2:
2770     case CK_BDVER3:
2771     case CK_BDVER4:
2772     case CK_x86_64:
2773       return true;
2774     }
2775     llvm_unreachable("Unhandled CPU kind");
2776   }
2777 
2778   bool setFPMath(StringRef Name) override;
2779 
checkCallingConvention(CallingConv CC) const2780   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
2781     // Most of the non-ARM calling conventions are i386 conventions.
2782     switch (CC) {
2783     case CC_X86ThisCall:
2784     case CC_X86FastCall:
2785     case CC_X86StdCall:
2786     case CC_X86VectorCall:
2787     case CC_C:
2788     case CC_Swift:
2789     case CC_X86Pascal:
2790     case CC_IntelOclBicc:
2791       return CCCR_OK;
2792     default:
2793       return CCCR_Warning;
2794     }
2795   }
2796 
getDefaultCallingConv(CallingConvMethodType MT) const2797   CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override {
2798     return MT == CCMT_Member ? CC_X86ThisCall : CC_C;
2799   }
2800 
hasSjLjLowering() const2801   bool hasSjLjLowering() const override {
2802     return true;
2803   }
2804 
setSupportedOpenCLOpts()2805   void setSupportedOpenCLOpts() override {
2806     getSupportedOpenCLOpts().setAll();
2807   }
2808 };
2809 
setFPMath(StringRef Name)2810 bool X86TargetInfo::setFPMath(StringRef Name) {
2811   if (Name == "387") {
2812     FPMath = FP_387;
2813     return true;
2814   }
2815   if (Name == "sse") {
2816     FPMath = FP_SSE;
2817     return true;
2818   }
2819   return false;
2820 }
2821 
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const2822 bool X86TargetInfo::initFeatureMap(
2823     llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
2824     const std::vector<std::string> &FeaturesVec) const {
2825   // FIXME: This *really* should not be here.
2826   // X86_64 always has SSE2.
2827   if (getTriple().getArch() == llvm::Triple::x86_64)
2828     setFeatureEnabledImpl(Features, "sse2", true);
2829 
2830   const CPUKind Kind = getCPUKind(CPU);
2831 
2832   // Enable X87 for all X86 processors but Lakemont.
2833   if (Kind != CK_Lakemont)
2834     setFeatureEnabledImpl(Features, "x87", true);
2835 
2836   switch (Kind) {
2837   case CK_Generic:
2838   case CK_i386:
2839   case CK_i486:
2840   case CK_i586:
2841   case CK_Pentium:
2842   case CK_i686:
2843   case CK_PentiumPro:
2844   case CK_Lakemont:
2845     break;
2846   case CK_PentiumMMX:
2847   case CK_Pentium2:
2848   case CK_K6:
2849   case CK_WinChipC6:
2850     setFeatureEnabledImpl(Features, "mmx", true);
2851     break;
2852   case CK_Pentium3:
2853   case CK_Pentium3M:
2854   case CK_C3_2:
2855     setFeatureEnabledImpl(Features, "sse", true);
2856     setFeatureEnabledImpl(Features, "fxsr", true);
2857     break;
2858   case CK_PentiumM:
2859   case CK_Pentium4:
2860   case CK_Pentium4M:
2861   case CK_x86_64:
2862     setFeatureEnabledImpl(Features, "sse2", true);
2863     setFeatureEnabledImpl(Features, "fxsr", true);
2864     break;
2865   case CK_Yonah:
2866   case CK_Prescott:
2867   case CK_Nocona:
2868     setFeatureEnabledImpl(Features, "sse3", true);
2869     setFeatureEnabledImpl(Features, "fxsr", true);
2870     setFeatureEnabledImpl(Features, "cx16", true);
2871     break;
2872   case CK_Core2:
2873   case CK_Bonnell:
2874     setFeatureEnabledImpl(Features, "ssse3", true);
2875     setFeatureEnabledImpl(Features, "fxsr", true);
2876     setFeatureEnabledImpl(Features, "cx16", true);
2877     break;
2878   case CK_Penryn:
2879     setFeatureEnabledImpl(Features, "sse4.1", true);
2880     setFeatureEnabledImpl(Features, "fxsr", true);
2881     setFeatureEnabledImpl(Features, "cx16", true);
2882     break;
2883   case CK_Cannonlake:
2884     setFeatureEnabledImpl(Features, "avx512ifma", true);
2885     setFeatureEnabledImpl(Features, "avx512vbmi", true);
2886     setFeatureEnabledImpl(Features, "sha", true);
2887     setFeatureEnabledImpl(Features, "umip", true);
2888     // FALLTHROUGH
2889   case CK_SkylakeServer:
2890     setFeatureEnabledImpl(Features, "avx512f", true);
2891     setFeatureEnabledImpl(Features, "avx512cd", true);
2892     setFeatureEnabledImpl(Features, "avx512dq", true);
2893     setFeatureEnabledImpl(Features, "avx512bw", true);
2894     setFeatureEnabledImpl(Features, "avx512vl", true);
2895     setFeatureEnabledImpl(Features, "pku", true);
2896     setFeatureEnabledImpl(Features, "pcommit", true);
2897     setFeatureEnabledImpl(Features, "clwb", true);
2898     // FALLTHROUGH
2899   case CK_SkylakeClient:
2900     setFeatureEnabledImpl(Features, "xsavec", true);
2901     setFeatureEnabledImpl(Features, "xsaves", true);
2902     setFeatureEnabledImpl(Features, "mpx", true);
2903     setFeatureEnabledImpl(Features, "sgx", true);
2904     setFeatureEnabledImpl(Features, "clflushopt", true);
2905     // FALLTHROUGH
2906   case CK_Broadwell:
2907     setFeatureEnabledImpl(Features, "rdseed", true);
2908     setFeatureEnabledImpl(Features, "adx", true);
2909     // FALLTHROUGH
2910   case CK_Haswell:
2911     setFeatureEnabledImpl(Features, "avx2", true);
2912     setFeatureEnabledImpl(Features, "lzcnt", true);
2913     setFeatureEnabledImpl(Features, "bmi", true);
2914     setFeatureEnabledImpl(Features, "bmi2", true);
2915     setFeatureEnabledImpl(Features, "rtm", true);
2916     setFeatureEnabledImpl(Features, "fma", true);
2917     setFeatureEnabledImpl(Features, "movbe", true);
2918     // FALLTHROUGH
2919   case CK_IvyBridge:
2920     setFeatureEnabledImpl(Features, "rdrnd", true);
2921     setFeatureEnabledImpl(Features, "f16c", true);
2922     setFeatureEnabledImpl(Features, "fsgsbase", true);
2923     // FALLTHROUGH
2924   case CK_SandyBridge:
2925     setFeatureEnabledImpl(Features, "avx", true);
2926     setFeatureEnabledImpl(Features, "xsave", true);
2927     setFeatureEnabledImpl(Features, "xsaveopt", true);
2928     // FALLTHROUGH
2929   case CK_Westmere:
2930   case CK_Silvermont:
2931     setFeatureEnabledImpl(Features, "aes", true);
2932     setFeatureEnabledImpl(Features, "pclmul", true);
2933     // FALLTHROUGH
2934   case CK_Nehalem:
2935     setFeatureEnabledImpl(Features, "sse4.2", true);
2936     setFeatureEnabledImpl(Features, "fxsr", true);
2937     setFeatureEnabledImpl(Features, "cx16", true);
2938     break;
2939   case CK_KNL:
2940     setFeatureEnabledImpl(Features, "avx512f", true);
2941     setFeatureEnabledImpl(Features, "avx512cd", true);
2942     setFeatureEnabledImpl(Features, "avx512er", true);
2943     setFeatureEnabledImpl(Features, "avx512pf", true);
2944     setFeatureEnabledImpl(Features, "prefetchwt1", true);
2945     setFeatureEnabledImpl(Features, "fxsr", true);
2946     setFeatureEnabledImpl(Features, "rdseed", true);
2947     setFeatureEnabledImpl(Features, "adx", true);
2948     setFeatureEnabledImpl(Features, "lzcnt", true);
2949     setFeatureEnabledImpl(Features, "bmi", true);
2950     setFeatureEnabledImpl(Features, "bmi2", true);
2951     setFeatureEnabledImpl(Features, "rtm", true);
2952     setFeatureEnabledImpl(Features, "fma", true);
2953     setFeatureEnabledImpl(Features, "rdrnd", true);
2954     setFeatureEnabledImpl(Features, "f16c", true);
2955     setFeatureEnabledImpl(Features, "fsgsbase", true);
2956     setFeatureEnabledImpl(Features, "aes", true);
2957     setFeatureEnabledImpl(Features, "pclmul", true);
2958     setFeatureEnabledImpl(Features, "cx16", true);
2959     setFeatureEnabledImpl(Features, "xsaveopt", true);
2960     setFeatureEnabledImpl(Features, "xsave", true);
2961     setFeatureEnabledImpl(Features, "movbe", true);
2962     break;
2963   case CK_K6_2:
2964   case CK_K6_3:
2965   case CK_WinChip2:
2966   case CK_C3:
2967     setFeatureEnabledImpl(Features, "3dnow", true);
2968     break;
2969   case CK_Athlon:
2970   case CK_AthlonThunderbird:
2971   case CK_Geode:
2972     setFeatureEnabledImpl(Features, "3dnowa", true);
2973     break;
2974   case CK_Athlon4:
2975   case CK_AthlonXP:
2976   case CK_AthlonMP:
2977     setFeatureEnabledImpl(Features, "sse", true);
2978     setFeatureEnabledImpl(Features, "3dnowa", true);
2979     setFeatureEnabledImpl(Features, "fxsr", true);
2980     break;
2981   case CK_K8:
2982   case CK_Opteron:
2983   case CK_Athlon64:
2984   case CK_AthlonFX:
2985     setFeatureEnabledImpl(Features, "sse2", true);
2986     setFeatureEnabledImpl(Features, "3dnowa", true);
2987     setFeatureEnabledImpl(Features, "fxsr", true);
2988     break;
2989   case CK_AMDFAM10:
2990     setFeatureEnabledImpl(Features, "sse4a", true);
2991     setFeatureEnabledImpl(Features, "lzcnt", true);
2992     setFeatureEnabledImpl(Features, "popcnt", true);
2993     // FALLTHROUGH
2994   case CK_K8SSE3:
2995   case CK_OpteronSSE3:
2996   case CK_Athlon64SSE3:
2997     setFeatureEnabledImpl(Features, "sse3", true);
2998     setFeatureEnabledImpl(Features, "3dnowa", true);
2999     setFeatureEnabledImpl(Features, "fxsr", true);
3000     break;
3001   case CK_BTVER2:
3002     setFeatureEnabledImpl(Features, "avx", true);
3003     setFeatureEnabledImpl(Features, "aes", true);
3004     setFeatureEnabledImpl(Features, "pclmul", true);
3005     setFeatureEnabledImpl(Features, "bmi", true);
3006     setFeatureEnabledImpl(Features, "f16c", true);
3007     setFeatureEnabledImpl(Features, "xsaveopt", true);
3008     // FALLTHROUGH
3009   case CK_BTVER1:
3010     setFeatureEnabledImpl(Features, "ssse3", true);
3011     setFeatureEnabledImpl(Features, "sse4a", true);
3012     setFeatureEnabledImpl(Features, "lzcnt", true);
3013     setFeatureEnabledImpl(Features, "popcnt", true);
3014     setFeatureEnabledImpl(Features, "prfchw", true);
3015     setFeatureEnabledImpl(Features, "cx16", true);
3016     setFeatureEnabledImpl(Features, "fxsr", true);
3017     break;
3018   case CK_BDVER4:
3019     setFeatureEnabledImpl(Features, "avx2", true);
3020     setFeatureEnabledImpl(Features, "bmi2", true);
3021     setFeatureEnabledImpl(Features, "mwaitx", true);
3022     // FALLTHROUGH
3023   case CK_BDVER3:
3024     setFeatureEnabledImpl(Features, "fsgsbase", true);
3025     setFeatureEnabledImpl(Features, "xsaveopt", true);
3026     // FALLTHROUGH
3027   case CK_BDVER2:
3028     setFeatureEnabledImpl(Features, "bmi", true);
3029     setFeatureEnabledImpl(Features, "fma", true);
3030     setFeatureEnabledImpl(Features, "f16c", true);
3031     setFeatureEnabledImpl(Features, "tbm", true);
3032     // FALLTHROUGH
3033   case CK_BDVER1:
3034     // xop implies avx, sse4a and fma4.
3035     setFeatureEnabledImpl(Features, "xop", true);
3036     setFeatureEnabledImpl(Features, "lzcnt", true);
3037     setFeatureEnabledImpl(Features, "aes", true);
3038     setFeatureEnabledImpl(Features, "pclmul", true);
3039     setFeatureEnabledImpl(Features, "prfchw", true);
3040     setFeatureEnabledImpl(Features, "cx16", true);
3041     setFeatureEnabledImpl(Features, "fxsr", true);
3042     setFeatureEnabledImpl(Features, "xsave", true);
3043     break;
3044   }
3045   if (!TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec))
3046     return false;
3047 
3048   // Can't do this earlier because we need to be able to explicitly enable
3049   // or disable these features and the things that they depend upon.
3050 
3051   // Enable popcnt if sse4.2 is enabled and popcnt is not explicitly disabled.
3052   auto I = Features.find("sse4.2");
3053   if (I != Features.end() && I->getValue() &&
3054       std::find(FeaturesVec.begin(), FeaturesVec.end(), "-popcnt") ==
3055           FeaturesVec.end())
3056     Features["popcnt"] = true;
3057 
3058   // Enable prfchw if 3DNow! is enabled and prfchw is not explicitly disabled.
3059   I = Features.find("3dnow");
3060   if (I != Features.end() && I->getValue() &&
3061       std::find(FeaturesVec.begin(), FeaturesVec.end(), "-prfchw") ==
3062           FeaturesVec.end())
3063     Features["prfchw"] = true;
3064 
3065   // Additionally, if SSE is enabled and mmx is not explicitly disabled,
3066   // then enable MMX.
3067   I = Features.find("sse");
3068   if (I != Features.end() && I->getValue() &&
3069       std::find(FeaturesVec.begin(), FeaturesVec.end(), "-mmx") ==
3070           FeaturesVec.end())
3071     Features["mmx"] = true;
3072 
3073   return true;
3074 }
3075 
setSSELevel(llvm::StringMap<bool> & Features,X86SSEEnum Level,bool Enabled)3076 void X86TargetInfo::setSSELevel(llvm::StringMap<bool> &Features,
3077                                 X86SSEEnum Level, bool Enabled) {
3078   if (Enabled) {
3079     switch (Level) {
3080     case AVX512F:
3081       Features["avx512f"] = true;
3082     case AVX2:
3083       Features["avx2"] = true;
3084     case AVX:
3085       Features["avx"] = true;
3086       Features["xsave"] = true;
3087     case SSE42:
3088       Features["sse4.2"] = true;
3089     case SSE41:
3090       Features["sse4.1"] = true;
3091     case SSSE3:
3092       Features["ssse3"] = true;
3093     case SSE3:
3094       Features["sse3"] = true;
3095     case SSE2:
3096       Features["sse2"] = true;
3097     case SSE1:
3098       Features["sse"] = true;
3099     case NoSSE:
3100       break;
3101     }
3102     return;
3103   }
3104 
3105   switch (Level) {
3106   case NoSSE:
3107   case SSE1:
3108     Features["sse"] = false;
3109   case SSE2:
3110     Features["sse2"] = Features["pclmul"] = Features["aes"] =
3111       Features["sha"] = false;
3112   case SSE3:
3113     Features["sse3"] = false;
3114     setXOPLevel(Features, NoXOP, false);
3115   case SSSE3:
3116     Features["ssse3"] = false;
3117   case SSE41:
3118     Features["sse4.1"] = false;
3119   case SSE42:
3120     Features["sse4.2"] = false;
3121   case AVX:
3122     Features["fma"] = Features["avx"] = Features["f16c"] = Features["xsave"] =
3123       Features["xsaveopt"] = false;
3124     setXOPLevel(Features, FMA4, false);
3125   case AVX2:
3126     Features["avx2"] = false;
3127   case AVX512F:
3128     Features["avx512f"] = Features["avx512cd"] = Features["avx512er"] =
3129       Features["avx512pf"] = Features["avx512dq"] = Features["avx512bw"] =
3130       Features["avx512vl"] = Features["avx512vbmi"] =
3131       Features["avx512ifma"] = false;
3132   }
3133 }
3134 
setMMXLevel(llvm::StringMap<bool> & Features,MMX3DNowEnum Level,bool Enabled)3135 void X86TargetInfo::setMMXLevel(llvm::StringMap<bool> &Features,
3136                                 MMX3DNowEnum Level, bool Enabled) {
3137   if (Enabled) {
3138     switch (Level) {
3139     case AMD3DNowAthlon:
3140       Features["3dnowa"] = true;
3141     case AMD3DNow:
3142       Features["3dnow"] = true;
3143     case MMX:
3144       Features["mmx"] = true;
3145     case NoMMX3DNow:
3146       break;
3147     }
3148     return;
3149   }
3150 
3151   switch (Level) {
3152   case NoMMX3DNow:
3153   case MMX:
3154     Features["mmx"] = false;
3155   case AMD3DNow:
3156     Features["3dnow"] = false;
3157   case AMD3DNowAthlon:
3158     Features["3dnowa"] = false;
3159   }
3160 }
3161 
setXOPLevel(llvm::StringMap<bool> & Features,XOPEnum Level,bool Enabled)3162 void X86TargetInfo::setXOPLevel(llvm::StringMap<bool> &Features, XOPEnum Level,
3163                                 bool Enabled) {
3164   if (Enabled) {
3165     switch (Level) {
3166     case XOP:
3167       Features["xop"] = true;
3168     case FMA4:
3169       Features["fma4"] = true;
3170       setSSELevel(Features, AVX, true);
3171     case SSE4A:
3172       Features["sse4a"] = true;
3173       setSSELevel(Features, SSE3, true);
3174     case NoXOP:
3175       break;
3176     }
3177     return;
3178   }
3179 
3180   switch (Level) {
3181   case NoXOP:
3182   case SSE4A:
3183     Features["sse4a"] = false;
3184   case FMA4:
3185     Features["fma4"] = false;
3186   case XOP:
3187     Features["xop"] = false;
3188   }
3189 }
3190 
setFeatureEnabledImpl(llvm::StringMap<bool> & Features,StringRef Name,bool Enabled)3191 void X86TargetInfo::setFeatureEnabledImpl(llvm::StringMap<bool> &Features,
3192                                           StringRef Name, bool Enabled) {
3193   // This is a bit of a hack to deal with the sse4 target feature when used
3194   // as part of the target attribute. We handle sse4 correctly everywhere
3195   // else. See below for more information on how we handle the sse4 options.
3196   if (Name != "sse4")
3197     Features[Name] = Enabled;
3198 
3199   if (Name == "mmx") {
3200     setMMXLevel(Features, MMX, Enabled);
3201   } else if (Name == "sse") {
3202     setSSELevel(Features, SSE1, Enabled);
3203   } else if (Name == "sse2") {
3204     setSSELevel(Features, SSE2, Enabled);
3205   } else if (Name == "sse3") {
3206     setSSELevel(Features, SSE3, Enabled);
3207   } else if (Name == "ssse3") {
3208     setSSELevel(Features, SSSE3, Enabled);
3209   } else if (Name == "sse4.2") {
3210     setSSELevel(Features, SSE42, Enabled);
3211   } else if (Name == "sse4.1") {
3212     setSSELevel(Features, SSE41, Enabled);
3213   } else if (Name == "3dnow") {
3214     setMMXLevel(Features, AMD3DNow, Enabled);
3215   } else if (Name == "3dnowa") {
3216     setMMXLevel(Features, AMD3DNowAthlon, Enabled);
3217   } else if (Name == "aes") {
3218     if (Enabled)
3219       setSSELevel(Features, SSE2, Enabled);
3220   } else if (Name == "pclmul") {
3221     if (Enabled)
3222       setSSELevel(Features, SSE2, Enabled);
3223   } else if (Name == "avx") {
3224     setSSELevel(Features, AVX, Enabled);
3225   } else if (Name == "avx2") {
3226     setSSELevel(Features, AVX2, Enabled);
3227   } else if (Name == "avx512f") {
3228     setSSELevel(Features, AVX512F, Enabled);
3229   } else if (Name == "avx512cd" || Name == "avx512er" || Name == "avx512pf" ||
3230              Name == "avx512dq" || Name == "avx512bw" || Name == "avx512vl" ||
3231              Name == "avx512vbmi" || Name == "avx512ifma") {
3232     if (Enabled)
3233       setSSELevel(Features, AVX512F, Enabled);
3234   } else if (Name == "fma") {
3235     if (Enabled)
3236       setSSELevel(Features, AVX, Enabled);
3237   } else if (Name == "fma4") {
3238     setXOPLevel(Features, FMA4, Enabled);
3239   } else if (Name == "xop") {
3240     setXOPLevel(Features, XOP, Enabled);
3241   } else if (Name == "sse4a") {
3242     setXOPLevel(Features, SSE4A, Enabled);
3243   } else if (Name == "f16c") {
3244     if (Enabled)
3245       setSSELevel(Features, AVX, Enabled);
3246   } else if (Name == "sha") {
3247     if (Enabled)
3248       setSSELevel(Features, SSE2, Enabled);
3249   } else if (Name == "sse4") {
3250     // We can get here via the __target__ attribute since that's not controlled
3251     // via the -msse4/-mno-sse4 command line alias. Handle this the same way
3252     // here - turn on the sse4.2 if enabled, turn off the sse4.1 level if
3253     // disabled.
3254     if (Enabled)
3255       setSSELevel(Features, SSE42, Enabled);
3256     else
3257       setSSELevel(Features, SSE41, Enabled);
3258   } else if (Name == "xsave") {
3259     if (!Enabled)
3260       Features["xsaveopt"] = false;
3261   } else if (Name == "xsaveopt" || Name == "xsavec" || Name == "xsaves") {
3262     if (Enabled)
3263       Features["xsave"] = true;
3264   }
3265 }
3266 
3267 /// handleTargetFeatures - Perform initialization based on the user
3268 /// configured set of features.
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)3269 bool X86TargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
3270                                          DiagnosticsEngine &Diags) {
3271   for (const auto &Feature : Features) {
3272     if (Feature[0] != '+')
3273       continue;
3274 
3275     if (Feature == "+aes") {
3276       HasAES = true;
3277     } else if (Feature == "+pclmul") {
3278       HasPCLMUL = true;
3279     } else if (Feature == "+lzcnt") {
3280       HasLZCNT = true;
3281     } else if (Feature == "+rdrnd") {
3282       HasRDRND = true;
3283     } else if (Feature == "+fsgsbase") {
3284       HasFSGSBASE = true;
3285     } else if (Feature == "+bmi") {
3286       HasBMI = true;
3287     } else if (Feature == "+bmi2") {
3288       HasBMI2 = true;
3289     } else if (Feature == "+popcnt") {
3290       HasPOPCNT = true;
3291     } else if (Feature == "+rtm") {
3292       HasRTM = true;
3293     } else if (Feature == "+prfchw") {
3294       HasPRFCHW = true;
3295     } else if (Feature == "+rdseed") {
3296       HasRDSEED = true;
3297     } else if (Feature == "+adx") {
3298       HasADX = true;
3299     } else if (Feature == "+tbm") {
3300       HasTBM = true;
3301     } else if (Feature == "+fma") {
3302       HasFMA = true;
3303     } else if (Feature == "+f16c") {
3304       HasF16C = true;
3305     } else if (Feature == "+avx512cd") {
3306       HasAVX512CD = true;
3307     } else if (Feature == "+avx512er") {
3308       HasAVX512ER = true;
3309     } else if (Feature == "+avx512pf") {
3310       HasAVX512PF = true;
3311     } else if (Feature == "+avx512dq") {
3312       HasAVX512DQ = true;
3313     } else if (Feature == "+avx512bw") {
3314       HasAVX512BW = true;
3315     } else if (Feature == "+avx512vl") {
3316       HasAVX512VL = true;
3317     } else if (Feature == "+avx512vbmi") {
3318       HasAVX512VBMI = true;
3319     } else if (Feature == "+avx512ifma") {
3320       HasAVX512IFMA = true;
3321     } else if (Feature == "+sha") {
3322       HasSHA = true;
3323     } else if (Feature == "+mpx") {
3324       HasMPX = true;
3325     } else if (Feature == "+movbe") {
3326       HasMOVBE = true;
3327     } else if (Feature == "+sgx") {
3328       HasSGX = true;
3329     } else if (Feature == "+cx16") {
3330       HasCX16 = true;
3331     } else if (Feature == "+fxsr") {
3332       HasFXSR = true;
3333     } else if (Feature == "+xsave") {
3334       HasXSAVE = true;
3335     } else if (Feature == "+xsaveopt") {
3336       HasXSAVEOPT = true;
3337     } else if (Feature == "+xsavec") {
3338       HasXSAVEC = true;
3339     } else if (Feature == "+xsaves") {
3340       HasXSAVES = true;
3341     } else if (Feature == "+mwaitx") {
3342       HasMWAITX = true;
3343     } else if (Feature == "+pku") {
3344       HasPKU = true;
3345     } else if (Feature == "+clflushopt") {
3346       HasCLFLUSHOPT = true;
3347     } else if (Feature == "+pcommit") {
3348       HasPCOMMIT = true;
3349     } else if (Feature == "+clwb") {
3350       HasCLWB = true;
3351     } else if (Feature == "+umip") {
3352       HasUMIP = true;
3353     } else if (Feature == "+prefetchwt1") {
3354       HasPREFETCHWT1 = true;
3355     }
3356 
3357     X86SSEEnum Level = llvm::StringSwitch<X86SSEEnum>(Feature)
3358       .Case("+avx512f", AVX512F)
3359       .Case("+avx2", AVX2)
3360       .Case("+avx", AVX)
3361       .Case("+sse4.2", SSE42)
3362       .Case("+sse4.1", SSE41)
3363       .Case("+ssse3", SSSE3)
3364       .Case("+sse3", SSE3)
3365       .Case("+sse2", SSE2)
3366       .Case("+sse", SSE1)
3367       .Default(NoSSE);
3368     SSELevel = std::max(SSELevel, Level);
3369 
3370     MMX3DNowEnum ThreeDNowLevel =
3371       llvm::StringSwitch<MMX3DNowEnum>(Feature)
3372         .Case("+3dnowa", AMD3DNowAthlon)
3373         .Case("+3dnow", AMD3DNow)
3374         .Case("+mmx", MMX)
3375         .Default(NoMMX3DNow);
3376     MMX3DNowLevel = std::max(MMX3DNowLevel, ThreeDNowLevel);
3377 
3378     XOPEnum XLevel = llvm::StringSwitch<XOPEnum>(Feature)
3379         .Case("+xop", XOP)
3380         .Case("+fma4", FMA4)
3381         .Case("+sse4a", SSE4A)
3382         .Default(NoXOP);
3383     XOPLevel = std::max(XOPLevel, XLevel);
3384   }
3385 
3386   // LLVM doesn't have a separate switch for fpmath, so only accept it if it
3387   // matches the selected sse level.
3388   if ((FPMath == FP_SSE && SSELevel < SSE1) ||
3389       (FPMath == FP_387 && SSELevel >= SSE1)) {
3390     Diags.Report(diag::err_target_unsupported_fpmath) <<
3391       (FPMath == FP_SSE ? "sse" : "387");
3392     return false;
3393   }
3394 
3395   SimdDefaultAlign =
3396       hasFeature("avx512f") ? 512 : hasFeature("avx") ? 256 : 128;
3397   return true;
3398 }
3399 
3400 /// X86TargetInfo::getTargetDefines - Return the set of the X86-specific macro
3401 /// definitions for this particular subtarget.
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3402 void X86TargetInfo::getTargetDefines(const LangOptions &Opts,
3403                                      MacroBuilder &Builder) const {
3404   // Target identification.
3405   if (getTriple().getArch() == llvm::Triple::x86_64) {
3406     Builder.defineMacro("__amd64__");
3407     Builder.defineMacro("__amd64");
3408     Builder.defineMacro("__x86_64");
3409     Builder.defineMacro("__x86_64__");
3410     if (getTriple().getArchName() == "x86_64h") {
3411       Builder.defineMacro("__x86_64h");
3412       Builder.defineMacro("__x86_64h__");
3413     }
3414   } else {
3415     DefineStd(Builder, "i386", Opts);
3416   }
3417 
3418   // Subtarget options.
3419   // FIXME: We are hard-coding the tune parameters based on the CPU, but they
3420   // truly should be based on -mtune options.
3421   switch (CPU) {
3422   case CK_Generic:
3423     break;
3424   case CK_i386:
3425     // The rest are coming from the i386 define above.
3426     Builder.defineMacro("__tune_i386__");
3427     break;
3428   case CK_i486:
3429   case CK_WinChipC6:
3430   case CK_WinChip2:
3431   case CK_C3:
3432     defineCPUMacros(Builder, "i486");
3433     break;
3434   case CK_PentiumMMX:
3435     Builder.defineMacro("__pentium_mmx__");
3436     Builder.defineMacro("__tune_pentium_mmx__");
3437     // Fallthrough
3438   case CK_i586:
3439   case CK_Pentium:
3440     defineCPUMacros(Builder, "i586");
3441     defineCPUMacros(Builder, "pentium");
3442     break;
3443   case CK_Pentium3:
3444   case CK_Pentium3M:
3445   case CK_PentiumM:
3446     Builder.defineMacro("__tune_pentium3__");
3447     // Fallthrough
3448   case CK_Pentium2:
3449   case CK_C3_2:
3450     Builder.defineMacro("__tune_pentium2__");
3451     // Fallthrough
3452   case CK_PentiumPro:
3453     Builder.defineMacro("__tune_i686__");
3454     Builder.defineMacro("__tune_pentiumpro__");
3455     // Fallthrough
3456   case CK_i686:
3457     Builder.defineMacro("__i686");
3458     Builder.defineMacro("__i686__");
3459     // Strangely, __tune_i686__ isn't defined by GCC when CPU == i686.
3460     Builder.defineMacro("__pentiumpro");
3461     Builder.defineMacro("__pentiumpro__");
3462     break;
3463   case CK_Pentium4:
3464   case CK_Pentium4M:
3465     defineCPUMacros(Builder, "pentium4");
3466     break;
3467   case CK_Yonah:
3468   case CK_Prescott:
3469   case CK_Nocona:
3470     defineCPUMacros(Builder, "nocona");
3471     break;
3472   case CK_Core2:
3473   case CK_Penryn:
3474     defineCPUMacros(Builder, "core2");
3475     break;
3476   case CK_Bonnell:
3477     defineCPUMacros(Builder, "atom");
3478     break;
3479   case CK_Silvermont:
3480     defineCPUMacros(Builder, "slm");
3481     break;
3482   case CK_Nehalem:
3483   case CK_Westmere:
3484   case CK_SandyBridge:
3485   case CK_IvyBridge:
3486   case CK_Haswell:
3487   case CK_Broadwell:
3488   case CK_SkylakeClient:
3489     // FIXME: Historically, we defined this legacy name, it would be nice to
3490     // remove it at some point. We've never exposed fine-grained names for
3491     // recent primary x86 CPUs, and we should keep it that way.
3492     defineCPUMacros(Builder, "corei7");
3493     break;
3494   case CK_SkylakeServer:
3495     defineCPUMacros(Builder, "skx");
3496     break;
3497   case CK_Cannonlake:
3498     break;
3499   case CK_KNL:
3500     defineCPUMacros(Builder, "knl");
3501     break;
3502   case CK_Lakemont:
3503     Builder.defineMacro("__tune_lakemont__");
3504     break;
3505   case CK_K6_2:
3506     Builder.defineMacro("__k6_2__");
3507     Builder.defineMacro("__tune_k6_2__");
3508     // Fallthrough
3509   case CK_K6_3:
3510     if (CPU != CK_K6_2) {  // In case of fallthrough
3511       // FIXME: GCC may be enabling these in cases where some other k6
3512       // architecture is specified but -m3dnow is explicitly provided. The
3513       // exact semantics need to be determined and emulated here.
3514       Builder.defineMacro("__k6_3__");
3515       Builder.defineMacro("__tune_k6_3__");
3516     }
3517     // Fallthrough
3518   case CK_K6:
3519     defineCPUMacros(Builder, "k6");
3520     break;
3521   case CK_Athlon:
3522   case CK_AthlonThunderbird:
3523   case CK_Athlon4:
3524   case CK_AthlonXP:
3525   case CK_AthlonMP:
3526     defineCPUMacros(Builder, "athlon");
3527     if (SSELevel != NoSSE) {
3528       Builder.defineMacro("__athlon_sse__");
3529       Builder.defineMacro("__tune_athlon_sse__");
3530     }
3531     break;
3532   case CK_K8:
3533   case CK_K8SSE3:
3534   case CK_x86_64:
3535   case CK_Opteron:
3536   case CK_OpteronSSE3:
3537   case CK_Athlon64:
3538   case CK_Athlon64SSE3:
3539   case CK_AthlonFX:
3540     defineCPUMacros(Builder, "k8");
3541     break;
3542   case CK_AMDFAM10:
3543     defineCPUMacros(Builder, "amdfam10");
3544     break;
3545   case CK_BTVER1:
3546     defineCPUMacros(Builder, "btver1");
3547     break;
3548   case CK_BTVER2:
3549     defineCPUMacros(Builder, "btver2");
3550     break;
3551   case CK_BDVER1:
3552     defineCPUMacros(Builder, "bdver1");
3553     break;
3554   case CK_BDVER2:
3555     defineCPUMacros(Builder, "bdver2");
3556     break;
3557   case CK_BDVER3:
3558     defineCPUMacros(Builder, "bdver3");
3559     break;
3560   case CK_BDVER4:
3561     defineCPUMacros(Builder, "bdver4");
3562     break;
3563   case CK_Geode:
3564     defineCPUMacros(Builder, "geode");
3565     break;
3566   }
3567 
3568   // Target properties.
3569   Builder.defineMacro("__REGISTER_PREFIX__", "");
3570 
3571   // Define __NO_MATH_INLINES on linux/x86 so that we don't get inline
3572   // functions in glibc header files that use FP Stack inline asm which the
3573   // backend can't deal with (PR879).
3574   Builder.defineMacro("__NO_MATH_INLINES");
3575 
3576   if (HasAES)
3577     Builder.defineMacro("__AES__");
3578 
3579   if (HasPCLMUL)
3580     Builder.defineMacro("__PCLMUL__");
3581 
3582   if (HasLZCNT)
3583     Builder.defineMacro("__LZCNT__");
3584 
3585   if (HasRDRND)
3586     Builder.defineMacro("__RDRND__");
3587 
3588   if (HasFSGSBASE)
3589     Builder.defineMacro("__FSGSBASE__");
3590 
3591   if (HasBMI)
3592     Builder.defineMacro("__BMI__");
3593 
3594   if (HasBMI2)
3595     Builder.defineMacro("__BMI2__");
3596 
3597   if (HasPOPCNT)
3598     Builder.defineMacro("__POPCNT__");
3599 
3600   if (HasRTM)
3601     Builder.defineMacro("__RTM__");
3602 
3603   if (HasPRFCHW)
3604     Builder.defineMacro("__PRFCHW__");
3605 
3606   if (HasRDSEED)
3607     Builder.defineMacro("__RDSEED__");
3608 
3609   if (HasADX)
3610     Builder.defineMacro("__ADX__");
3611 
3612   if (HasTBM)
3613     Builder.defineMacro("__TBM__");
3614 
3615   if (HasMWAITX)
3616     Builder.defineMacro("__MWAITX__");
3617 
3618   switch (XOPLevel) {
3619   case XOP:
3620     Builder.defineMacro("__XOP__");
3621   case FMA4:
3622     Builder.defineMacro("__FMA4__");
3623   case SSE4A:
3624     Builder.defineMacro("__SSE4A__");
3625   case NoXOP:
3626     break;
3627   }
3628 
3629   if (HasFMA)
3630     Builder.defineMacro("__FMA__");
3631 
3632   if (HasF16C)
3633     Builder.defineMacro("__F16C__");
3634 
3635   if (HasAVX512CD)
3636     Builder.defineMacro("__AVX512CD__");
3637   if (HasAVX512ER)
3638     Builder.defineMacro("__AVX512ER__");
3639   if (HasAVX512PF)
3640     Builder.defineMacro("__AVX512PF__");
3641   if (HasAVX512DQ)
3642     Builder.defineMacro("__AVX512DQ__");
3643   if (HasAVX512BW)
3644     Builder.defineMacro("__AVX512BW__");
3645   if (HasAVX512VL)
3646     Builder.defineMacro("__AVX512VL__");
3647   if (HasAVX512VBMI)
3648     Builder.defineMacro("__AVX512VBMI__");
3649   if (HasAVX512IFMA)
3650     Builder.defineMacro("__AVX512IFMA__");
3651 
3652   if (HasSHA)
3653     Builder.defineMacro("__SHA__");
3654 
3655   if (HasFXSR)
3656     Builder.defineMacro("__FXSR__");
3657   if (HasXSAVE)
3658     Builder.defineMacro("__XSAVE__");
3659   if (HasXSAVEOPT)
3660     Builder.defineMacro("__XSAVEOPT__");
3661   if (HasXSAVEC)
3662     Builder.defineMacro("__XSAVEC__");
3663   if (HasXSAVES)
3664     Builder.defineMacro("__XSAVES__");
3665   if (HasPKU)
3666     Builder.defineMacro("__PKU__");
3667   if (HasCX16)
3668     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16");
3669 
3670   // Each case falls through to the previous one here.
3671   switch (SSELevel) {
3672   case AVX512F:
3673     Builder.defineMacro("__AVX512F__");
3674   case AVX2:
3675     Builder.defineMacro("__AVX2__");
3676   case AVX:
3677     Builder.defineMacro("__AVX__");
3678   case SSE42:
3679     Builder.defineMacro("__SSE4_2__");
3680   case SSE41:
3681     Builder.defineMacro("__SSE4_1__");
3682   case SSSE3:
3683     Builder.defineMacro("__SSSE3__");
3684   case SSE3:
3685     Builder.defineMacro("__SSE3__");
3686   case SSE2:
3687     Builder.defineMacro("__SSE2__");
3688     Builder.defineMacro("__SSE2_MATH__");  // -mfp-math=sse always implied.
3689   case SSE1:
3690     Builder.defineMacro("__SSE__");
3691     Builder.defineMacro("__SSE_MATH__");   // -mfp-math=sse always implied.
3692   case NoSSE:
3693     break;
3694   }
3695 
3696   if (Opts.MicrosoftExt && getTriple().getArch() == llvm::Triple::x86) {
3697     switch (SSELevel) {
3698     case AVX512F:
3699     case AVX2:
3700     case AVX:
3701     case SSE42:
3702     case SSE41:
3703     case SSSE3:
3704     case SSE3:
3705     case SSE2:
3706       Builder.defineMacro("_M_IX86_FP", Twine(2));
3707       break;
3708     case SSE1:
3709       Builder.defineMacro("_M_IX86_FP", Twine(1));
3710       break;
3711     default:
3712       Builder.defineMacro("_M_IX86_FP", Twine(0));
3713     }
3714   }
3715 
3716   // Each case falls through to the previous one here.
3717   switch (MMX3DNowLevel) {
3718   case AMD3DNowAthlon:
3719     Builder.defineMacro("__3dNOW_A__");
3720   case AMD3DNow:
3721     Builder.defineMacro("__3dNOW__");
3722   case MMX:
3723     Builder.defineMacro("__MMX__");
3724   case NoMMX3DNow:
3725     break;
3726   }
3727 
3728   if (CPU >= CK_i486) {
3729     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
3730     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
3731     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
3732   }
3733   if (CPU >= CK_i586)
3734     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
3735 }
3736 
hasFeature(StringRef Feature) const3737 bool X86TargetInfo::hasFeature(StringRef Feature) const {
3738   return llvm::StringSwitch<bool>(Feature)
3739       .Case("aes", HasAES)
3740       .Case("avx", SSELevel >= AVX)
3741       .Case("avx2", SSELevel >= AVX2)
3742       .Case("avx512f", SSELevel >= AVX512F)
3743       .Case("avx512cd", HasAVX512CD)
3744       .Case("avx512er", HasAVX512ER)
3745       .Case("avx512pf", HasAVX512PF)
3746       .Case("avx512dq", HasAVX512DQ)
3747       .Case("avx512bw", HasAVX512BW)
3748       .Case("avx512vl", HasAVX512VL)
3749       .Case("avx512vbmi", HasAVX512VBMI)
3750       .Case("avx512ifma", HasAVX512IFMA)
3751       .Case("bmi", HasBMI)
3752       .Case("bmi2", HasBMI2)
3753       .Case("clflushopt", HasCLFLUSHOPT)
3754       .Case("clwb", HasCLWB)
3755       .Case("cx16", HasCX16)
3756       .Case("f16c", HasF16C)
3757       .Case("fma", HasFMA)
3758       .Case("fma4", XOPLevel >= FMA4)
3759       .Case("fsgsbase", HasFSGSBASE)
3760       .Case("fxsr", HasFXSR)
3761       .Case("lzcnt", HasLZCNT)
3762       .Case("mm3dnow", MMX3DNowLevel >= AMD3DNow)
3763       .Case("mm3dnowa", MMX3DNowLevel >= AMD3DNowAthlon)
3764       .Case("mmx", MMX3DNowLevel >= MMX)
3765       .Case("movbe", HasMOVBE)
3766       .Case("mpx", HasMPX)
3767       .Case("pclmul", HasPCLMUL)
3768       .Case("pcommit", HasPCOMMIT)
3769       .Case("pku", HasPKU)
3770       .Case("popcnt", HasPOPCNT)
3771       .Case("prefetchwt1", HasPREFETCHWT1)
3772       .Case("prfchw", HasPRFCHW)
3773       .Case("rdrnd", HasRDRND)
3774       .Case("rdseed", HasRDSEED)
3775       .Case("rtm", HasRTM)
3776       .Case("sgx", HasSGX)
3777       .Case("sha", HasSHA)
3778       .Case("sse", SSELevel >= SSE1)
3779       .Case("sse2", SSELevel >= SSE2)
3780       .Case("sse3", SSELevel >= SSE3)
3781       .Case("ssse3", SSELevel >= SSSE3)
3782       .Case("sse4.1", SSELevel >= SSE41)
3783       .Case("sse4.2", SSELevel >= SSE42)
3784       .Case("sse4a", XOPLevel >= SSE4A)
3785       .Case("tbm", HasTBM)
3786       .Case("umip", HasUMIP)
3787       .Case("x86", true)
3788       .Case("x86_32", getTriple().getArch() == llvm::Triple::x86)
3789       .Case("x86_64", getTriple().getArch() == llvm::Triple::x86_64)
3790       .Case("xop", XOPLevel >= XOP)
3791       .Case("xsave", HasXSAVE)
3792       .Case("xsavec", HasXSAVEC)
3793       .Case("xsaves", HasXSAVES)
3794       .Case("xsaveopt", HasXSAVEOPT)
3795       .Default(false);
3796 }
3797 
3798 // We can't use a generic validation scheme for the features accepted here
3799 // versus subtarget features accepted in the target attribute because the
3800 // bitfield structure that's initialized in the runtime only supports the
3801 // below currently rather than the full range of subtarget features. (See
3802 // X86TargetInfo::hasFeature for a somewhat comprehensive list).
validateCpuSupports(StringRef FeatureStr) const3803 bool X86TargetInfo::validateCpuSupports(StringRef FeatureStr) const {
3804   return llvm::StringSwitch<bool>(FeatureStr)
3805       .Case("cmov", true)
3806       .Case("mmx", true)
3807       .Case("popcnt", true)
3808       .Case("sse", true)
3809       .Case("sse2", true)
3810       .Case("sse3", true)
3811       .Case("ssse3", true)
3812       .Case("sse4.1", true)
3813       .Case("sse4.2", true)
3814       .Case("avx", true)
3815       .Case("avx2", true)
3816       .Case("sse4a", true)
3817       .Case("fma4", true)
3818       .Case("xop", true)
3819       .Case("fma", true)
3820       .Case("avx512f", true)
3821       .Case("bmi", true)
3822       .Case("bmi2", true)
3823       .Case("aes", true)
3824       .Case("pclmul", true)
3825       .Case("avx512vl", true)
3826       .Case("avx512bw", true)
3827       .Case("avx512dq", true)
3828       .Case("avx512cd", true)
3829       .Case("avx512er", true)
3830       .Case("avx512pf", true)
3831       .Case("avx512vbmi", true)
3832       .Case("avx512ifma", true)
3833       .Default(false);
3834 }
3835 
3836 bool
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const3837 X86TargetInfo::validateAsmConstraint(const char *&Name,
3838                                      TargetInfo::ConstraintInfo &Info) const {
3839   switch (*Name) {
3840   default: return false;
3841   // Constant constraints.
3842   case 'e': // 32-bit signed integer constant for use with sign-extending x86_64
3843             // instructions.
3844   case 'Z': // 32-bit unsigned integer constant for use with zero-extending
3845             // x86_64 instructions.
3846   case 's':
3847     Info.setRequiresImmediate();
3848     return true;
3849   case 'I':
3850     Info.setRequiresImmediate(0, 31);
3851     return true;
3852   case 'J':
3853     Info.setRequiresImmediate(0, 63);
3854     return true;
3855   case 'K':
3856     Info.setRequiresImmediate(-128, 127);
3857     return true;
3858   case 'L':
3859     Info.setRequiresImmediate({ int(0xff), int(0xffff), int(0xffffffff) });
3860     return true;
3861   case 'M':
3862     Info.setRequiresImmediate(0, 3);
3863     return true;
3864   case 'N':
3865     Info.setRequiresImmediate(0, 255);
3866     return true;
3867   case 'O':
3868     Info.setRequiresImmediate(0, 127);
3869     return true;
3870   // Register constraints.
3871   case 'Y': // 'Y' is the first character for several 2-character constraints.
3872     // Shift the pointer to the second character of the constraint.
3873     Name++;
3874     switch (*Name) {
3875     default:
3876       return false;
3877     case '0': // First SSE register.
3878     case 't': // Any SSE register, when SSE2 is enabled.
3879     case 'i': // Any SSE register, when SSE2 and inter-unit moves enabled.
3880     case 'm': // Any MMX register, when inter-unit moves enabled.
3881       Info.setAllowsRegister();
3882       return true;
3883     }
3884   case 'f': // Any x87 floating point stack register.
3885     // Constraint 'f' cannot be used for output operands.
3886     if (Info.ConstraintStr[0] == '=')
3887       return false;
3888     Info.setAllowsRegister();
3889     return true;
3890   case 'a': // eax.
3891   case 'b': // ebx.
3892   case 'c': // ecx.
3893   case 'd': // edx.
3894   case 'S': // esi.
3895   case 'D': // edi.
3896   case 'A': // edx:eax.
3897   case 't': // Top of floating point stack.
3898   case 'u': // Second from top of floating point stack.
3899   case 'q': // Any register accessible as [r]l: a, b, c, and d.
3900   case 'y': // Any MMX register.
3901   case 'x': // Any SSE register.
3902   case 'Q': // Any register accessible as [r]h: a, b, c, and d.
3903   case 'R': // "Legacy" registers: ax, bx, cx, dx, di, si, sp, bp.
3904   case 'l': // "Index" registers: any general register that can be used as an
3905             // index in a base+index memory access.
3906     Info.setAllowsRegister();
3907     return true;
3908   // Floating point constant constraints.
3909   case 'C': // SSE floating point constant.
3910   case 'G': // x87 floating point constant.
3911     return true;
3912   }
3913 }
3914 
validateOutputSize(StringRef Constraint,unsigned Size) const3915 bool X86TargetInfo::validateOutputSize(StringRef Constraint,
3916                                        unsigned Size) const {
3917   // Strip off constraint modifiers.
3918   while (Constraint[0] == '=' ||
3919          Constraint[0] == '+' ||
3920          Constraint[0] == '&')
3921     Constraint = Constraint.substr(1);
3922 
3923   return validateOperandSize(Constraint, Size);
3924 }
3925 
validateInputSize(StringRef Constraint,unsigned Size) const3926 bool X86TargetInfo::validateInputSize(StringRef Constraint,
3927                                       unsigned Size) const {
3928   return validateOperandSize(Constraint, Size);
3929 }
3930 
validateOperandSize(StringRef Constraint,unsigned Size) const3931 bool X86TargetInfo::validateOperandSize(StringRef Constraint,
3932                                         unsigned Size) const {
3933   switch (Constraint[0]) {
3934   default: break;
3935   case 'y':
3936     return Size <= 64;
3937   case 'f':
3938   case 't':
3939   case 'u':
3940     return Size <= 128;
3941   case 'x':
3942     if (SSELevel >= AVX512F)
3943       // 512-bit zmm registers can be used if target supports AVX512F.
3944       return Size <= 512U;
3945     else if (SSELevel >= AVX)
3946       // 256-bit ymm registers can be used if target supports AVX.
3947       return Size <= 256U;
3948     return Size <= 128U;
3949   case 'Y':
3950     // 'Y' is the first character for several 2-character constraints.
3951     switch (Constraint[1]) {
3952     default: break;
3953     case 'm':
3954       // 'Ym' is synonymous with 'y'.
3955       return Size <= 64;
3956     case 'i':
3957     case 't':
3958       // 'Yi' and 'Yt' are synonymous with 'x' when SSE2 is enabled.
3959       if (SSELevel >= AVX512F)
3960         return Size <= 512U;
3961       else if (SSELevel >= AVX)
3962         return Size <= 256U;
3963       return SSELevel >= SSE2 && Size <= 128U;
3964     }
3965 
3966   }
3967 
3968   return true;
3969 }
3970 
3971 std::string
convertConstraint(const char * & Constraint) const3972 X86TargetInfo::convertConstraint(const char *&Constraint) const {
3973   switch (*Constraint) {
3974   case 'a': return std::string("{ax}");
3975   case 'b': return std::string("{bx}");
3976   case 'c': return std::string("{cx}");
3977   case 'd': return std::string("{dx}");
3978   case 'S': return std::string("{si}");
3979   case 'D': return std::string("{di}");
3980   case 'p': // address
3981     return std::string("im");
3982   case 't': // top of floating point stack.
3983     return std::string("{st}");
3984   case 'u': // second from top of floating point stack.
3985     return std::string("{st(1)}"); // second from top of floating point stack.
3986   default:
3987     return std::string(1, *Constraint);
3988   }
3989 }
3990 
3991 // X86-32 generic target
3992 class X86_32TargetInfo : public X86TargetInfo {
3993 public:
X86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)3994   X86_32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
3995       : X86TargetInfo(Triple, Opts) {
3996     DoubleAlign = LongLongAlign = 32;
3997     LongDoubleWidth = 96;
3998     LongDoubleAlign = 32;
3999     SuitableAlign = 128;
4000     resetDataLayout("e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128");
4001     SizeType = UnsignedInt;
4002     PtrDiffType = SignedInt;
4003     IntPtrType = SignedInt;
4004     RegParmMax = 3;
4005 
4006     // Use fpret for all types.
4007     RealTypeUsesObjCFPRet = ((1 << TargetInfo::Float) |
4008                              (1 << TargetInfo::Double) |
4009                              (1 << TargetInfo::LongDouble));
4010 
4011     // x86-32 has atomics up to 8 bytes
4012     // FIXME: Check that we actually have cmpxchg8b before setting
4013     // MaxAtomicInlineWidth. (cmpxchg8b is an i586 instruction.)
4014     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
4015   }
getBuiltinVaListKind() const4016   BuiltinVaListKind getBuiltinVaListKind() const override {
4017     return TargetInfo::CharPtrBuiltinVaList;
4018   }
4019 
getEHDataRegisterNumber(unsigned RegNo) const4020   int getEHDataRegisterNumber(unsigned RegNo) const override {
4021     if (RegNo == 0) return 0;
4022     if (RegNo == 1) return 2;
4023     return -1;
4024   }
validateOperandSize(StringRef Constraint,unsigned Size) const4025   bool validateOperandSize(StringRef Constraint,
4026                            unsigned Size) const override {
4027     switch (Constraint[0]) {
4028     default: break;
4029     case 'R':
4030     case 'q':
4031     case 'Q':
4032     case 'a':
4033     case 'b':
4034     case 'c':
4035     case 'd':
4036     case 'S':
4037     case 'D':
4038       return Size <= 32;
4039     case 'A':
4040       return Size <= 64;
4041     }
4042 
4043     return X86TargetInfo::validateOperandSize(Constraint, Size);
4044   }
4045 };
4046 
4047 class NetBSDI386TargetInfo : public NetBSDTargetInfo<X86_32TargetInfo> {
4048 public:
NetBSDI386TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4049   NetBSDI386TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4050       : NetBSDTargetInfo<X86_32TargetInfo>(Triple, Opts) {}
4051 
getFloatEvalMethod() const4052   unsigned getFloatEvalMethod() const override {
4053     unsigned Major, Minor, Micro;
4054     getTriple().getOSVersion(Major, Minor, Micro);
4055     // New NetBSD uses the default rounding mode.
4056     if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 26) || Major == 0)
4057       return X86_32TargetInfo::getFloatEvalMethod();
4058     // NetBSD before 6.99.26 defaults to "double" rounding.
4059     return 1;
4060   }
4061 };
4062 
4063 class OpenBSDI386TargetInfo : public OpenBSDTargetInfo<X86_32TargetInfo> {
4064 public:
OpenBSDI386TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4065   OpenBSDI386TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4066       : OpenBSDTargetInfo<X86_32TargetInfo>(Triple, Opts) {
4067     SizeType = UnsignedLong;
4068     IntPtrType = SignedLong;
4069     PtrDiffType = SignedLong;
4070   }
4071 };
4072 
4073 class BitrigI386TargetInfo : public BitrigTargetInfo<X86_32TargetInfo> {
4074 public:
BitrigI386TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4075   BitrigI386TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4076       : BitrigTargetInfo<X86_32TargetInfo>(Triple, Opts) {
4077     SizeType = UnsignedLong;
4078     IntPtrType = SignedLong;
4079     PtrDiffType = SignedLong;
4080   }
4081 };
4082 
4083 class DarwinI386TargetInfo : public DarwinTargetInfo<X86_32TargetInfo> {
4084 public:
DarwinI386TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4085   DarwinI386TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4086       : DarwinTargetInfo<X86_32TargetInfo>(Triple, Opts) {
4087     LongDoubleWidth = 128;
4088     LongDoubleAlign = 128;
4089     SuitableAlign = 128;
4090     MaxVectorAlign = 256;
4091     // The watchOS simulator uses the builtin bool type for Objective-C.
4092     llvm::Triple T = llvm::Triple(Triple);
4093     if (T.isWatchOS())
4094       UseSignedCharForObjCBool = false;
4095     SizeType = UnsignedLong;
4096     IntPtrType = SignedLong;
4097     resetDataLayout("e-m:o-p:32:32-f64:32:64-f80:128-n8:16:32-S128");
4098     HasAlignMac68kSupport = true;
4099   }
4100 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)4101   bool handleTargetFeatures(std::vector<std::string> &Features,
4102                             DiagnosticsEngine &Diags) override {
4103     if (!DarwinTargetInfo<X86_32TargetInfo>::handleTargetFeatures(Features,
4104                                                                   Diags))
4105       return false;
4106     // We now know the features we have: we can decide how to align vectors.
4107     MaxVectorAlign =
4108         hasFeature("avx512f") ? 512 : hasFeature("avx") ? 256 : 128;
4109     return true;
4110   }
4111 };
4112 
4113 // x86-32 Windows target
4114 class WindowsX86_32TargetInfo : public WindowsTargetInfo<X86_32TargetInfo> {
4115 public:
WindowsX86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4116   WindowsX86_32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4117       : WindowsTargetInfo<X86_32TargetInfo>(Triple, Opts) {
4118     WCharType = UnsignedShort;
4119     DoubleAlign = LongLongAlign = 64;
4120     bool IsWinCOFF =
4121         getTriple().isOSWindows() && getTriple().isOSBinFormatCOFF();
4122     resetDataLayout(IsWinCOFF
4123                         ? "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32"
4124                         : "e-m:e-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32");
4125   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4126   void getTargetDefines(const LangOptions &Opts,
4127                         MacroBuilder &Builder) const override {
4128     WindowsTargetInfo<X86_32TargetInfo>::getTargetDefines(Opts, Builder);
4129   }
4130 };
4131 
4132 // x86-32 Windows Visual Studio target
4133 class MicrosoftX86_32TargetInfo : public WindowsX86_32TargetInfo {
4134 public:
MicrosoftX86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4135   MicrosoftX86_32TargetInfo(const llvm::Triple &Triple,
4136                             const TargetOptions &Opts)
4137       : WindowsX86_32TargetInfo(Triple, Opts) {
4138     LongDoubleWidth = LongDoubleAlign = 64;
4139     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
4140   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4141   void getTargetDefines(const LangOptions &Opts,
4142                         MacroBuilder &Builder) const override {
4143     WindowsX86_32TargetInfo::getTargetDefines(Opts, Builder);
4144     WindowsX86_32TargetInfo::getVisualStudioDefines(Opts, Builder);
4145     // The value of the following reflects processor type.
4146     // 300=386, 400=486, 500=Pentium, 600=Blend (default)
4147     // We lost the original triple, so we use the default.
4148     Builder.defineMacro("_M_IX86", "600");
4149   }
4150 };
4151 
addCygMingDefines(const LangOptions & Opts,MacroBuilder & Builder)4152 static void addCygMingDefines(const LangOptions &Opts, MacroBuilder &Builder) {
4153   // Mingw and cygwin define __declspec(a) to __attribute__((a)).  Clang
4154   // supports __declspec natively under -fms-extensions, but we define a no-op
4155   // __declspec macro anyway for pre-processor compatibility.
4156   if (Opts.MicrosoftExt)
4157     Builder.defineMacro("__declspec", "__declspec");
4158   else
4159     Builder.defineMacro("__declspec(a)", "__attribute__((a))");
4160 
4161   if (!Opts.MicrosoftExt) {
4162     // Provide macros for all the calling convention keywords.  Provide both
4163     // single and double underscore prefixed variants.  These are available on
4164     // x64 as well as x86, even though they have no effect.
4165     const char *CCs[] = {"cdecl", "stdcall", "fastcall", "thiscall", "pascal"};
4166     for (const char *CC : CCs) {
4167       std::string GCCSpelling = "__attribute__((__";
4168       GCCSpelling += CC;
4169       GCCSpelling += "__))";
4170       Builder.defineMacro(Twine("_") + CC, GCCSpelling);
4171       Builder.defineMacro(Twine("__") + CC, GCCSpelling);
4172     }
4173   }
4174 }
4175 
addMinGWDefines(const LangOptions & Opts,MacroBuilder & Builder)4176 static void addMinGWDefines(const LangOptions &Opts, MacroBuilder &Builder) {
4177   Builder.defineMacro("__MSVCRT__");
4178   Builder.defineMacro("__MINGW32__");
4179   addCygMingDefines(Opts, Builder);
4180 }
4181 
4182 // x86-32 MinGW target
4183 class MinGWX86_32TargetInfo : public WindowsX86_32TargetInfo {
4184 public:
MinGWX86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4185   MinGWX86_32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4186       : WindowsX86_32TargetInfo(Triple, Opts) {}
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4187   void getTargetDefines(const LangOptions &Opts,
4188                         MacroBuilder &Builder) const override {
4189     WindowsX86_32TargetInfo::getTargetDefines(Opts, Builder);
4190     DefineStd(Builder, "WIN32", Opts);
4191     DefineStd(Builder, "WINNT", Opts);
4192     Builder.defineMacro("_X86_");
4193     addMinGWDefines(Opts, Builder);
4194   }
4195 };
4196 
4197 // x86-32 Cygwin target
4198 class CygwinX86_32TargetInfo : public X86_32TargetInfo {
4199 public:
CygwinX86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4200   CygwinX86_32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4201       : X86_32TargetInfo(Triple, Opts) {
4202     WCharType = UnsignedShort;
4203     DoubleAlign = LongLongAlign = 64;
4204     resetDataLayout("e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32");
4205   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4206   void getTargetDefines(const LangOptions &Opts,
4207                         MacroBuilder &Builder) const override {
4208     X86_32TargetInfo::getTargetDefines(Opts, Builder);
4209     Builder.defineMacro("_X86_");
4210     Builder.defineMacro("__CYGWIN__");
4211     Builder.defineMacro("__CYGWIN32__");
4212     addCygMingDefines(Opts, Builder);
4213     DefineStd(Builder, "unix", Opts);
4214     if (Opts.CPlusPlus)
4215       Builder.defineMacro("_GNU_SOURCE");
4216   }
4217 };
4218 
4219 // x86-32 Haiku target
4220 class HaikuX86_32TargetInfo : public HaikuTargetInfo<X86_32TargetInfo> {
4221 public:
HaikuX86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4222   HaikuX86_32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4223     : HaikuTargetInfo<X86_32TargetInfo>(Triple, Opts) {
4224   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4225   void getTargetDefines(const LangOptions &Opts,
4226                         MacroBuilder &Builder) const override {
4227     HaikuTargetInfo<X86_32TargetInfo>::getTargetDefines(Opts, Builder);
4228     Builder.defineMacro("__INTEL__");
4229   }
4230 };
4231 
4232 // X86-32 MCU target
4233 class MCUX86_32TargetInfo : public X86_32TargetInfo {
4234 public:
MCUX86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4235   MCUX86_32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4236       : X86_32TargetInfo(Triple, Opts) {
4237     LongDoubleWidth = 64;
4238     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
4239     resetDataLayout("e-m:e-p:32:32-i64:32-f64:32-f128:32-n8:16:32-a:0:32-S32");
4240     WIntType = UnsignedInt;
4241   }
4242 
checkCallingConvention(CallingConv CC) const4243   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
4244     // On MCU we support only C calling convention.
4245     return CC == CC_C ? CCCR_OK : CCCR_Warning;
4246   }
4247 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4248   void getTargetDefines(const LangOptions &Opts,
4249                         MacroBuilder &Builder) const override {
4250     X86_32TargetInfo::getTargetDefines(Opts, Builder);
4251     Builder.defineMacro("__iamcu");
4252     Builder.defineMacro("__iamcu__");
4253   }
4254 
allowsLargerPreferedTypeAlignment() const4255   bool allowsLargerPreferedTypeAlignment() const override {
4256     return false;
4257   }
4258 };
4259 
4260 // RTEMS Target
4261 template<typename Target>
4262 class RTEMSTargetInfo : public OSTargetInfo<Target> {
4263 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const4264   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
4265                     MacroBuilder &Builder) const override {
4266     // RTEMS defines; list based off of gcc output
4267 
4268     Builder.defineMacro("__rtems__");
4269     Builder.defineMacro("__ELF__");
4270   }
4271 
4272 public:
RTEMSTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4273   RTEMSTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4274       : OSTargetInfo<Target>(Triple, Opts) {
4275     switch (Triple.getArch()) {
4276     default:
4277     case llvm::Triple::x86:
4278       // this->MCountName = ".mcount";
4279       break;
4280     case llvm::Triple::mips:
4281     case llvm::Triple::mipsel:
4282     case llvm::Triple::ppc:
4283     case llvm::Triple::ppc64:
4284     case llvm::Triple::ppc64le:
4285       // this->MCountName = "_mcount";
4286       break;
4287     case llvm::Triple::arm:
4288       // this->MCountName = "__mcount";
4289       break;
4290     }
4291   }
4292 };
4293 
4294 // x86-32 RTEMS target
4295 class RTEMSX86_32TargetInfo : public X86_32TargetInfo {
4296 public:
RTEMSX86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4297   RTEMSX86_32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4298       : X86_32TargetInfo(Triple, Opts) {
4299     SizeType = UnsignedLong;
4300     IntPtrType = SignedLong;
4301     PtrDiffType = SignedLong;
4302   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4303   void getTargetDefines(const LangOptions &Opts,
4304                         MacroBuilder &Builder) const override {
4305     X86_32TargetInfo::getTargetDefines(Opts, Builder);
4306     Builder.defineMacro("__INTEL__");
4307     Builder.defineMacro("__rtems__");
4308   }
4309 };
4310 
4311 // x86-64 generic target
4312 class X86_64TargetInfo : public X86TargetInfo {
4313 public:
X86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4314   X86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4315       : X86TargetInfo(Triple, Opts) {
4316     const bool IsX32 = getTriple().getEnvironment() == llvm::Triple::GNUX32;
4317     bool IsWinCOFF =
4318         getTriple().isOSWindows() && getTriple().isOSBinFormatCOFF();
4319     LongWidth = LongAlign = PointerWidth = PointerAlign = IsX32 ? 32 : 64;
4320     LongDoubleWidth = 128;
4321     LongDoubleAlign = 128;
4322     LargeArrayMinWidth = 128;
4323     LargeArrayAlign = 128;
4324     SuitableAlign = 128;
4325     SizeType    = IsX32 ? UnsignedInt      : UnsignedLong;
4326     PtrDiffType = IsX32 ? SignedInt        : SignedLong;
4327     IntPtrType  = IsX32 ? SignedInt        : SignedLong;
4328     IntMaxType  = IsX32 ? SignedLongLong   : SignedLong;
4329     Int64Type   = IsX32 ? SignedLongLong   : SignedLong;
4330     RegParmMax = 6;
4331 
4332     // Pointers are 32-bit in x32.
4333     resetDataLayout(IsX32
4334                         ? "e-m:e-p:32:32-i64:64-f80:128-n8:16:32:64-S128"
4335                         : IsWinCOFF ? "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
4336                                     : "e-m:e-i64:64-f80:128-n8:16:32:64-S128");
4337 
4338     // Use fpret only for long double.
4339     RealTypeUsesObjCFPRet = (1 << TargetInfo::LongDouble);
4340 
4341     // Use fp2ret for _Complex long double.
4342     ComplexLongDoubleUsesFP2Ret = true;
4343 
4344     // Make __builtin_ms_va_list available.
4345     HasBuiltinMSVaList = true;
4346 
4347     // x86-64 has atomics up to 16 bytes.
4348     MaxAtomicPromoteWidth = 128;
4349     MaxAtomicInlineWidth = 128;
4350   }
getBuiltinVaListKind() const4351   BuiltinVaListKind getBuiltinVaListKind() const override {
4352     return TargetInfo::X86_64ABIBuiltinVaList;
4353   }
4354 
getEHDataRegisterNumber(unsigned RegNo) const4355   int getEHDataRegisterNumber(unsigned RegNo) const override {
4356     if (RegNo == 0) return 0;
4357     if (RegNo == 1) return 1;
4358     return -1;
4359   }
4360 
checkCallingConvention(CallingConv CC) const4361   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
4362     switch (CC) {
4363     case CC_C:
4364     case CC_Swift:
4365     case CC_X86VectorCall:
4366     case CC_IntelOclBicc:
4367     case CC_X86_64Win64:
4368     case CC_PreserveMost:
4369     case CC_PreserveAll:
4370       return CCCR_OK;
4371     default:
4372       return CCCR_Warning;
4373     }
4374   }
4375 
getDefaultCallingConv(CallingConvMethodType MT) const4376   CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override {
4377     return CC_C;
4378   }
4379 
4380   // for x32 we need it here explicitly
hasInt128Type() const4381   bool hasInt128Type() const override { return true; }
getUnwindWordWidth() const4382   unsigned getUnwindWordWidth() const override { return 64; }
getRegisterWidth() const4383   unsigned getRegisterWidth() const override { return 64; }
4384 
validateGlobalRegisterVariable(StringRef RegName,unsigned RegSize,bool & HasSizeMismatch) const4385   bool validateGlobalRegisterVariable(StringRef RegName,
4386                                       unsigned RegSize,
4387                                       bool &HasSizeMismatch) const override {
4388     // rsp and rbp are the only 64-bit registers the x86 backend can currently
4389     // handle.
4390     if (RegName.equals("rsp") || RegName.equals("rbp")) {
4391       // Check that the register size is 64-bit.
4392       HasSizeMismatch = RegSize != 64;
4393       return true;
4394     }
4395 
4396     // Check if the register is a 32-bit register the backend can handle.
4397     return X86TargetInfo::validateGlobalRegisterVariable(RegName, RegSize,
4398                                                          HasSizeMismatch);
4399   }
4400 };
4401 
4402 // x86-64 Windows target
4403 class WindowsX86_64TargetInfo : public WindowsTargetInfo<X86_64TargetInfo> {
4404 public:
WindowsX86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4405   WindowsX86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4406       : WindowsTargetInfo<X86_64TargetInfo>(Triple, Opts) {
4407     WCharType = UnsignedShort;
4408     LongWidth = LongAlign = 32;
4409     DoubleAlign = LongLongAlign = 64;
4410     IntMaxType = SignedLongLong;
4411     Int64Type = SignedLongLong;
4412     SizeType = UnsignedLongLong;
4413     PtrDiffType = SignedLongLong;
4414     IntPtrType = SignedLongLong;
4415   }
4416 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4417   void getTargetDefines(const LangOptions &Opts,
4418                                 MacroBuilder &Builder) const override {
4419     WindowsTargetInfo<X86_64TargetInfo>::getTargetDefines(Opts, Builder);
4420     Builder.defineMacro("_WIN64");
4421   }
4422 
getBuiltinVaListKind() const4423   BuiltinVaListKind getBuiltinVaListKind() const override {
4424     return TargetInfo::CharPtrBuiltinVaList;
4425   }
4426 
checkCallingConvention(CallingConv CC) const4427   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
4428     switch (CC) {
4429     case CC_X86StdCall:
4430     case CC_X86ThisCall:
4431     case CC_X86FastCall:
4432       return CCCR_Ignore;
4433     case CC_C:
4434     case CC_X86VectorCall:
4435     case CC_IntelOclBicc:
4436     case CC_X86_64SysV:
4437       return CCCR_OK;
4438     default:
4439       return CCCR_Warning;
4440     }
4441   }
4442 };
4443 
4444 // x86-64 Windows Visual Studio target
4445 class MicrosoftX86_64TargetInfo : public WindowsX86_64TargetInfo {
4446 public:
MicrosoftX86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4447   MicrosoftX86_64TargetInfo(const llvm::Triple &Triple,
4448                             const TargetOptions &Opts)
4449       : WindowsX86_64TargetInfo(Triple, Opts) {
4450     LongDoubleWidth = LongDoubleAlign = 64;
4451     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
4452   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4453   void getTargetDefines(const LangOptions &Opts,
4454                         MacroBuilder &Builder) const override {
4455     WindowsX86_64TargetInfo::getTargetDefines(Opts, Builder);
4456     WindowsX86_64TargetInfo::getVisualStudioDefines(Opts, Builder);
4457     Builder.defineMacro("_M_X64", "100");
4458     Builder.defineMacro("_M_AMD64", "100");
4459   }
4460 };
4461 
4462 // x86-64 MinGW target
4463 class MinGWX86_64TargetInfo : public WindowsX86_64TargetInfo {
4464 public:
MinGWX86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4465   MinGWX86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4466       : WindowsX86_64TargetInfo(Triple, Opts) {
4467     // Mingw64 rounds long double size and alignment up to 16 bytes, but sticks
4468     // with x86 FP ops. Weird.
4469     LongDoubleWidth = LongDoubleAlign = 128;
4470     LongDoubleFormat = &llvm::APFloat::x87DoubleExtended;
4471   }
4472 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4473   void getTargetDefines(const LangOptions &Opts,
4474                         MacroBuilder &Builder) const override {
4475     WindowsX86_64TargetInfo::getTargetDefines(Opts, Builder);
4476     DefineStd(Builder, "WIN64", Opts);
4477     Builder.defineMacro("__MINGW64__");
4478     addMinGWDefines(Opts, Builder);
4479 
4480     // GCC defines this macro when it is using __gxx_personality_seh0.
4481     if (!Opts.SjLjExceptions)
4482       Builder.defineMacro("__SEH__");
4483   }
4484 };
4485 
4486 // x86-64 Cygwin target
4487 class CygwinX86_64TargetInfo : public X86_64TargetInfo {
4488 public:
CygwinX86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4489   CygwinX86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4490       : X86_64TargetInfo(Triple, Opts) {
4491     TLSSupported = false;
4492     WCharType = UnsignedShort;
4493   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4494   void getTargetDefines(const LangOptions &Opts,
4495                         MacroBuilder &Builder) const override {
4496     X86_64TargetInfo::getTargetDefines(Opts, Builder);
4497     Builder.defineMacro("__x86_64__");
4498     Builder.defineMacro("__CYGWIN__");
4499     Builder.defineMacro("__CYGWIN64__");
4500     addCygMingDefines(Opts, Builder);
4501     DefineStd(Builder, "unix", Opts);
4502     if (Opts.CPlusPlus)
4503       Builder.defineMacro("_GNU_SOURCE");
4504 
4505     // GCC defines this macro when it is using __gxx_personality_seh0.
4506     if (!Opts.SjLjExceptions)
4507       Builder.defineMacro("__SEH__");
4508   }
4509 };
4510 
4511 class DarwinX86_64TargetInfo : public DarwinTargetInfo<X86_64TargetInfo> {
4512 public:
DarwinX86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4513   DarwinX86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4514       : DarwinTargetInfo<X86_64TargetInfo>(Triple, Opts) {
4515     Int64Type = SignedLongLong;
4516     // The 64-bit iOS simulator uses the builtin bool type for Objective-C.
4517     llvm::Triple T = llvm::Triple(Triple);
4518     if (T.isiOS())
4519       UseSignedCharForObjCBool = false;
4520     resetDataLayout("e-m:o-i64:64-f80:128-n8:16:32:64-S128");
4521   }
4522 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)4523   bool handleTargetFeatures(std::vector<std::string> &Features,
4524                             DiagnosticsEngine &Diags) override {
4525     if (!DarwinTargetInfo<X86_64TargetInfo>::handleTargetFeatures(Features,
4526                                                                   Diags))
4527       return false;
4528     // We now know the features we have: we can decide how to align vectors.
4529     MaxVectorAlign =
4530         hasFeature("avx512f") ? 512 : hasFeature("avx") ? 256 : 128;
4531     return true;
4532   }
4533 };
4534 
4535 class OpenBSDX86_64TargetInfo : public OpenBSDTargetInfo<X86_64TargetInfo> {
4536 public:
OpenBSDX86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4537   OpenBSDX86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4538       : OpenBSDTargetInfo<X86_64TargetInfo>(Triple, Opts) {
4539     IntMaxType = SignedLongLong;
4540     Int64Type = SignedLongLong;
4541   }
4542 };
4543 
4544 class BitrigX86_64TargetInfo : public BitrigTargetInfo<X86_64TargetInfo> {
4545 public:
BitrigX86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)4546   BitrigX86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
4547       : BitrigTargetInfo<X86_64TargetInfo>(Triple, Opts) {
4548     IntMaxType = SignedLongLong;
4549     Int64Type = SignedLongLong;
4550   }
4551 };
4552 
4553 class ARMTargetInfo : public TargetInfo {
4554   // Possible FPU choices.
4555   enum FPUMode {
4556     VFP2FPU = (1 << 0),
4557     VFP3FPU = (1 << 1),
4558     VFP4FPU = (1 << 2),
4559     NeonFPU = (1 << 3),
4560     FPARMV8 = (1 << 4)
4561   };
4562 
4563   // Possible HWDiv features.
4564   enum HWDivMode {
4565     HWDivThumb = (1 << 0),
4566     HWDivARM = (1 << 1)
4567   };
4568 
FPUModeIsVFP(FPUMode Mode)4569   static bool FPUModeIsVFP(FPUMode Mode) {
4570     return Mode & (VFP2FPU | VFP3FPU | VFP4FPU | NeonFPU | FPARMV8);
4571   }
4572 
4573   static const TargetInfo::GCCRegAlias GCCRegAliases[];
4574   static const char * const GCCRegNames[];
4575 
4576   std::string ABI, CPU;
4577 
4578   StringRef CPUProfile;
4579   StringRef CPUAttr;
4580 
4581   enum {
4582     FP_Default,
4583     FP_VFP,
4584     FP_Neon
4585   } FPMath;
4586 
4587   unsigned ArchISA;
4588   unsigned ArchKind = llvm::ARM::AK_ARMV4T;
4589   unsigned ArchProfile;
4590   unsigned ArchVersion;
4591 
4592   unsigned FPU : 5;
4593 
4594   unsigned IsAAPCS : 1;
4595   unsigned HWDiv : 2;
4596 
4597   // Initialized via features.
4598   unsigned SoftFloat : 1;
4599   unsigned SoftFloatABI : 1;
4600 
4601   unsigned CRC : 1;
4602   unsigned Crypto : 1;
4603   unsigned DSP : 1;
4604   unsigned Unaligned : 1;
4605 
4606   enum {
4607     LDREX_B = (1 << 0), /// byte (8-bit)
4608     LDREX_H = (1 << 1), /// half (16-bit)
4609     LDREX_W = (1 << 2), /// word (32-bit)
4610     LDREX_D = (1 << 3), /// double (64-bit)
4611   };
4612 
4613   uint32_t LDREX;
4614 
4615   // ACLE 6.5.1 Hardware floating point
4616   enum {
4617     HW_FP_HP = (1 << 1), /// half (16-bit)
4618     HW_FP_SP = (1 << 2), /// single (32-bit)
4619     HW_FP_DP = (1 << 3), /// double (64-bit)
4620   };
4621   uint32_t HW_FP;
4622 
4623   static const Builtin::Info BuiltinInfo[];
4624 
setABIAAPCS()4625   void setABIAAPCS() {
4626     IsAAPCS = true;
4627 
4628     DoubleAlign = LongLongAlign = LongDoubleAlign = SuitableAlign = 64;
4629     const llvm::Triple &T = getTriple();
4630 
4631     // size_t is unsigned long on MachO-derived environments, NetBSD and Bitrig.
4632     if (T.isOSBinFormatMachO() || T.getOS() == llvm::Triple::NetBSD ||
4633         T.getOS() == llvm::Triple::Bitrig)
4634       SizeType = UnsignedLong;
4635     else
4636       SizeType = UnsignedInt;
4637 
4638     switch (T.getOS()) {
4639     case llvm::Triple::NetBSD:
4640       WCharType = SignedInt;
4641       break;
4642     case llvm::Triple::Win32:
4643       WCharType = UnsignedShort;
4644       break;
4645     case llvm::Triple::Linux:
4646     default:
4647       // AAPCS 7.1.1, ARM-Linux ABI 2.4: type of wchar_t is unsigned int.
4648       WCharType = UnsignedInt;
4649       break;
4650     }
4651 
4652     UseBitFieldTypeAlignment = true;
4653 
4654     ZeroLengthBitfieldBoundary = 0;
4655 
4656     // Thumb1 add sp, #imm requires the immediate value be multiple of 4,
4657     // so set preferred for small types to 32.
4658     if (T.isOSBinFormatMachO()) {
4659       resetDataLayout(BigEndian
4660                           ? "E-m:o-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64"
4661                           : "e-m:o-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64");
4662     } else if (T.isOSWindows()) {
4663       assert(!BigEndian && "Windows on ARM does not support big endian");
4664       resetDataLayout("e"
4665                       "-m:w"
4666                       "-p:32:32"
4667                       "-i64:64"
4668                       "-v128:64:128"
4669                       "-a:0:32"
4670                       "-n32"
4671                       "-S64");
4672     } else if (T.isOSNaCl()) {
4673       assert(!BigEndian && "NaCl on ARM does not support big endian");
4674       resetDataLayout("e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S128");
4675     } else {
4676       resetDataLayout(BigEndian
4677                           ? "E-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64"
4678                           : "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64");
4679     }
4680 
4681     // FIXME: Enumerated types are variable width in straight AAPCS.
4682   }
4683 
setABIAPCS(bool IsAAPCS16)4684   void setABIAPCS(bool IsAAPCS16) {
4685     const llvm::Triple &T = getTriple();
4686 
4687     IsAAPCS = false;
4688 
4689     if (IsAAPCS16)
4690       DoubleAlign = LongLongAlign = LongDoubleAlign = SuitableAlign = 64;
4691     else
4692       DoubleAlign = LongLongAlign = LongDoubleAlign = SuitableAlign = 32;
4693 
4694     // size_t is unsigned int on FreeBSD.
4695     if (T.getOS() == llvm::Triple::FreeBSD)
4696       SizeType = UnsignedInt;
4697     else
4698       SizeType = UnsignedLong;
4699 
4700     // Revert to using SignedInt on apcs-gnu to comply with existing behaviour.
4701     WCharType = SignedInt;
4702 
4703     // Do not respect the alignment of bit-field types when laying out
4704     // structures. This corresponds to PCC_BITFIELD_TYPE_MATTERS in gcc.
4705     UseBitFieldTypeAlignment = false;
4706 
4707     /// gcc forces the alignment to 4 bytes, regardless of the type of the
4708     /// zero length bitfield.  This corresponds to EMPTY_FIELD_BOUNDARY in
4709     /// gcc.
4710     ZeroLengthBitfieldBoundary = 32;
4711 
4712     if (T.isOSBinFormatMachO() && IsAAPCS16) {
4713       assert(!BigEndian && "AAPCS16 does not support big-endian");
4714       resetDataLayout("e-m:o-p:32:32-i64:64-a:0:32-n32-S128");
4715     } else if (T.isOSBinFormatMachO())
4716       resetDataLayout(
4717           BigEndian
4718               ? "E-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32"
4719               : "e-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32");
4720     else
4721       resetDataLayout(
4722           BigEndian
4723               ? "E-m:e-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32"
4724               : "e-m:e-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32");
4725 
4726     // FIXME: Override "preferred align" for double and long long.
4727   }
4728 
setArchInfo()4729   void setArchInfo() {
4730     StringRef ArchName = getTriple().getArchName();
4731 
4732     ArchISA     = llvm::ARM::parseArchISA(ArchName);
4733     CPU         = llvm::ARM::getDefaultCPU(ArchName);
4734     unsigned AK = llvm::ARM::parseArch(ArchName);
4735     if (AK != llvm::ARM::AK_INVALID)
4736       ArchKind = AK;
4737     setArchInfo(ArchKind);
4738   }
4739 
setArchInfo(unsigned Kind)4740   void setArchInfo(unsigned Kind) {
4741     StringRef SubArch;
4742 
4743     // cache TargetParser info
4744     ArchKind    = Kind;
4745     SubArch     = llvm::ARM::getSubArch(ArchKind);
4746     ArchProfile = llvm::ARM::parseArchProfile(SubArch);
4747     ArchVersion = llvm::ARM::parseArchVersion(SubArch);
4748 
4749     // cache CPU related strings
4750     CPUAttr    = getCPUAttr();
4751     CPUProfile = getCPUProfile();
4752   }
4753 
setAtomic()4754   void setAtomic() {
4755     // when triple does not specify a sub arch,
4756     // then we are not using inline atomics
4757     bool ShouldUseInlineAtomic =
4758                    (ArchISA == llvm::ARM::IK_ARM   && ArchVersion >= 6) ||
4759                    (ArchISA == llvm::ARM::IK_THUMB && ArchVersion >= 7);
4760     // Cortex M does not support 8 byte atomics, while general Thumb2 does.
4761     if (ArchProfile == llvm::ARM::PK_M) {
4762       MaxAtomicPromoteWidth = 32;
4763       if (ShouldUseInlineAtomic)
4764         MaxAtomicInlineWidth = 32;
4765     }
4766     else {
4767       MaxAtomicPromoteWidth = 64;
4768       if (ShouldUseInlineAtomic)
4769         MaxAtomicInlineWidth = 64;
4770     }
4771   }
4772 
isThumb() const4773   bool isThumb() const {
4774     return (ArchISA == llvm::ARM::IK_THUMB);
4775   }
4776 
supportsThumb() const4777   bool supportsThumb() const {
4778     return CPUAttr.count('T') || ArchVersion >= 6;
4779   }
4780 
supportsThumb2() const4781   bool supportsThumb2() const {
4782     return CPUAttr.equals("6T2") ||
4783            (ArchVersion >= 7 && !CPUAttr.equals("8M_BASE"));
4784   }
4785 
getCPUAttr() const4786   StringRef getCPUAttr() const {
4787     // For most sub-arches, the build attribute CPU name is enough.
4788     // For Cortex variants, it's slightly different.
4789     switch(ArchKind) {
4790     default:
4791       return llvm::ARM::getCPUAttr(ArchKind);
4792     case llvm::ARM::AK_ARMV6M:
4793       return "6M";
4794     case llvm::ARM::AK_ARMV7S:
4795       return "7S";
4796     case llvm::ARM::AK_ARMV7A:
4797       return "7A";
4798     case llvm::ARM::AK_ARMV7R:
4799       return "7R";
4800     case llvm::ARM::AK_ARMV7M:
4801       return "7M";
4802     case llvm::ARM::AK_ARMV7EM:
4803       return "7EM";
4804     case llvm::ARM::AK_ARMV8A:
4805       return "8A";
4806     case llvm::ARM::AK_ARMV8_1A:
4807       return "8_1A";
4808     case llvm::ARM::AK_ARMV8_2A:
4809       return "8_2A";
4810     case llvm::ARM::AK_ARMV8MBaseline:
4811       return "8M_BASE";
4812     case llvm::ARM::AK_ARMV8MMainline:
4813       return "8M_MAIN";
4814     }
4815   }
4816 
getCPUProfile() const4817   StringRef getCPUProfile() const {
4818     switch(ArchProfile) {
4819     case llvm::ARM::PK_A:
4820       return "A";
4821     case llvm::ARM::PK_R:
4822       return "R";
4823     case llvm::ARM::PK_M:
4824       return "M";
4825     default:
4826       return "";
4827     }
4828   }
4829 
4830 public:
ARMTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts,bool IsBigEndian)4831   ARMTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts,
4832                 bool IsBigEndian)
4833       : TargetInfo(Triple), FPMath(FP_Default), IsAAPCS(true), LDREX(0),
4834         HW_FP(0) {
4835     BigEndian = IsBigEndian;
4836 
4837     switch (getTriple().getOS()) {
4838     case llvm::Triple::NetBSD:
4839       PtrDiffType = SignedLong;
4840       break;
4841     default:
4842       PtrDiffType = SignedInt;
4843       break;
4844     }
4845 
4846     // Cache arch related info.
4847     setArchInfo();
4848 
4849     // {} in inline assembly are neon specifiers, not assembly variant
4850     // specifiers.
4851     NoAsmVariants = true;
4852 
4853     // FIXME: This duplicates code from the driver that sets the -target-abi
4854     // option - this code is used if -target-abi isn't passed and should
4855     // be unified in some way.
4856     if (Triple.isOSBinFormatMachO()) {
4857       // The backend is hardwired to assume AAPCS for M-class processors, ensure
4858       // the frontend matches that.
4859       if (Triple.getEnvironment() == llvm::Triple::EABI ||
4860           Triple.getOS() == llvm::Triple::UnknownOS ||
4861           StringRef(CPU).startswith("cortex-m")) {
4862         setABI("aapcs");
4863       } else if (Triple.isWatchABI()) {
4864         setABI("aapcs16");
4865       } else {
4866         setABI("apcs-gnu");
4867       }
4868     } else if (Triple.isOSWindows()) {
4869       // FIXME: this is invalid for WindowsCE
4870       setABI("aapcs");
4871     } else {
4872       // Select the default based on the platform.
4873       switch (Triple.getEnvironment()) {
4874       case llvm::Triple::Android:
4875       case llvm::Triple::GNUEABI:
4876       case llvm::Triple::GNUEABIHF:
4877       case llvm::Triple::MuslEABI:
4878       case llvm::Triple::MuslEABIHF:
4879         setABI("aapcs-linux");
4880         break;
4881       case llvm::Triple::EABIHF:
4882       case llvm::Triple::EABI:
4883         setABI("aapcs");
4884         break;
4885       case llvm::Triple::GNU:
4886         setABI("apcs-gnu");
4887       break;
4888       default:
4889         if (Triple.getOS() == llvm::Triple::NetBSD)
4890           setABI("apcs-gnu");
4891         else
4892           setABI("aapcs");
4893         break;
4894       }
4895     }
4896 
4897     // ARM targets default to using the ARM C++ ABI.
4898     TheCXXABI.set(TargetCXXABI::GenericARM);
4899 
4900     // ARM has atomics up to 8 bytes
4901     setAtomic();
4902 
4903     // Do force alignment of members that follow zero length bitfields.  If
4904     // the alignment of the zero-length bitfield is greater than the member
4905     // that follows it, `bar', `bar' will be aligned as the  type of the
4906     // zero length bitfield.
4907     UseZeroLengthBitfieldAlignment = true;
4908 
4909     if (Triple.getOS() == llvm::Triple::Linux ||
4910         Triple.getOS() == llvm::Triple::UnknownOS)
4911       this->MCountName =
4912           Opts.EABIVersion == "gnu" ? "\01__gnu_mcount_nc" : "\01mcount";
4913   }
4914 
getABI() const4915   StringRef getABI() const override { return ABI; }
4916 
setABI(const std::string & Name)4917   bool setABI(const std::string &Name) override {
4918     ABI = Name;
4919 
4920     // The defaults (above) are for AAPCS, check if we need to change them.
4921     //
4922     // FIXME: We need support for -meabi... we could just mangle it into the
4923     // name.
4924     if (Name == "apcs-gnu" || Name == "aapcs16") {
4925       setABIAPCS(Name == "aapcs16");
4926       return true;
4927     }
4928     if (Name == "aapcs" || Name == "aapcs-vfp" || Name == "aapcs-linux") {
4929       setABIAAPCS();
4930       return true;
4931     }
4932     return false;
4933   }
4934 
4935   // FIXME: This should be based on Arch attributes, not CPU names.
4936   bool
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const4937   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
4938                  StringRef CPU,
4939                  const std::vector<std::string> &FeaturesVec) const override {
4940 
4941     std::vector<const char*> TargetFeatures;
4942     unsigned Arch = llvm::ARM::parseArch(getTriple().getArchName());
4943 
4944     // get default FPU features
4945     unsigned FPUKind = llvm::ARM::getDefaultFPU(CPU, Arch);
4946     llvm::ARM::getFPUFeatures(FPUKind, TargetFeatures);
4947 
4948     // get default Extension features
4949     unsigned Extensions = llvm::ARM::getDefaultExtensions(CPU, Arch);
4950     llvm::ARM::getExtensionFeatures(Extensions, TargetFeatures);
4951 
4952     for (const char *Feature : TargetFeatures)
4953       if (Feature[0] == '+')
4954         Features[Feature+1] = true;
4955 
4956     return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
4957   }
4958 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)4959   bool handleTargetFeatures(std::vector<std::string> &Features,
4960                             DiagnosticsEngine &Diags) override {
4961     FPU = 0;
4962     CRC = 0;
4963     Crypto = 0;
4964     DSP = 0;
4965     Unaligned = 1;
4966     SoftFloat = SoftFloatABI = false;
4967     HWDiv = 0;
4968 
4969     // This does not diagnose illegal cases like having both
4970     // "+vfpv2" and "+vfpv3" or having "+neon" and "+fp-only-sp".
4971     uint32_t HW_FP_remove = 0;
4972     for (const auto &Feature : Features) {
4973       if (Feature == "+soft-float") {
4974         SoftFloat = true;
4975       } else if (Feature == "+soft-float-abi") {
4976         SoftFloatABI = true;
4977       } else if (Feature == "+vfp2") {
4978         FPU |= VFP2FPU;
4979         HW_FP |= HW_FP_SP | HW_FP_DP;
4980       } else if (Feature == "+vfp3") {
4981         FPU |= VFP3FPU;
4982         HW_FP |= HW_FP_SP | HW_FP_DP;
4983       } else if (Feature == "+vfp4") {
4984         FPU |= VFP4FPU;
4985         HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP;
4986       } else if (Feature == "+fp-armv8") {
4987         FPU |= FPARMV8;
4988         HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP;
4989       } else if (Feature == "+neon") {
4990         FPU |= NeonFPU;
4991         HW_FP |= HW_FP_SP | HW_FP_DP;
4992       } else if (Feature == "+hwdiv") {
4993         HWDiv |= HWDivThumb;
4994       } else if (Feature == "+hwdiv-arm") {
4995         HWDiv |= HWDivARM;
4996       } else if (Feature == "+crc") {
4997         CRC = 1;
4998       } else if (Feature == "+crypto") {
4999         Crypto = 1;
5000       } else if (Feature == "+dsp") {
5001         DSP = 1;
5002       } else if (Feature == "+fp-only-sp") {
5003         HW_FP_remove |= HW_FP_DP;
5004       } else if (Feature == "+strict-align") {
5005         Unaligned = 0;
5006       } else if (Feature == "+fp16") {
5007         HW_FP |= HW_FP_HP;
5008       }
5009     }
5010     HW_FP &= ~HW_FP_remove;
5011 
5012     switch (ArchVersion) {
5013     case 6:
5014       if (ArchProfile == llvm::ARM::PK_M)
5015         LDREX = 0;
5016       else if (ArchKind == llvm::ARM::AK_ARMV6K)
5017         LDREX = LDREX_D | LDREX_W | LDREX_H | LDREX_B ;
5018       else
5019         LDREX = LDREX_W;
5020       break;
5021     case 7:
5022       if (ArchProfile == llvm::ARM::PK_M)
5023         LDREX = LDREX_W | LDREX_H | LDREX_B ;
5024       else
5025         LDREX = LDREX_D | LDREX_W | LDREX_H | LDREX_B ;
5026       break;
5027     case 8:
5028       LDREX = LDREX_D | LDREX_W | LDREX_H | LDREX_B ;
5029     }
5030 
5031     if (!(FPU & NeonFPU) && FPMath == FP_Neon) {
5032       Diags.Report(diag::err_target_unsupported_fpmath) << "neon";
5033       return false;
5034     }
5035 
5036     if (FPMath == FP_Neon)
5037       Features.push_back("+neonfp");
5038     else if (FPMath == FP_VFP)
5039       Features.push_back("-neonfp");
5040 
5041     // Remove front-end specific options which the backend handles differently.
5042     auto Feature =
5043         std::find(Features.begin(), Features.end(), "+soft-float-abi");
5044     if (Feature != Features.end())
5045       Features.erase(Feature);
5046 
5047     return true;
5048   }
5049 
hasFeature(StringRef Feature) const5050   bool hasFeature(StringRef Feature) const override {
5051     return llvm::StringSwitch<bool>(Feature)
5052         .Case("arm", true)
5053         .Case("aarch32", true)
5054         .Case("softfloat", SoftFloat)
5055         .Case("thumb", isThumb())
5056         .Case("neon", (FPU & NeonFPU) && !SoftFloat)
5057         .Case("hwdiv", HWDiv & HWDivThumb)
5058         .Case("hwdiv-arm", HWDiv & HWDivARM)
5059         .Default(false);
5060   }
5061 
setCPU(const std::string & Name)5062   bool setCPU(const std::string &Name) override {
5063     if (Name != "generic")
5064       setArchInfo(llvm::ARM::parseCPUArch(Name));
5065 
5066     if (ArchKind == llvm::ARM::AK_INVALID)
5067       return false;
5068     setAtomic();
5069     CPU = Name;
5070     return true;
5071   }
5072 
5073   bool setFPMath(StringRef Name) override;
5074 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5075   void getTargetDefines(const LangOptions &Opts,
5076                         MacroBuilder &Builder) const override {
5077     // Target identification.
5078     Builder.defineMacro("__arm");
5079     Builder.defineMacro("__arm__");
5080     // For bare-metal none-eabi.
5081     if (getTriple().getOS() == llvm::Triple::UnknownOS &&
5082         getTriple().getEnvironment() == llvm::Triple::EABI)
5083       Builder.defineMacro("__ELF__");
5084 
5085     // Target properties.
5086     Builder.defineMacro("__REGISTER_PREFIX__", "");
5087 
5088     // Unfortunately, __ARM_ARCH_7K__ is now more of an ABI descriptor. The CPU
5089     // happens to be Cortex-A7 though, so it should still get __ARM_ARCH_7A__.
5090     if (getTriple().isWatchABI())
5091       Builder.defineMacro("__ARM_ARCH_7K__", "2");
5092 
5093     if (!CPUAttr.empty())
5094       Builder.defineMacro("__ARM_ARCH_" + CPUAttr + "__");
5095 
5096     // ACLE 6.4.1 ARM/Thumb instruction set architecture
5097     // __ARM_ARCH is defined as an integer value indicating the current ARM ISA
5098     Builder.defineMacro("__ARM_ARCH", Twine(ArchVersion));
5099 
5100     if (ArchVersion >= 8) {
5101       // ACLE 6.5.7 Crypto Extension
5102       if (Crypto)
5103         Builder.defineMacro("__ARM_FEATURE_CRYPTO", "1");
5104       // ACLE 6.5.8 CRC32 Extension
5105       if (CRC)
5106         Builder.defineMacro("__ARM_FEATURE_CRC32", "1");
5107       // ACLE 6.5.10 Numeric Maximum and Minimum
5108       Builder.defineMacro("__ARM_FEATURE_NUMERIC_MAXMIN", "1");
5109       // ACLE 6.5.9 Directed Rounding
5110       Builder.defineMacro("__ARM_FEATURE_DIRECTED_ROUNDING", "1");
5111     }
5112 
5113     // __ARM_ARCH_ISA_ARM is defined to 1 if the core supports the ARM ISA.  It
5114     // is not defined for the M-profile.
5115     // NOTE that the default profile is assumed to be 'A'
5116     if (CPUProfile.empty() || ArchProfile != llvm::ARM::PK_M)
5117       Builder.defineMacro("__ARM_ARCH_ISA_ARM", "1");
5118 
5119     // __ARM_ARCH_ISA_THUMB is defined to 1 if the core supports the original
5120     // Thumb ISA (including v6-M and v8-M Baseline).  It is set to 2 if the
5121     // core supports the Thumb-2 ISA as found in the v6T2 architecture and all
5122     // v7 and v8 architectures excluding v8-M Baseline.
5123     if (supportsThumb2())
5124       Builder.defineMacro("__ARM_ARCH_ISA_THUMB", "2");
5125     else if (supportsThumb())
5126       Builder.defineMacro("__ARM_ARCH_ISA_THUMB", "1");
5127 
5128     // __ARM_32BIT_STATE is defined to 1 if code is being generated for a 32-bit
5129     // instruction set such as ARM or Thumb.
5130     Builder.defineMacro("__ARM_32BIT_STATE", "1");
5131 
5132     // ACLE 6.4.2 Architectural Profile (A, R, M or pre-Cortex)
5133 
5134     // __ARM_ARCH_PROFILE is defined as 'A', 'R', 'M' or 'S', or unset.
5135     if (!CPUProfile.empty())
5136       Builder.defineMacro("__ARM_ARCH_PROFILE", "'" + CPUProfile + "'");
5137 
5138     // ACLE 6.4.3 Unaligned access supported in hardware
5139     if (Unaligned)
5140       Builder.defineMacro("__ARM_FEATURE_UNALIGNED", "1");
5141 
5142     // ACLE 6.4.4 LDREX/STREX
5143     if (LDREX)
5144       Builder.defineMacro("__ARM_FEATURE_LDREX", "0x" + llvm::utohexstr(LDREX));
5145 
5146     // ACLE 6.4.5 CLZ
5147     if (ArchVersion == 5 ||
5148        (ArchVersion == 6 && CPUProfile != "M") ||
5149         ArchVersion >  6)
5150       Builder.defineMacro("__ARM_FEATURE_CLZ", "1");
5151 
5152     // ACLE 6.5.1 Hardware Floating Point
5153     if (HW_FP)
5154       Builder.defineMacro("__ARM_FP", "0x" + llvm::utohexstr(HW_FP));
5155 
5156     // ACLE predefines.
5157     Builder.defineMacro("__ARM_ACLE", "200");
5158 
5159     // FP16 support (we currently only support IEEE format).
5160     Builder.defineMacro("__ARM_FP16_FORMAT_IEEE", "1");
5161     Builder.defineMacro("__ARM_FP16_ARGS", "1");
5162 
5163     // ACLE 6.5.3 Fused multiply-accumulate (FMA)
5164     if (ArchVersion >= 7 && (FPU & VFP4FPU))
5165       Builder.defineMacro("__ARM_FEATURE_FMA", "1");
5166 
5167     // Subtarget options.
5168 
5169     // FIXME: It's more complicated than this and we don't really support
5170     // interworking.
5171     // Windows on ARM does not "support" interworking
5172     if (5 <= ArchVersion && ArchVersion <= 8 && !getTriple().isOSWindows())
5173       Builder.defineMacro("__THUMB_INTERWORK__");
5174 
5175     if (ABI == "aapcs" || ABI == "aapcs-linux" || ABI == "aapcs-vfp") {
5176       // Embedded targets on Darwin follow AAPCS, but not EABI.
5177       // Windows on ARM follows AAPCS VFP, but does not conform to EABI.
5178       if (!getTriple().isOSBinFormatMachO() && !getTriple().isOSWindows())
5179         Builder.defineMacro("__ARM_EABI__");
5180       Builder.defineMacro("__ARM_PCS", "1");
5181     }
5182 
5183     if ((!SoftFloat && !SoftFloatABI) || ABI == "aapcs-vfp" ||
5184         ABI == "aapcs16")
5185       Builder.defineMacro("__ARM_PCS_VFP", "1");
5186 
5187     if (SoftFloat)
5188       Builder.defineMacro("__SOFTFP__");
5189 
5190     if (CPU == "xscale")
5191       Builder.defineMacro("__XSCALE__");
5192 
5193     if (isThumb()) {
5194       Builder.defineMacro("__THUMBEL__");
5195       Builder.defineMacro("__thumb__");
5196       if (supportsThumb2())
5197         Builder.defineMacro("__thumb2__");
5198     }
5199 
5200     // ACLE 6.4.9 32-bit SIMD instructions
5201     if (ArchVersion >= 6 && (CPUProfile != "M" || CPUAttr == "7EM"))
5202       Builder.defineMacro("__ARM_FEATURE_SIMD32", "1");
5203 
5204     // ACLE 6.4.10 Hardware Integer Divide
5205     if (((HWDiv & HWDivThumb) && isThumb()) ||
5206         ((HWDiv & HWDivARM) && !isThumb())) {
5207       Builder.defineMacro("__ARM_FEATURE_IDIV", "1");
5208       Builder.defineMacro("__ARM_ARCH_EXT_IDIV__", "1");
5209     }
5210 
5211     // Note, this is always on in gcc, even though it doesn't make sense.
5212     Builder.defineMacro("__APCS_32__");
5213 
5214     if (FPUModeIsVFP((FPUMode) FPU)) {
5215       Builder.defineMacro("__VFP_FP__");
5216       if (FPU & VFP2FPU)
5217         Builder.defineMacro("__ARM_VFPV2__");
5218       if (FPU & VFP3FPU)
5219         Builder.defineMacro("__ARM_VFPV3__");
5220       if (FPU & VFP4FPU)
5221         Builder.defineMacro("__ARM_VFPV4__");
5222     }
5223 
5224     // This only gets set when Neon instructions are actually available, unlike
5225     // the VFP define, hence the soft float and arch check. This is subtly
5226     // different from gcc, we follow the intent which was that it should be set
5227     // when Neon instructions are actually available.
5228     if ((FPU & NeonFPU) && !SoftFloat && ArchVersion >= 7) {
5229       Builder.defineMacro("__ARM_NEON", "1");
5230       Builder.defineMacro("__ARM_NEON__");
5231       // current AArch32 NEON implementations do not support double-precision
5232       // floating-point even when it is present in VFP.
5233       Builder.defineMacro("__ARM_NEON_FP",
5234                           "0x" + llvm::utohexstr(HW_FP & ~HW_FP_DP));
5235     }
5236 
5237     Builder.defineMacro("__ARM_SIZEOF_WCHAR_T",
5238                         Opts.ShortWChar ? "2" : "4");
5239 
5240     Builder.defineMacro("__ARM_SIZEOF_MINIMAL_ENUM",
5241                         Opts.ShortEnums ? "1" : "4");
5242 
5243     if (ArchVersion >= 6 && CPUAttr != "6M" && CPUAttr != "8M_BASE") {
5244       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
5245       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
5246       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
5247       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
5248     }
5249 
5250     // ACLE 6.4.7 DSP instructions
5251     if (DSP) {
5252       Builder.defineMacro("__ARM_FEATURE_DSP", "1");
5253     }
5254 
5255     // ACLE 6.4.8 Saturation instructions
5256     bool SAT = false;
5257     if ((ArchVersion == 6 && CPUProfile != "M") || ArchVersion > 6 ) {
5258       Builder.defineMacro("__ARM_FEATURE_SAT", "1");
5259       SAT = true;
5260     }
5261 
5262     // ACLE 6.4.6 Q (saturation) flag
5263     if (DSP || SAT)
5264       Builder.defineMacro("__ARM_FEATURE_QBIT", "1");
5265 
5266     if (Opts.UnsafeFPMath)
5267       Builder.defineMacro("__ARM_FP_FAST", "1");
5268 
5269     if (ArchKind == llvm::ARM::AK_ARMV8_1A)
5270       Builder.defineMacro("__ARM_FEATURE_QRDMX", "1");
5271   }
5272 
getTargetBuiltins() const5273   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
5274     return llvm::makeArrayRef(BuiltinInfo,
5275                              clang::ARM::LastTSBuiltin-Builtin::FirstTSBuiltin);
5276   }
isCLZForZeroUndef() const5277   bool isCLZForZeroUndef() const override { return false; }
getBuiltinVaListKind() const5278   BuiltinVaListKind getBuiltinVaListKind() const override {
5279     return IsAAPCS
5280                ? AAPCSABIBuiltinVaList
5281                : (getTriple().isWatchABI() ? TargetInfo::CharPtrBuiltinVaList
5282                                            : TargetInfo::VoidPtrBuiltinVaList);
5283   }
5284   ArrayRef<const char *> getGCCRegNames() const override;
5285   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const5286   bool validateAsmConstraint(const char *&Name,
5287                              TargetInfo::ConstraintInfo &Info) const override {
5288     switch (*Name) {
5289     default: break;
5290     case 'l': // r0-r7
5291     case 'h': // r8-r15
5292     case 't': // VFP Floating point register single precision
5293     case 'w': // VFP Floating point register double precision
5294       Info.setAllowsRegister();
5295       return true;
5296     case 'I':
5297     case 'J':
5298     case 'K':
5299     case 'L':
5300     case 'M':
5301       // FIXME
5302       return true;
5303     case 'Q': // A memory address that is a single base register.
5304       Info.setAllowsMemory();
5305       return true;
5306     case 'U': // a memory reference...
5307       switch (Name[1]) {
5308       case 'q': // ...ARMV4 ldrsb
5309       case 'v': // ...VFP load/store (reg+constant offset)
5310       case 'y': // ...iWMMXt load/store
5311       case 't': // address valid for load/store opaque types wider
5312                 // than 128-bits
5313       case 'n': // valid address for Neon doubleword vector load/store
5314       case 'm': // valid address for Neon element and structure load/store
5315       case 's': // valid address for non-offset loads/stores of quad-word
5316                 // values in four ARM registers
5317         Info.setAllowsMemory();
5318         Name++;
5319         return true;
5320       }
5321     }
5322     return false;
5323   }
convertConstraint(const char * & Constraint) const5324   std::string convertConstraint(const char *&Constraint) const override {
5325     std::string R;
5326     switch (*Constraint) {
5327     case 'U':   // Two-character constraint; add "^" hint for later parsing.
5328       R = std::string("^") + std::string(Constraint, 2);
5329       Constraint++;
5330       break;
5331     case 'p': // 'p' should be translated to 'r' by default.
5332       R = std::string("r");
5333       break;
5334     default:
5335       return std::string(1, *Constraint);
5336     }
5337     return R;
5338   }
5339   bool
validateConstraintModifier(StringRef Constraint,char Modifier,unsigned Size,std::string & SuggestedModifier) const5340   validateConstraintModifier(StringRef Constraint, char Modifier, unsigned Size,
5341                              std::string &SuggestedModifier) const override {
5342     bool isOutput = (Constraint[0] == '=');
5343     bool isInOut = (Constraint[0] == '+');
5344 
5345     // Strip off constraint modifiers.
5346     while (Constraint[0] == '=' ||
5347            Constraint[0] == '+' ||
5348            Constraint[0] == '&')
5349       Constraint = Constraint.substr(1);
5350 
5351     switch (Constraint[0]) {
5352     default: break;
5353     case 'r': {
5354       switch (Modifier) {
5355       default:
5356         return (isInOut || isOutput || Size <= 64);
5357       case 'q':
5358         // A register of size 32 cannot fit a vector type.
5359         return false;
5360       }
5361     }
5362     }
5363 
5364     return true;
5365   }
getClobbers() const5366   const char *getClobbers() const override {
5367     // FIXME: Is this really right?
5368     return "";
5369   }
5370 
checkCallingConvention(CallingConv CC) const5371   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
5372     switch (CC) {
5373     case CC_AAPCS:
5374     case CC_AAPCS_VFP:
5375     case CC_Swift:
5376       return CCCR_OK;
5377     default:
5378       return CCCR_Warning;
5379     }
5380   }
5381 
getEHDataRegisterNumber(unsigned RegNo) const5382   int getEHDataRegisterNumber(unsigned RegNo) const override {
5383     if (RegNo == 0) return 0;
5384     if (RegNo == 1) return 1;
5385     return -1;
5386   }
5387 
hasSjLjLowering() const5388   bool hasSjLjLowering() const override {
5389     return true;
5390   }
5391 };
5392 
setFPMath(StringRef Name)5393 bool ARMTargetInfo::setFPMath(StringRef Name) {
5394   if (Name == "neon") {
5395     FPMath = FP_Neon;
5396     return true;
5397   } else if (Name == "vfp" || Name == "vfp2" || Name == "vfp3" ||
5398              Name == "vfp4") {
5399     FPMath = FP_VFP;
5400     return true;
5401   }
5402   return false;
5403 }
5404 
5405 const char * const ARMTargetInfo::GCCRegNames[] = {
5406   // Integer registers
5407   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
5408   "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc",
5409 
5410   // Float registers
5411   "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
5412   "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
5413   "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
5414   "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
5415 
5416   // Double registers
5417   "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
5418   "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
5419   "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
5420   "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
5421 
5422   // Quad registers
5423   "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7",
5424   "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
5425 };
5426 
getGCCRegNames() const5427 ArrayRef<const char *> ARMTargetInfo::getGCCRegNames() const {
5428   return llvm::makeArrayRef(GCCRegNames);
5429 }
5430 
5431 const TargetInfo::GCCRegAlias ARMTargetInfo::GCCRegAliases[] = {
5432   { { "a1" }, "r0" },
5433   { { "a2" }, "r1" },
5434   { { "a3" }, "r2" },
5435   { { "a4" }, "r3" },
5436   { { "v1" }, "r4" },
5437   { { "v2" }, "r5" },
5438   { { "v3" }, "r6" },
5439   { { "v4" }, "r7" },
5440   { { "v5" }, "r8" },
5441   { { "v6", "rfp" }, "r9" },
5442   { { "sl" }, "r10" },
5443   { { "fp" }, "r11" },
5444   { { "ip" }, "r12" },
5445   { { "r13" }, "sp" },
5446   { { "r14" }, "lr" },
5447   { { "r15" }, "pc" },
5448   // The S, D and Q registers overlap, but aren't really aliases; we
5449   // don't want to substitute one of these for a different-sized one.
5450 };
5451 
getGCCRegAliases() const5452 ArrayRef<TargetInfo::GCCRegAlias> ARMTargetInfo::getGCCRegAliases() const {
5453   return llvm::makeArrayRef(GCCRegAliases);
5454 }
5455 
5456 const Builtin::Info ARMTargetInfo::BuiltinInfo[] = {
5457 #define BUILTIN(ID, TYPE, ATTRS) \
5458   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5459 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
5460   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
5461 #include "clang/Basic/BuiltinsNEON.def"
5462 
5463 #define BUILTIN(ID, TYPE, ATTRS) \
5464   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5465 #define LANGBUILTIN(ID, TYPE, ATTRS, LANG) \
5466   { #ID, TYPE, ATTRS, nullptr, LANG, nullptr },
5467 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
5468   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
5469 #include "clang/Basic/BuiltinsARM.def"
5470 };
5471 
5472 class ARMleTargetInfo : public ARMTargetInfo {
5473 public:
ARMleTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5474   ARMleTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
5475       : ARMTargetInfo(Triple, Opts, /*BigEndian=*/false) {}
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5476   void getTargetDefines(const LangOptions &Opts,
5477                         MacroBuilder &Builder) const override {
5478     Builder.defineMacro("__ARMEL__");
5479     ARMTargetInfo::getTargetDefines(Opts, Builder);
5480   }
5481 };
5482 
5483 class ARMbeTargetInfo : public ARMTargetInfo {
5484 public:
ARMbeTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5485   ARMbeTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
5486       : ARMTargetInfo(Triple, Opts, /*BigEndian=*/true) {}
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5487   void getTargetDefines(const LangOptions &Opts,
5488                         MacroBuilder &Builder) const override {
5489     Builder.defineMacro("__ARMEB__");
5490     Builder.defineMacro("__ARM_BIG_ENDIAN");
5491     ARMTargetInfo::getTargetDefines(Opts, Builder);
5492   }
5493 };
5494 
5495 class WindowsARMTargetInfo : public WindowsTargetInfo<ARMleTargetInfo> {
5496   const llvm::Triple Triple;
5497 public:
WindowsARMTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5498   WindowsARMTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
5499       : WindowsTargetInfo<ARMleTargetInfo>(Triple, Opts), Triple(Triple) {
5500     WCharType = UnsignedShort;
5501     SizeType = UnsignedInt;
5502   }
getVisualStudioDefines(const LangOptions & Opts,MacroBuilder & Builder) const5503   void getVisualStudioDefines(const LangOptions &Opts,
5504                               MacroBuilder &Builder) const {
5505     WindowsTargetInfo<ARMleTargetInfo>::getVisualStudioDefines(Opts, Builder);
5506 
5507     // FIXME: this is invalid for WindowsCE
5508     Builder.defineMacro("_M_ARM_NT", "1");
5509     Builder.defineMacro("_M_ARMT", "_M_ARM");
5510     Builder.defineMacro("_M_THUMB", "_M_ARM");
5511 
5512     assert((Triple.getArch() == llvm::Triple::arm ||
5513             Triple.getArch() == llvm::Triple::thumb) &&
5514            "invalid architecture for Windows ARM target info");
5515     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5516     Builder.defineMacro("_M_ARM", Triple.getArchName().substr(Offset));
5517 
5518     // TODO map the complete set of values
5519     // 31: VFPv3 40: VFPv4
5520     Builder.defineMacro("_M_ARM_FP", "31");
5521   }
getBuiltinVaListKind() const5522   BuiltinVaListKind getBuiltinVaListKind() const override {
5523     return TargetInfo::CharPtrBuiltinVaList;
5524   }
checkCallingConvention(CallingConv CC) const5525   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
5526     switch (CC) {
5527     case CC_X86StdCall:
5528     case CC_X86ThisCall:
5529     case CC_X86FastCall:
5530     case CC_X86VectorCall:
5531       return CCCR_Ignore;
5532     case CC_C:
5533       return CCCR_OK;
5534     default:
5535       return CCCR_Warning;
5536     }
5537   }
5538 };
5539 
5540 // Windows ARM + Itanium C++ ABI Target
5541 class ItaniumWindowsARMleTargetInfo : public WindowsARMTargetInfo {
5542 public:
ItaniumWindowsARMleTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5543   ItaniumWindowsARMleTargetInfo(const llvm::Triple &Triple,
5544                                 const TargetOptions &Opts)
5545       : WindowsARMTargetInfo(Triple, Opts) {
5546     TheCXXABI.set(TargetCXXABI::GenericARM);
5547   }
5548 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5549   void getTargetDefines(const LangOptions &Opts,
5550                         MacroBuilder &Builder) const override {
5551     WindowsARMTargetInfo::getTargetDefines(Opts, Builder);
5552 
5553     if (Opts.MSVCCompat)
5554       WindowsARMTargetInfo::getVisualStudioDefines(Opts, Builder);
5555   }
5556 };
5557 
5558 // Windows ARM, MS (C++) ABI
5559 class MicrosoftARMleTargetInfo : public WindowsARMTargetInfo {
5560 public:
MicrosoftARMleTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5561   MicrosoftARMleTargetInfo(const llvm::Triple &Triple,
5562                            const TargetOptions &Opts)
5563       : WindowsARMTargetInfo(Triple, Opts) {
5564     TheCXXABI.set(TargetCXXABI::Microsoft);
5565   }
5566 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5567   void getTargetDefines(const LangOptions &Opts,
5568                         MacroBuilder &Builder) const override {
5569     WindowsARMTargetInfo::getTargetDefines(Opts, Builder);
5570     WindowsARMTargetInfo::getVisualStudioDefines(Opts, Builder);
5571   }
5572 };
5573 
5574 // ARM MinGW target
5575 class MinGWARMTargetInfo : public WindowsARMTargetInfo {
5576 public:
MinGWARMTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5577   MinGWARMTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
5578       : WindowsARMTargetInfo(Triple, Opts) {
5579     TheCXXABI.set(TargetCXXABI::GenericARM);
5580   }
5581 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5582   void getTargetDefines(const LangOptions &Opts,
5583                         MacroBuilder &Builder) const override {
5584     WindowsARMTargetInfo::getTargetDefines(Opts, Builder);
5585     DefineStd(Builder, "WIN32", Opts);
5586     DefineStd(Builder, "WINNT", Opts);
5587     Builder.defineMacro("_ARM_");
5588     addMinGWDefines(Opts, Builder);
5589   }
5590 };
5591 
5592 // ARM Cygwin target
5593 class CygwinARMTargetInfo : public ARMleTargetInfo {
5594 public:
CygwinARMTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5595   CygwinARMTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
5596       : ARMleTargetInfo(Triple, Opts) {
5597     TLSSupported = false;
5598     WCharType = UnsignedShort;
5599     DoubleAlign = LongLongAlign = 64;
5600     resetDataLayout("e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64");
5601   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5602   void getTargetDefines(const LangOptions &Opts,
5603                         MacroBuilder &Builder) const override {
5604     ARMleTargetInfo::getTargetDefines(Opts, Builder);
5605     Builder.defineMacro("_ARM_");
5606     Builder.defineMacro("__CYGWIN__");
5607     Builder.defineMacro("__CYGWIN32__");
5608     DefineStd(Builder, "unix", Opts);
5609     if (Opts.CPlusPlus)
5610       Builder.defineMacro("_GNU_SOURCE");
5611   }
5612 };
5613 
5614 class DarwinARMTargetInfo : public DarwinTargetInfo<ARMleTargetInfo> {
5615 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const5616   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
5617                     MacroBuilder &Builder) const override {
5618     getDarwinDefines(Builder, Opts, Triple, PlatformName, PlatformMinVersion);
5619   }
5620 
5621 public:
DarwinARMTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5622   DarwinARMTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
5623       : DarwinTargetInfo<ARMleTargetInfo>(Triple, Opts) {
5624     HasAlignMac68kSupport = true;
5625     // iOS always has 64-bit atomic instructions.
5626     // FIXME: This should be based off of the target features in
5627     // ARMleTargetInfo.
5628     MaxAtomicInlineWidth = 64;
5629 
5630     if (Triple.isWatchABI()) {
5631       // Darwin on iOS uses a variant of the ARM C++ ABI.
5632       TheCXXABI.set(TargetCXXABI::WatchOS);
5633 
5634       // The 32-bit ABI is silent on what ptrdiff_t should be, but given that
5635       // size_t is long, it's a bit weird for it to be int.
5636       PtrDiffType = SignedLong;
5637 
5638       // BOOL should be a real boolean on the new ABI
5639       UseSignedCharForObjCBool = false;
5640     } else
5641       TheCXXABI.set(TargetCXXABI::iOS);
5642   }
5643 };
5644 
5645 class AArch64TargetInfo : public TargetInfo {
5646   virtual void setDataLayout() = 0;
5647   static const TargetInfo::GCCRegAlias GCCRegAliases[];
5648   static const char *const GCCRegNames[];
5649 
5650   enum FPUModeEnum {
5651     FPUMode,
5652     NeonMode
5653   };
5654 
5655   unsigned FPU;
5656   unsigned CRC;
5657   unsigned Crypto;
5658   unsigned Unaligned;
5659   unsigned V8_1A;
5660 
5661   static const Builtin::Info BuiltinInfo[];
5662 
5663   std::string ABI;
5664 
5665 public:
AArch64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)5666   AArch64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
5667       : TargetInfo(Triple), ABI("aapcs") {
5668     if (getTriple().getOS() == llvm::Triple::NetBSD) {
5669       WCharType = SignedInt;
5670 
5671       // NetBSD apparently prefers consistency across ARM targets to consistency
5672       // across 64-bit targets.
5673       Int64Type = SignedLongLong;
5674       IntMaxType = SignedLongLong;
5675     } else {
5676       WCharType = UnsignedInt;
5677       Int64Type = SignedLong;
5678       IntMaxType = SignedLong;
5679     }
5680 
5681     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
5682     MaxVectorAlign = 128;
5683     MaxAtomicInlineWidth = 128;
5684     MaxAtomicPromoteWidth = 128;
5685 
5686     LongDoubleWidth = LongDoubleAlign = SuitableAlign = 128;
5687     LongDoubleFormat = &llvm::APFloat::IEEEquad;
5688 
5689     // {} in inline assembly are neon specifiers, not assembly variant
5690     // specifiers.
5691     NoAsmVariants = true;
5692 
5693     // AAPCS gives rules for bitfields. 7.1.7 says: "The container type
5694     // contributes to the alignment of the containing aggregate in the same way
5695     // a plain (non bit-field) member of that type would, without exception for
5696     // zero-sized or anonymous bit-fields."
5697     assert(UseBitFieldTypeAlignment && "bitfields affect type alignment");
5698     UseZeroLengthBitfieldAlignment = true;
5699 
5700     // AArch64 targets default to using the ARM C++ ABI.
5701     TheCXXABI.set(TargetCXXABI::GenericAArch64);
5702 
5703     if (Triple.getOS() == llvm::Triple::Linux ||
5704         Triple.getOS() == llvm::Triple::UnknownOS)
5705       this->MCountName = Opts.EABIVersion == "gnu" ? "\01_mcount" : "mcount";
5706   }
5707 
getABI() const5708   StringRef getABI() const override { return ABI; }
setABI(const std::string & Name)5709   bool setABI(const std::string &Name) override {
5710     if (Name != "aapcs" && Name != "darwinpcs")
5711       return false;
5712 
5713     ABI = Name;
5714     return true;
5715   }
5716 
setCPU(const std::string & Name)5717   bool setCPU(const std::string &Name) override {
5718     bool CPUKnown = llvm::StringSwitch<bool>(Name)
5719                         .Case("generic", true)
5720                         .Cases("cortex-a53", "cortex-a57", "cortex-a72",
5721                                "cortex-a35", "exynos-m1", true)
5722                         .Case("cortex-a73", true)
5723                         .Case("cyclone", true)
5724                         .Case("kryo", true)
5725                         .Case("vulcan", true)
5726                         .Default(false);
5727     return CPUKnown;
5728   }
5729 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5730   void getTargetDefines(const LangOptions &Opts,
5731                         MacroBuilder &Builder) const override {
5732     // Target identification.
5733     Builder.defineMacro("__aarch64__");
5734 
5735     // Target properties.
5736     Builder.defineMacro("_LP64");
5737     Builder.defineMacro("__LP64__");
5738 
5739     // ACLE predefines. Many can only have one possible value on v8 AArch64.
5740     Builder.defineMacro("__ARM_ACLE", "200");
5741     Builder.defineMacro("__ARM_ARCH", "8");
5742     Builder.defineMacro("__ARM_ARCH_PROFILE", "'A'");
5743 
5744     Builder.defineMacro("__ARM_64BIT_STATE", "1");
5745     Builder.defineMacro("__ARM_PCS_AAPCS64", "1");
5746     Builder.defineMacro("__ARM_ARCH_ISA_A64", "1");
5747 
5748     Builder.defineMacro("__ARM_FEATURE_CLZ", "1");
5749     Builder.defineMacro("__ARM_FEATURE_FMA", "1");
5750     Builder.defineMacro("__ARM_FEATURE_LDREX", "0xF");
5751     Builder.defineMacro("__ARM_FEATURE_IDIV", "1"); // As specified in ACLE
5752     Builder.defineMacro("__ARM_FEATURE_DIV");  // For backwards compatibility
5753     Builder.defineMacro("__ARM_FEATURE_NUMERIC_MAXMIN", "1");
5754     Builder.defineMacro("__ARM_FEATURE_DIRECTED_ROUNDING", "1");
5755 
5756     Builder.defineMacro("__ARM_ALIGN_MAX_STACK_PWR", "4");
5757 
5758     // 0xe implies support for half, single and double precision operations.
5759     Builder.defineMacro("__ARM_FP", "0xE");
5760 
5761     // PCS specifies this for SysV variants, which is all we support. Other ABIs
5762     // may choose __ARM_FP16_FORMAT_ALTERNATIVE.
5763     Builder.defineMacro("__ARM_FP16_FORMAT_IEEE", "1");
5764     Builder.defineMacro("__ARM_FP16_ARGS", "1");
5765 
5766     if (Opts.UnsafeFPMath)
5767       Builder.defineMacro("__ARM_FP_FAST", "1");
5768 
5769     Builder.defineMacro("__ARM_SIZEOF_WCHAR_T", Opts.ShortWChar ? "2" : "4");
5770 
5771     Builder.defineMacro("__ARM_SIZEOF_MINIMAL_ENUM",
5772                         Opts.ShortEnums ? "1" : "4");
5773 
5774     if (FPU == NeonMode) {
5775       Builder.defineMacro("__ARM_NEON", "1");
5776       // 64-bit NEON supports half, single and double precision operations.
5777       Builder.defineMacro("__ARM_NEON_FP", "0xE");
5778     }
5779 
5780     if (CRC)
5781       Builder.defineMacro("__ARM_FEATURE_CRC32", "1");
5782 
5783     if (Crypto)
5784       Builder.defineMacro("__ARM_FEATURE_CRYPTO", "1");
5785 
5786     if (Unaligned)
5787       Builder.defineMacro("__ARM_FEATURE_UNALIGNED", "1");
5788 
5789     if (V8_1A)
5790       Builder.defineMacro("__ARM_FEATURE_QRDMX", "1");
5791 
5792     // All of the __sync_(bool|val)_compare_and_swap_(1|2|4|8) builtins work.
5793     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
5794     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
5795     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
5796     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
5797   }
5798 
getTargetBuiltins() const5799   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
5800     return llvm::makeArrayRef(BuiltinInfo,
5801                        clang::AArch64::LastTSBuiltin - Builtin::FirstTSBuiltin);
5802   }
5803 
hasFeature(StringRef Feature) const5804   bool hasFeature(StringRef Feature) const override {
5805     return Feature == "aarch64" ||
5806       Feature == "arm64" ||
5807       Feature == "arm" ||
5808       (Feature == "neon" && FPU == NeonMode);
5809   }
5810 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)5811   bool handleTargetFeatures(std::vector<std::string> &Features,
5812                             DiagnosticsEngine &Diags) override {
5813     FPU = FPUMode;
5814     CRC = 0;
5815     Crypto = 0;
5816     Unaligned = 1;
5817     V8_1A = 0;
5818 
5819     for (const auto &Feature : Features) {
5820       if (Feature == "+neon")
5821         FPU = NeonMode;
5822       if (Feature == "+crc")
5823         CRC = 1;
5824       if (Feature == "+crypto")
5825         Crypto = 1;
5826       if (Feature == "+strict-align")
5827         Unaligned = 0;
5828       if (Feature == "+v8.1a")
5829         V8_1A = 1;
5830     }
5831 
5832     setDataLayout();
5833 
5834     return true;
5835   }
5836 
checkCallingConvention(CallingConv CC) const5837   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
5838     switch (CC) {
5839     case CC_C:
5840     case CC_Swift:
5841     case CC_PreserveMost:
5842     case CC_PreserveAll:
5843       return CCCR_OK;
5844     default:
5845       return CCCR_Warning;
5846     }
5847   }
5848 
isCLZForZeroUndef() const5849   bool isCLZForZeroUndef() const override { return false; }
5850 
getBuiltinVaListKind() const5851   BuiltinVaListKind getBuiltinVaListKind() const override {
5852     return TargetInfo::AArch64ABIBuiltinVaList;
5853   }
5854 
5855   ArrayRef<const char *> getGCCRegNames() const override;
5856   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
5857 
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const5858   bool validateAsmConstraint(const char *&Name,
5859                              TargetInfo::ConstraintInfo &Info) const override {
5860     switch (*Name) {
5861     default:
5862       return false;
5863     case 'w': // Floating point and SIMD registers (V0-V31)
5864       Info.setAllowsRegister();
5865       return true;
5866     case 'I': // Constant that can be used with an ADD instruction
5867     case 'J': // Constant that can be used with a SUB instruction
5868     case 'K': // Constant that can be used with a 32-bit logical instruction
5869     case 'L': // Constant that can be used with a 64-bit logical instruction
5870     case 'M': // Constant that can be used as a 32-bit MOV immediate
5871     case 'N': // Constant that can be used as a 64-bit MOV immediate
5872     case 'Y': // Floating point constant zero
5873     case 'Z': // Integer constant zero
5874       return true;
5875     case 'Q': // A memory reference with base register and no offset
5876       Info.setAllowsMemory();
5877       return true;
5878     case 'S': // A symbolic address
5879       Info.setAllowsRegister();
5880       return true;
5881     case 'U':
5882       // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes.
5883       // Utf: A memory address suitable for ldp/stp in TF mode.
5884       // Usa: An absolute symbolic address.
5885       // Ush: The high part (bits 32:12) of a pc-relative symbolic address.
5886       llvm_unreachable("FIXME: Unimplemented support for U* constraints.");
5887     case 'z': // Zero register, wzr or xzr
5888       Info.setAllowsRegister();
5889       return true;
5890     case 'x': // Floating point and SIMD registers (V0-V15)
5891       Info.setAllowsRegister();
5892       return true;
5893     }
5894     return false;
5895   }
5896 
5897   bool
validateConstraintModifier(StringRef Constraint,char Modifier,unsigned Size,std::string & SuggestedModifier) const5898   validateConstraintModifier(StringRef Constraint, char Modifier, unsigned Size,
5899                              std::string &SuggestedModifier) const override {
5900     // Strip off constraint modifiers.
5901     while (Constraint[0] == '=' || Constraint[0] == '+' || Constraint[0] == '&')
5902       Constraint = Constraint.substr(1);
5903 
5904     switch (Constraint[0]) {
5905     default:
5906       return true;
5907     case 'z':
5908     case 'r': {
5909       switch (Modifier) {
5910       case 'x':
5911       case 'w':
5912         // For now assume that the person knows what they're
5913         // doing with the modifier.
5914         return true;
5915       default:
5916         // By default an 'r' constraint will be in the 'x'
5917         // registers.
5918         if (Size == 64)
5919           return true;
5920 
5921         SuggestedModifier = "w";
5922         return false;
5923       }
5924     }
5925     }
5926   }
5927 
getClobbers() const5928   const char *getClobbers() const override { return ""; }
5929 
getEHDataRegisterNumber(unsigned RegNo) const5930   int getEHDataRegisterNumber(unsigned RegNo) const override {
5931     if (RegNo == 0)
5932       return 0;
5933     if (RegNo == 1)
5934       return 1;
5935     return -1;
5936   }
5937 };
5938 
5939 const char *const AArch64TargetInfo::GCCRegNames[] = {
5940   // 32-bit Integer registers
5941   "w0",  "w1",  "w2",  "w3",  "w4",  "w5",  "w6",  "w7",  "w8",  "w9",  "w10",
5942   "w11", "w12", "w13", "w14", "w15", "w16", "w17", "w18", "w19", "w20", "w21",
5943   "w22", "w23", "w24", "w25", "w26", "w27", "w28", "w29", "w30", "wsp",
5944 
5945   // 64-bit Integer registers
5946   "x0",  "x1",  "x2",  "x3",  "x4",  "x5",  "x6",  "x7",  "x8",  "x9",  "x10",
5947   "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "x19", "x20", "x21",
5948   "x22", "x23", "x24", "x25", "x26", "x27", "x28", "fp",  "lr",  "sp",
5949 
5950   // 32-bit floating point regsisters
5951   "s0",  "s1",  "s2",  "s3",  "s4",  "s5",  "s6",  "s7",  "s8",  "s9",  "s10",
5952   "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21",
5953   "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
5954 
5955   // 64-bit floating point regsisters
5956   "d0",  "d1",  "d2",  "d3",  "d4",  "d5",  "d6",  "d7",  "d8",  "d9",  "d10",
5957   "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21",
5958   "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
5959 
5960   // Vector registers
5961   "v0",  "v1",  "v2",  "v3",  "v4",  "v5",  "v6",  "v7",  "v8",  "v9",  "v10",
5962   "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21",
5963   "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
5964 };
5965 
getGCCRegNames() const5966 ArrayRef<const char *> AArch64TargetInfo::getGCCRegNames() const {
5967   return llvm::makeArrayRef(GCCRegNames);
5968 }
5969 
5970 const TargetInfo::GCCRegAlias AArch64TargetInfo::GCCRegAliases[] = {
5971   { { "w31" }, "wsp" },
5972   { { "x29" }, "fp" },
5973   { { "x30" }, "lr" },
5974   { { "x31" }, "sp" },
5975   // The S/D/Q and W/X registers overlap, but aren't really aliases; we
5976   // don't want to substitute one of these for a different-sized one.
5977 };
5978 
getGCCRegAliases() const5979 ArrayRef<TargetInfo::GCCRegAlias> AArch64TargetInfo::getGCCRegAliases() const {
5980   return llvm::makeArrayRef(GCCRegAliases);
5981 }
5982 
5983 const Builtin::Info AArch64TargetInfo::BuiltinInfo[] = {
5984 #define BUILTIN(ID, TYPE, ATTRS)                                               \
5985   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5986 #include "clang/Basic/BuiltinsNEON.def"
5987 
5988 #define BUILTIN(ID, TYPE, ATTRS)                                               \
5989   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5990 #include "clang/Basic/BuiltinsAArch64.def"
5991 };
5992 
5993 class AArch64leTargetInfo : public AArch64TargetInfo {
setDataLayout()5994   void setDataLayout() override {
5995     if (getTriple().isOSBinFormatMachO())
5996       resetDataLayout("e-m:o-i64:64-i128:128-n32:64-S128");
5997     else
5998       resetDataLayout("e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128");
5999   }
6000 
6001 public:
AArch64leTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)6002   AArch64leTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
6003       : AArch64TargetInfo(Triple, Opts) {
6004     BigEndian = false;
6005   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6006   void getTargetDefines(const LangOptions &Opts,
6007                         MacroBuilder &Builder) const override {
6008     Builder.defineMacro("__AARCH64EL__");
6009     AArch64TargetInfo::getTargetDefines(Opts, Builder);
6010   }
6011 };
6012 
6013 class AArch64beTargetInfo : public AArch64TargetInfo {
setDataLayout()6014   void setDataLayout() override {
6015     assert(!getTriple().isOSBinFormatMachO());
6016     resetDataLayout("E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128");
6017   }
6018 
6019 public:
AArch64beTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)6020   AArch64beTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
6021       : AArch64TargetInfo(Triple, Opts) {}
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6022   void getTargetDefines(const LangOptions &Opts,
6023                         MacroBuilder &Builder) const override {
6024     Builder.defineMacro("__AARCH64EB__");
6025     Builder.defineMacro("__AARCH_BIG_ENDIAN");
6026     Builder.defineMacro("__ARM_BIG_ENDIAN");
6027     AArch64TargetInfo::getTargetDefines(Opts, Builder);
6028   }
6029 };
6030 
6031 class DarwinAArch64TargetInfo : public DarwinTargetInfo<AArch64leTargetInfo> {
6032 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const6033   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
6034                     MacroBuilder &Builder) const override {
6035     Builder.defineMacro("__AARCH64_SIMD__");
6036     Builder.defineMacro("__ARM64_ARCH_8__");
6037     Builder.defineMacro("__ARM_NEON__");
6038     Builder.defineMacro("__LITTLE_ENDIAN__");
6039     Builder.defineMacro("__REGISTER_PREFIX__", "");
6040     Builder.defineMacro("__arm64", "1");
6041     Builder.defineMacro("__arm64__", "1");
6042 
6043     getDarwinDefines(Builder, Opts, Triple, PlatformName, PlatformMinVersion);
6044   }
6045 
6046 public:
DarwinAArch64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)6047   DarwinAArch64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
6048       : DarwinTargetInfo<AArch64leTargetInfo>(Triple, Opts) {
6049     Int64Type = SignedLongLong;
6050     WCharType = SignedInt;
6051     UseSignedCharForObjCBool = false;
6052 
6053     LongDoubleWidth = LongDoubleAlign = SuitableAlign = 64;
6054     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
6055 
6056     TheCXXABI.set(TargetCXXABI::iOS64);
6057   }
6058 
getBuiltinVaListKind() const6059   BuiltinVaListKind getBuiltinVaListKind() const override {
6060     return TargetInfo::CharPtrBuiltinVaList;
6061   }
6062 };
6063 
6064 // Hexagon abstract base class
6065 class HexagonTargetInfo : public TargetInfo {
6066   static const Builtin::Info BuiltinInfo[];
6067   static const char * const GCCRegNames[];
6068   static const TargetInfo::GCCRegAlias GCCRegAliases[];
6069   std::string CPU;
6070   bool HasHVX, HasHVXDouble;
6071 
6072 public:
HexagonTargetInfo(const llvm::Triple & Triple,const TargetOptions &)6073   HexagonTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
6074       : TargetInfo(Triple) {
6075     BigEndian = false;
6076     // Specify the vector alignment explicitly. For v512x1, the calculated
6077     // alignment would be 512*alignment(i1), which is 512 bytes, instead of
6078     // the required minimum of 64 bytes.
6079     resetDataLayout("e-m:e-p:32:32:32-a:0-n16:32-"
6080         "i64:64:64-i32:32:32-i16:16:16-i1:8:8-f32:32:32-f64:64:64-"
6081         "v32:32:32-v64:64:64-v512:512:512-v1024:1024:1024-v2048:2048:2048");
6082     SizeType    = UnsignedInt;
6083     PtrDiffType = SignedInt;
6084     IntPtrType  = SignedInt;
6085 
6086     // {} in inline assembly are packet specifiers, not assembly variant
6087     // specifiers.
6088     NoAsmVariants = true;
6089 
6090     LargeArrayMinWidth = 64;
6091     LargeArrayAlign = 64;
6092     UseBitFieldTypeAlignment = true;
6093     ZeroLengthBitfieldBoundary = 32;
6094     HasHVX = HasHVXDouble = false;
6095   }
6096 
getTargetBuiltins() const6097   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
6098     return llvm::makeArrayRef(BuiltinInfo,
6099                          clang::Hexagon::LastTSBuiltin-Builtin::FirstTSBuiltin);
6100   }
6101 
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const6102   bool validateAsmConstraint(const char *&Name,
6103                              TargetInfo::ConstraintInfo &Info) const override {
6104     switch (*Name) {
6105       case 'v':
6106       case 'q':
6107         if (HasHVX) {
6108           Info.setAllowsRegister();
6109           return true;
6110         }
6111         break;
6112       case 's':
6113         // Relocatable constant.
6114         return true;
6115     }
6116     return false;
6117   }
6118 
6119   void getTargetDefines(const LangOptions &Opts,
6120                         MacroBuilder &Builder) const override;
6121 
isCLZForZeroUndef() const6122   bool isCLZForZeroUndef() const override { return false; }
6123 
hasFeature(StringRef Feature) const6124   bool hasFeature(StringRef Feature) const override {
6125     return llvm::StringSwitch<bool>(Feature)
6126       .Case("hexagon", true)
6127       .Case("hvx", HasHVX)
6128       .Case("hvx-double", HasHVXDouble)
6129       .Default(false);
6130   }
6131 
6132   bool initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
6133         StringRef CPU, const std::vector<std::string> &FeaturesVec)
6134         const override;
6135 
6136   bool handleTargetFeatures(std::vector<std::string> &Features,
6137                             DiagnosticsEngine &Diags) override;
6138 
getBuiltinVaListKind() const6139   BuiltinVaListKind getBuiltinVaListKind() const override {
6140     return TargetInfo::CharPtrBuiltinVaList;
6141   }
6142   ArrayRef<const char *> getGCCRegNames() const override;
6143   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
getClobbers() const6144   const char *getClobbers() const override {
6145     return "";
6146   }
6147 
getHexagonCPUSuffix(StringRef Name)6148   static const char *getHexagonCPUSuffix(StringRef Name) {
6149     return llvm::StringSwitch<const char*>(Name)
6150       .Case("hexagonv4", "4")
6151       .Case("hexagonv5", "5")
6152       .Case("hexagonv55", "55")
6153       .Case("hexagonv60", "60")
6154       .Default(nullptr);
6155   }
6156 
setCPU(const std::string & Name)6157   bool setCPU(const std::string &Name) override {
6158     if (!getHexagonCPUSuffix(Name))
6159       return false;
6160     CPU = Name;
6161     return true;
6162   }
6163 
getEHDataRegisterNumber(unsigned RegNo) const6164   int getEHDataRegisterNumber(unsigned RegNo) const override {
6165     return RegNo < 2 ? RegNo : -1;
6166   }
6167 };
6168 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6169 void HexagonTargetInfo::getTargetDefines(const LangOptions &Opts,
6170                                          MacroBuilder &Builder) const {
6171   Builder.defineMacro("__qdsp6__", "1");
6172   Builder.defineMacro("__hexagon__", "1");
6173 
6174   if (CPU == "hexagonv4") {
6175     Builder.defineMacro("__HEXAGON_V4__");
6176     Builder.defineMacro("__HEXAGON_ARCH__", "4");
6177     if (Opts.HexagonQdsp6Compat) {
6178       Builder.defineMacro("__QDSP6_V4__");
6179       Builder.defineMacro("__QDSP6_ARCH__", "4");
6180     }
6181   } else if (CPU == "hexagonv5") {
6182     Builder.defineMacro("__HEXAGON_V5__");
6183     Builder.defineMacro("__HEXAGON_ARCH__", "5");
6184     if(Opts.HexagonQdsp6Compat) {
6185       Builder.defineMacro("__QDSP6_V5__");
6186       Builder.defineMacro("__QDSP6_ARCH__", "5");
6187     }
6188   } else if (CPU == "hexagonv55") {
6189     Builder.defineMacro("__HEXAGON_V55__");
6190     Builder.defineMacro("__HEXAGON_ARCH__", "55");
6191     Builder.defineMacro("__QDSP6_V55__");
6192     Builder.defineMacro("__QDSP6_ARCH__", "55");
6193   } else if (CPU == "hexagonv60") {
6194     Builder.defineMacro("__HEXAGON_V60__");
6195     Builder.defineMacro("__HEXAGON_ARCH__", "60");
6196     Builder.defineMacro("__QDSP6_V60__");
6197     Builder.defineMacro("__QDSP6_ARCH__", "60");
6198   }
6199 
6200   if (hasFeature("hvx")) {
6201     Builder.defineMacro("__HVX__");
6202     if (hasFeature("hvx-double"))
6203       Builder.defineMacro("__HVXDBL__");
6204   }
6205 }
6206 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)6207 bool HexagonTargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
6208                                              DiagnosticsEngine &Diags) {
6209   for (auto &F : Features) {
6210     if (F == "+hvx")
6211       HasHVX = true;
6212     else if (F == "-hvx")
6213       HasHVX = HasHVXDouble = false;
6214     else if (F == "+hvx-double")
6215       HasHVX = HasHVXDouble = true;
6216     else if (F == "-hvx-double")
6217       HasHVXDouble = false;
6218   }
6219   return true;
6220 }
6221 
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const6222 bool HexagonTargetInfo::initFeatureMap(llvm::StringMap<bool> &Features,
6223       DiagnosticsEngine &Diags, StringRef CPU,
6224       const std::vector<std::string> &FeaturesVec) const {
6225   // Default for v60: -hvx, -hvx-double.
6226   Features["hvx"] = false;
6227   Features["hvx-double"] = false;
6228 
6229   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
6230 }
6231 
6232 
6233 const char *const HexagonTargetInfo::GCCRegNames[] = {
6234   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
6235   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
6236   "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
6237   "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
6238   "p0", "p1", "p2", "p3",
6239   "sa0", "lc0", "sa1", "lc1", "m0", "m1", "usr", "ugp"
6240 };
6241 
getGCCRegNames() const6242 ArrayRef<const char*> HexagonTargetInfo::getGCCRegNames() const {
6243   return llvm::makeArrayRef(GCCRegNames);
6244 }
6245 
6246 const TargetInfo::GCCRegAlias HexagonTargetInfo::GCCRegAliases[] = {
6247   { { "sp" }, "r29" },
6248   { { "fp" }, "r30" },
6249   { { "lr" }, "r31" },
6250 };
6251 
getGCCRegAliases() const6252 ArrayRef<TargetInfo::GCCRegAlias> HexagonTargetInfo::getGCCRegAliases() const {
6253   return llvm::makeArrayRef(GCCRegAliases);
6254 }
6255 
6256 
6257 const Builtin::Info HexagonTargetInfo::BuiltinInfo[] = {
6258 #define BUILTIN(ID, TYPE, ATTRS) \
6259   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
6260 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
6261   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
6262 #include "clang/Basic/BuiltinsHexagon.def"
6263 };
6264 
6265 class LanaiTargetInfo : public TargetInfo {
6266   // Class for Lanai (32-bit).
6267   // The CPU profiles supported by the Lanai backend
6268   enum CPUKind {
6269     CK_NONE,
6270     CK_V11,
6271   } CPU;
6272 
6273   static const TargetInfo::GCCRegAlias GCCRegAliases[];
6274   static const char *const GCCRegNames[];
6275 
6276 public:
LanaiTargetInfo(const llvm::Triple & Triple,const TargetOptions &)6277   LanaiTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
6278       : TargetInfo(Triple) {
6279     // Description string has to be kept in sync with backend.
6280     resetDataLayout("E"        // Big endian
6281                     "-m:e"     // ELF name manging
6282                     "-p:32:32" // 32 bit pointers, 32 bit aligned
6283                     "-i64:64"  // 64 bit integers, 64 bit aligned
6284                     "-a:0:32"  // 32 bit alignment of objects of aggregate type
6285                     "-n32"     // 32 bit native integer width
6286                     "-S64"     // 64 bit natural stack alignment
6287                     );
6288 
6289     // Setting RegParmMax equal to what mregparm was set to in the old
6290     // toolchain
6291     RegParmMax = 4;
6292 
6293     // Set the default CPU to V11
6294     CPU = CK_V11;
6295 
6296     // Temporary approach to make everything at least word-aligned and allow for
6297     // safely casting between pointers with different alignment requirements.
6298     // TODO: Remove this when there are no more cast align warnings on the
6299     // firmware.
6300     MinGlobalAlign = 32;
6301   }
6302 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6303   void getTargetDefines(const LangOptions &Opts,
6304                         MacroBuilder &Builder) const override {
6305     // Define __lanai__ when building for target lanai.
6306     Builder.defineMacro("__lanai__");
6307 
6308     // Set define for the CPU specified.
6309     switch (CPU) {
6310     case CK_V11:
6311       Builder.defineMacro("__LANAI_V11__");
6312       break;
6313     case CK_NONE:
6314       llvm_unreachable("Unhandled target CPU");
6315     }
6316   }
6317 
setCPU(const std::string & Name)6318   bool setCPU(const std::string &Name) override {
6319     CPU = llvm::StringSwitch<CPUKind>(Name)
6320               .Case("v11", CK_V11)
6321               .Default(CK_NONE);
6322 
6323     return CPU != CK_NONE;
6324   }
6325 
hasFeature(StringRef Feature) const6326   bool hasFeature(StringRef Feature) const override {
6327     return llvm::StringSwitch<bool>(Feature).Case("lanai", true).Default(false);
6328   }
6329 
6330   ArrayRef<const char *> getGCCRegNames() const override;
6331 
6332   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
6333 
getBuiltinVaListKind() const6334   BuiltinVaListKind getBuiltinVaListKind() const override {
6335     return TargetInfo::VoidPtrBuiltinVaList;
6336   }
6337 
getTargetBuiltins() const6338   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
6339 
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const6340   bool validateAsmConstraint(const char *&Name,
6341                              TargetInfo::ConstraintInfo &info) const override {
6342     return false;
6343   }
6344 
getClobbers() const6345   const char *getClobbers() const override { return ""; }
6346 };
6347 
6348 const char *const LanaiTargetInfo::GCCRegNames[] = {
6349     "r0",  "r1",  "r2",  "r3",  "r4",  "r5",  "r6",  "r7",  "r8",  "r9",  "r10",
6350     "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21",
6351     "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31"};
6352 
getGCCRegNames() const6353 ArrayRef<const char *> LanaiTargetInfo::getGCCRegNames() const {
6354   return llvm::makeArrayRef(GCCRegNames);
6355 }
6356 
6357 const TargetInfo::GCCRegAlias LanaiTargetInfo::GCCRegAliases[] = {
6358     {{"pc"}, "r2"},
6359     {{"sp"}, "r4"},
6360     {{"fp"}, "r5"},
6361     {{"rv"}, "r8"},
6362     {{"rr1"}, "r10"},
6363     {{"rr2"}, "r11"},
6364     {{"rca"}, "r15"},
6365 };
6366 
getGCCRegAliases() const6367 ArrayRef<TargetInfo::GCCRegAlias> LanaiTargetInfo::getGCCRegAliases() const {
6368   return llvm::makeArrayRef(GCCRegAliases);
6369 }
6370 
6371 // Shared base class for SPARC v8 (32-bit) and SPARC v9 (64-bit).
6372 class SparcTargetInfo : public TargetInfo {
6373   static const TargetInfo::GCCRegAlias GCCRegAliases[];
6374   static const char * const GCCRegNames[];
6375   bool SoftFloat;
6376 public:
SparcTargetInfo(const llvm::Triple & Triple,const TargetOptions &)6377   SparcTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
6378       : TargetInfo(Triple), SoftFloat(false) {}
6379 
getEHDataRegisterNumber(unsigned RegNo) const6380   int getEHDataRegisterNumber(unsigned RegNo) const override {
6381     if (RegNo == 0) return 24;
6382     if (RegNo == 1) return 25;
6383     return -1;
6384   }
6385 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)6386   bool handleTargetFeatures(std::vector<std::string> &Features,
6387                             DiagnosticsEngine &Diags) override {
6388     // Check if software floating point is enabled
6389     auto Feature = std::find(Features.begin(), Features.end(), "+soft-float");
6390     if (Feature != Features.end()) {
6391       SoftFloat = true;
6392     }
6393     return true;
6394   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6395   void getTargetDefines(const LangOptions &Opts,
6396                         MacroBuilder &Builder) const override {
6397     DefineStd(Builder, "sparc", Opts);
6398     Builder.defineMacro("__REGISTER_PREFIX__", "");
6399 
6400     if (SoftFloat)
6401       Builder.defineMacro("SOFT_FLOAT", "1");
6402   }
6403 
hasFeature(StringRef Feature) const6404   bool hasFeature(StringRef Feature) const override {
6405     return llvm::StringSwitch<bool>(Feature)
6406              .Case("softfloat", SoftFloat)
6407              .Case("sparc", true)
6408              .Default(false);
6409   }
6410 
hasSjLjLowering() const6411   bool hasSjLjLowering() const override {
6412     return true;
6413   }
6414 
getTargetBuiltins() const6415   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
6416     // FIXME: Implement!
6417     return None;
6418   }
getBuiltinVaListKind() const6419   BuiltinVaListKind getBuiltinVaListKind() const override {
6420     return TargetInfo::VoidPtrBuiltinVaList;
6421   }
6422   ArrayRef<const char *> getGCCRegNames() const override;
6423   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const6424   bool validateAsmConstraint(const char *&Name,
6425                              TargetInfo::ConstraintInfo &info) const override {
6426     // FIXME: Implement!
6427     switch (*Name) {
6428     case 'I': // Signed 13-bit constant
6429     case 'J': // Zero
6430     case 'K': // 32-bit constant with the low 12 bits clear
6431     case 'L': // A constant in the range supported by movcc (11-bit signed imm)
6432     case 'M': // A constant in the range supported by movrcc (19-bit signed imm)
6433     case 'N': // Same as 'K' but zext (required for SIMode)
6434     case 'O': // The constant 4096
6435       return true;
6436     }
6437     return false;
6438   }
getClobbers() const6439   const char *getClobbers() const override {
6440     // FIXME: Implement!
6441     return "";
6442   }
6443 
6444   // No Sparc V7 for now, the backend doesn't support it anyway.
6445   enum CPUKind {
6446     CK_GENERIC,
6447     CK_V8,
6448     CK_SUPERSPARC,
6449     CK_SPARCLITE,
6450     CK_F934,
6451     CK_HYPERSPARC,
6452     CK_SPARCLITE86X,
6453     CK_SPARCLET,
6454     CK_TSC701,
6455     CK_V9,
6456     CK_ULTRASPARC,
6457     CK_ULTRASPARC3,
6458     CK_NIAGARA,
6459     CK_NIAGARA2,
6460     CK_NIAGARA3,
6461     CK_NIAGARA4,
6462     CK_MYRIAD2_1,
6463     CK_MYRIAD2_2,
6464     CK_LEON2,
6465     CK_LEON2_AT697E,
6466     CK_LEON2_AT697F,
6467     CK_LEON3,
6468     CK_LEON3_UT699,
6469     CK_LEON3_GR712RC,
6470     CK_LEON4,
6471     CK_LEON4_GR740
6472   } CPU = CK_GENERIC;
6473 
6474   enum CPUGeneration {
6475     CG_V8,
6476     CG_V9,
6477   };
6478 
getCPUGeneration(CPUKind Kind) const6479   CPUGeneration getCPUGeneration(CPUKind Kind) const {
6480     switch (Kind) {
6481     case CK_GENERIC:
6482     case CK_V8:
6483     case CK_SUPERSPARC:
6484     case CK_SPARCLITE:
6485     case CK_F934:
6486     case CK_HYPERSPARC:
6487     case CK_SPARCLITE86X:
6488     case CK_SPARCLET:
6489     case CK_TSC701:
6490     case CK_MYRIAD2_1:
6491     case CK_MYRIAD2_2:
6492     case CK_LEON2:
6493     case CK_LEON2_AT697E:
6494     case CK_LEON2_AT697F:
6495     case CK_LEON3:
6496     case CK_LEON3_UT699:
6497     case CK_LEON3_GR712RC:
6498     case CK_LEON4:
6499     case CK_LEON4_GR740:
6500       return CG_V8;
6501     case CK_V9:
6502     case CK_ULTRASPARC:
6503     case CK_ULTRASPARC3:
6504     case CK_NIAGARA:
6505     case CK_NIAGARA2:
6506     case CK_NIAGARA3:
6507     case CK_NIAGARA4:
6508       return CG_V9;
6509     }
6510     llvm_unreachable("Unexpected CPU kind");
6511   }
6512 
getCPUKind(StringRef Name) const6513   CPUKind getCPUKind(StringRef Name) const {
6514     return llvm::StringSwitch<CPUKind>(Name)
6515         .Case("v8", CK_V8)
6516         .Case("supersparc", CK_SUPERSPARC)
6517         .Case("sparclite", CK_SPARCLITE)
6518         .Case("f934", CK_F934)
6519         .Case("hypersparc", CK_HYPERSPARC)
6520         .Case("sparclite86x", CK_SPARCLITE86X)
6521         .Case("sparclet", CK_SPARCLET)
6522         .Case("tsc701", CK_TSC701)
6523         .Case("v9", CK_V9)
6524         .Case("ultrasparc", CK_ULTRASPARC)
6525         .Case("ultrasparc3", CK_ULTRASPARC3)
6526         .Case("niagara", CK_NIAGARA)
6527         .Case("niagara2", CK_NIAGARA2)
6528         .Case("niagara3", CK_NIAGARA3)
6529         .Case("niagara4", CK_NIAGARA4)
6530         .Case("myriad2", CK_MYRIAD2_1)
6531         .Case("myriad2.1", CK_MYRIAD2_1)
6532         .Case("myriad2.2", CK_MYRIAD2_2)
6533         .Case("leon2", CK_LEON2)
6534         .Case("at697e", CK_LEON2_AT697E)
6535         .Case("at697f", CK_LEON2_AT697F)
6536         .Case("leon3", CK_LEON3)
6537         .Case("ut699", CK_LEON3_UT699)
6538         .Case("gr712rc", CK_LEON3_GR712RC)
6539         .Case("leon4", CK_LEON4)
6540         .Case("gr740", CK_LEON4_GR740)
6541         .Default(CK_GENERIC);
6542   }
6543 
setCPU(const std::string & Name)6544   bool setCPU(const std::string &Name) override {
6545     CPU = getCPUKind(Name);
6546     return CPU != CK_GENERIC;
6547   }
6548 };
6549 
6550 const char * const SparcTargetInfo::GCCRegNames[] = {
6551   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
6552   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
6553   "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
6554   "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31"
6555 };
6556 
getGCCRegNames() const6557 ArrayRef<const char *> SparcTargetInfo::getGCCRegNames() const {
6558   return llvm::makeArrayRef(GCCRegNames);
6559 }
6560 
6561 const TargetInfo::GCCRegAlias SparcTargetInfo::GCCRegAliases[] = {
6562   { { "g0" }, "r0" },
6563   { { "g1" }, "r1" },
6564   { { "g2" }, "r2" },
6565   { { "g3" }, "r3" },
6566   { { "g4" }, "r4" },
6567   { { "g5" }, "r5" },
6568   { { "g6" }, "r6" },
6569   { { "g7" }, "r7" },
6570   { { "o0" }, "r8" },
6571   { { "o1" }, "r9" },
6572   { { "o2" }, "r10" },
6573   { { "o3" }, "r11" },
6574   { { "o4" }, "r12" },
6575   { { "o5" }, "r13" },
6576   { { "o6", "sp" }, "r14" },
6577   { { "o7" }, "r15" },
6578   { { "l0" }, "r16" },
6579   { { "l1" }, "r17" },
6580   { { "l2" }, "r18" },
6581   { { "l3" }, "r19" },
6582   { { "l4" }, "r20" },
6583   { { "l5" }, "r21" },
6584   { { "l6" }, "r22" },
6585   { { "l7" }, "r23" },
6586   { { "i0" }, "r24" },
6587   { { "i1" }, "r25" },
6588   { { "i2" }, "r26" },
6589   { { "i3" }, "r27" },
6590   { { "i4" }, "r28" },
6591   { { "i5" }, "r29" },
6592   { { "i6", "fp" }, "r30" },
6593   { { "i7" }, "r31" },
6594 };
6595 
getGCCRegAliases() const6596 ArrayRef<TargetInfo::GCCRegAlias> SparcTargetInfo::getGCCRegAliases() const {
6597   return llvm::makeArrayRef(GCCRegAliases);
6598 }
6599 
6600 // SPARC v8 is the 32-bit mode selected by Triple::sparc.
6601 class SparcV8TargetInfo : public SparcTargetInfo {
6602 public:
SparcV8TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)6603   SparcV8TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
6604       : SparcTargetInfo(Triple, Opts) {
6605     resetDataLayout("E-m:e-p:32:32-i64:64-f128:64-n32-S64");
6606     // NetBSD / OpenBSD use long (same as llvm default); everyone else uses int.
6607     switch (getTriple().getOS()) {
6608     default:
6609       SizeType = UnsignedInt;
6610       IntPtrType = SignedInt;
6611       PtrDiffType = SignedInt;
6612       break;
6613     case llvm::Triple::NetBSD:
6614     case llvm::Triple::OpenBSD:
6615       SizeType = UnsignedLong;
6616       IntPtrType = SignedLong;
6617       PtrDiffType = SignedLong;
6618       break;
6619     }
6620     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
6621   }
6622 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6623   void getTargetDefines(const LangOptions &Opts,
6624                         MacroBuilder &Builder) const override {
6625     SparcTargetInfo::getTargetDefines(Opts, Builder);
6626     switch (getCPUGeneration(CPU)) {
6627     case CG_V8:
6628       Builder.defineMacro("__sparcv8");
6629       if (getTriple().getOS() != llvm::Triple::Solaris)
6630         Builder.defineMacro("__sparcv8__");
6631       break;
6632     case CG_V9:
6633       Builder.defineMacro("__sparcv9");
6634       if (getTriple().getOS() != llvm::Triple::Solaris) {
6635         Builder.defineMacro("__sparcv9__");
6636         Builder.defineMacro("__sparc_v9__");
6637       }
6638       break;
6639     }
6640     if (getTriple().getVendor() == llvm::Triple::Myriad) {
6641       switch (CPU) {
6642       case CK_MYRIAD2_1:
6643         Builder.defineMacro("__myriad2", "1");
6644         Builder.defineMacro("__myriad2__", "1");
6645         break;
6646       case CK_MYRIAD2_2:
6647         Builder.defineMacro("__myriad2", "2");
6648         Builder.defineMacro("__myriad2__", "2");
6649         break;
6650       default:
6651         break;
6652       }
6653     }
6654   }
6655 
hasSjLjLowering() const6656   bool hasSjLjLowering() const override {
6657     return true;
6658   }
6659 };
6660 
6661 // SPARCV8el is the 32-bit little-endian mode selected by Triple::sparcel.
6662 class SparcV8elTargetInfo : public SparcV8TargetInfo {
6663  public:
SparcV8elTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)6664    SparcV8elTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
6665        : SparcV8TargetInfo(Triple, Opts) {
6666      resetDataLayout("e-m:e-p:32:32-i64:64-f128:64-n32-S64");
6667      BigEndian = false;
6668   }
6669 };
6670 
6671 // SPARC v9 is the 64-bit mode selected by Triple::sparcv9.
6672 class SparcV9TargetInfo : public SparcTargetInfo {
6673 public:
SparcV9TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)6674   SparcV9TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
6675       : SparcTargetInfo(Triple, Opts) {
6676     // FIXME: Support Sparc quad-precision long double?
6677     resetDataLayout("E-m:e-i64:64-n32:64-S128");
6678     // This is an LP64 platform.
6679     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
6680 
6681     // OpenBSD uses long long for int64_t and intmax_t.
6682     if (getTriple().getOS() == llvm::Triple::OpenBSD)
6683       IntMaxType = SignedLongLong;
6684     else
6685       IntMaxType = SignedLong;
6686     Int64Type = IntMaxType;
6687 
6688     // The SPARCv8 System V ABI has long double 128-bits in size, but 64-bit
6689     // aligned. The SPARCv9 SCD 2.4.1 says 16-byte aligned.
6690     LongDoubleWidth = 128;
6691     LongDoubleAlign = 128;
6692     LongDoubleFormat = &llvm::APFloat::IEEEquad;
6693     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
6694   }
6695 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6696   void getTargetDefines(const LangOptions &Opts,
6697                         MacroBuilder &Builder) const override {
6698     SparcTargetInfo::getTargetDefines(Opts, Builder);
6699     Builder.defineMacro("__sparcv9");
6700     Builder.defineMacro("__arch64__");
6701     // Solaris doesn't need these variants, but the BSDs do.
6702     if (getTriple().getOS() != llvm::Triple::Solaris) {
6703       Builder.defineMacro("__sparc64__");
6704       Builder.defineMacro("__sparc_v9__");
6705       Builder.defineMacro("__sparcv9__");
6706     }
6707   }
6708 
setCPU(const std::string & Name)6709   bool setCPU(const std::string &Name) override {
6710     if (!SparcTargetInfo::setCPU(Name))
6711       return false;
6712     return getCPUGeneration(CPU) == CG_V9;
6713   }
6714 };
6715 
6716 class SystemZTargetInfo : public TargetInfo {
6717   static const Builtin::Info BuiltinInfo[];
6718   static const char *const GCCRegNames[];
6719   std::string CPU;
6720   bool HasTransactionalExecution;
6721   bool HasVector;
6722 
6723 public:
SystemZTargetInfo(const llvm::Triple & Triple,const TargetOptions &)6724   SystemZTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
6725       : TargetInfo(Triple), CPU("z10"), HasTransactionalExecution(false),
6726         HasVector(false) {
6727     IntMaxType = SignedLong;
6728     Int64Type = SignedLong;
6729     TLSSupported = true;
6730     IntWidth = IntAlign = 32;
6731     LongWidth = LongLongWidth = LongAlign = LongLongAlign = 64;
6732     PointerWidth = PointerAlign = 64;
6733     LongDoubleWidth = 128;
6734     LongDoubleAlign = 64;
6735     LongDoubleFormat = &llvm::APFloat::IEEEquad;
6736     DefaultAlignForAttributeAligned = 64;
6737     MinGlobalAlign = 16;
6738     resetDataLayout("E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-a:8:16-n32:64");
6739     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
6740   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6741   void getTargetDefines(const LangOptions &Opts,
6742                         MacroBuilder &Builder) const override {
6743     Builder.defineMacro("__s390__");
6744     Builder.defineMacro("__s390x__");
6745     Builder.defineMacro("__zarch__");
6746     Builder.defineMacro("__LONG_DOUBLE_128__");
6747 
6748     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
6749     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
6750     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
6751     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
6752 
6753     if (HasTransactionalExecution)
6754       Builder.defineMacro("__HTM__");
6755     if (Opts.ZVector)
6756       Builder.defineMacro("__VEC__", "10301");
6757   }
getTargetBuiltins() const6758   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
6759     return llvm::makeArrayRef(BuiltinInfo,
6760                          clang::SystemZ::LastTSBuiltin-Builtin::FirstTSBuiltin);
6761   }
6762 
6763   ArrayRef<const char *> getGCCRegNames() const override;
getGCCRegAliases() const6764   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
6765     // No aliases.
6766     return None;
6767   }
6768   bool validateAsmConstraint(const char *&Name,
6769                              TargetInfo::ConstraintInfo &info) const override;
getClobbers() const6770   const char *getClobbers() const override {
6771     // FIXME: Is this really right?
6772     return "";
6773   }
getBuiltinVaListKind() const6774   BuiltinVaListKind getBuiltinVaListKind() const override {
6775     return TargetInfo::SystemZBuiltinVaList;
6776   }
setCPU(const std::string & Name)6777   bool setCPU(const std::string &Name) override {
6778     CPU = Name;
6779     bool CPUKnown = llvm::StringSwitch<bool>(Name)
6780       .Case("z10", true)
6781       .Case("z196", true)
6782       .Case("zEC12", true)
6783       .Case("z13", true)
6784       .Default(false);
6785 
6786     return CPUKnown;
6787   }
6788   bool
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const6789   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
6790                  StringRef CPU,
6791                  const std::vector<std::string> &FeaturesVec) const override {
6792     if (CPU == "zEC12")
6793       Features["transactional-execution"] = true;
6794     if (CPU == "z13") {
6795       Features["transactional-execution"] = true;
6796       Features["vector"] = true;
6797     }
6798     return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
6799   }
6800 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)6801   bool handleTargetFeatures(std::vector<std::string> &Features,
6802                             DiagnosticsEngine &Diags) override {
6803     HasTransactionalExecution = false;
6804     for (const auto &Feature : Features) {
6805       if (Feature == "+transactional-execution")
6806         HasTransactionalExecution = true;
6807       else if (Feature == "+vector")
6808         HasVector = true;
6809     }
6810     // If we use the vector ABI, vector types are 64-bit aligned.
6811     if (HasVector) {
6812       MaxVectorAlign = 64;
6813       resetDataLayout("E-m:e-i1:8:16-i8:8:16-i64:64-f128:64"
6814                       "-v128:64-a:8:16-n32:64");
6815     }
6816     return true;
6817   }
6818 
hasFeature(StringRef Feature) const6819   bool hasFeature(StringRef Feature) const override {
6820     return llvm::StringSwitch<bool>(Feature)
6821         .Case("systemz", true)
6822         .Case("htm", HasTransactionalExecution)
6823         .Case("vx", HasVector)
6824         .Default(false);
6825   }
6826 
checkCallingConvention(CallingConv CC) const6827   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
6828     switch (CC) {
6829     case CC_C:
6830     case CC_Swift:
6831       return CCCR_OK;
6832     default:
6833       return CCCR_Warning;
6834     }
6835   }
6836 
getABI() const6837   StringRef getABI() const override {
6838     if (HasVector)
6839       return "vector";
6840     return "";
6841   }
6842 
useFloat128ManglingForLongDouble() const6843   bool useFloat128ManglingForLongDouble() const override {
6844     return true;
6845   }
6846 };
6847 
6848 const Builtin::Info SystemZTargetInfo::BuiltinInfo[] = {
6849 #define BUILTIN(ID, TYPE, ATTRS)                                               \
6850   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
6851 #define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE)                               \
6852   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, FEATURE },
6853 #include "clang/Basic/BuiltinsSystemZ.def"
6854 };
6855 
6856 const char *const SystemZTargetInfo::GCCRegNames[] = {
6857   "r0",  "r1",  "r2",  "r3",  "r4",  "r5",  "r6",  "r7",
6858   "r8",  "r9",  "r10", "r11", "r12", "r13", "r14", "r15",
6859   "f0",  "f2",  "f4",  "f6",  "f1",  "f3",  "f5",  "f7",
6860   "f8",  "f10", "f12", "f14", "f9",  "f11", "f13", "f15"
6861 };
6862 
getGCCRegNames() const6863 ArrayRef<const char *> SystemZTargetInfo::getGCCRegNames() const {
6864   return llvm::makeArrayRef(GCCRegNames);
6865 }
6866 
6867 bool SystemZTargetInfo::
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const6868 validateAsmConstraint(const char *&Name,
6869                       TargetInfo::ConstraintInfo &Info) const {
6870   switch (*Name) {
6871   default:
6872     return false;
6873 
6874   case 'a': // Address register
6875   case 'd': // Data register (equivalent to 'r')
6876   case 'f': // Floating-point register
6877     Info.setAllowsRegister();
6878     return true;
6879 
6880   case 'I': // Unsigned 8-bit constant
6881   case 'J': // Unsigned 12-bit constant
6882   case 'K': // Signed 16-bit constant
6883   case 'L': // Signed 20-bit displacement (on all targets we support)
6884   case 'M': // 0x7fffffff
6885     return true;
6886 
6887   case 'Q': // Memory with base and unsigned 12-bit displacement
6888   case 'R': // Likewise, plus an index
6889   case 'S': // Memory with base and signed 20-bit displacement
6890   case 'T': // Likewise, plus an index
6891     Info.setAllowsMemory();
6892     return true;
6893   }
6894 }
6895 
6896 class MSP430TargetInfo : public TargetInfo {
6897   static const char *const GCCRegNames[];
6898 
6899 public:
MSP430TargetInfo(const llvm::Triple & Triple,const TargetOptions &)6900   MSP430TargetInfo(const llvm::Triple &Triple, const TargetOptions &)
6901       : TargetInfo(Triple) {
6902     BigEndian = false;
6903     TLSSupported = false;
6904     IntWidth = 16;
6905     IntAlign = 16;
6906     LongWidth = 32;
6907     LongLongWidth = 64;
6908     LongAlign = LongLongAlign = 16;
6909     PointerWidth = 16;
6910     PointerAlign = 16;
6911     SuitableAlign = 16;
6912     SizeType = UnsignedInt;
6913     IntMaxType = SignedLongLong;
6914     IntPtrType = SignedInt;
6915     PtrDiffType = SignedInt;
6916     SigAtomicType = SignedLong;
6917     resetDataLayout("e-m:e-p:16:16-i32:16:32-a:16-n8:16");
6918   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6919   void getTargetDefines(const LangOptions &Opts,
6920                         MacroBuilder &Builder) const override {
6921     Builder.defineMacro("MSP430");
6922     Builder.defineMacro("__MSP430__");
6923     // FIXME: defines for different 'flavours' of MCU
6924   }
getTargetBuiltins() const6925   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
6926     // FIXME: Implement.
6927     return None;
6928   }
hasFeature(StringRef Feature) const6929   bool hasFeature(StringRef Feature) const override {
6930     return Feature == "msp430";
6931   }
6932   ArrayRef<const char *> getGCCRegNames() const override;
getGCCRegAliases() const6933   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
6934     // No aliases.
6935     return None;
6936   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const6937   bool validateAsmConstraint(const char *&Name,
6938                              TargetInfo::ConstraintInfo &info) const override {
6939     // FIXME: implement
6940     switch (*Name) {
6941     case 'K': // the constant 1
6942     case 'L': // constant -1^20 .. 1^19
6943     case 'M': // constant 1-4:
6944       return true;
6945     }
6946     // No target constraints for now.
6947     return false;
6948   }
getClobbers() const6949   const char *getClobbers() const override {
6950     // FIXME: Is this really right?
6951     return "";
6952   }
getBuiltinVaListKind() const6953   BuiltinVaListKind getBuiltinVaListKind() const override {
6954     // FIXME: implement
6955     return TargetInfo::CharPtrBuiltinVaList;
6956   }
6957 };
6958 
6959 const char *const MSP430TargetInfo::GCCRegNames[] = {
6960     "r0", "r1", "r2",  "r3",  "r4",  "r5",  "r6",  "r7",
6961     "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"};
6962 
getGCCRegNames() const6963 ArrayRef<const char *> MSP430TargetInfo::getGCCRegNames() const {
6964   return llvm::makeArrayRef(GCCRegNames);
6965 }
6966 
6967 // LLVM and Clang cannot be used directly to output native binaries for
6968 // target, but is used to compile C code to llvm bitcode with correct
6969 // type and alignment information.
6970 //
6971 // TCE uses the llvm bitcode as input and uses it for generating customized
6972 // target processor and program binary. TCE co-design environment is
6973 // publicly available in http://tce.cs.tut.fi
6974 
6975 static const unsigned TCEOpenCLAddrSpaceMap[] = {
6976     3, // opencl_global
6977     4, // opencl_local
6978     5, // opencl_constant
6979     // FIXME: generic has to be added to the target
6980     0, // opencl_generic
6981     0, // cuda_device
6982     0, // cuda_constant
6983     0  // cuda_shared
6984 };
6985 
6986 class TCETargetInfo : public TargetInfo {
6987 public:
TCETargetInfo(const llvm::Triple & Triple,const TargetOptions &)6988   TCETargetInfo(const llvm::Triple &Triple, const TargetOptions &)
6989       : TargetInfo(Triple) {
6990     TLSSupported = false;
6991     IntWidth = 32;
6992     LongWidth = LongLongWidth = 32;
6993     PointerWidth = 32;
6994     IntAlign = 32;
6995     LongAlign = LongLongAlign = 32;
6996     PointerAlign = 32;
6997     SuitableAlign = 32;
6998     SizeType = UnsignedInt;
6999     IntMaxType = SignedLong;
7000     IntPtrType = SignedInt;
7001     PtrDiffType = SignedInt;
7002     FloatWidth = 32;
7003     FloatAlign = 32;
7004     DoubleWidth = 32;
7005     DoubleAlign = 32;
7006     LongDoubleWidth = 32;
7007     LongDoubleAlign = 32;
7008     FloatFormat = &llvm::APFloat::IEEEsingle;
7009     DoubleFormat = &llvm::APFloat::IEEEsingle;
7010     LongDoubleFormat = &llvm::APFloat::IEEEsingle;
7011     resetDataLayout("E-p:32:32-i8:8:32-i16:16:32-i64:32"
7012                     "-f64:32-v64:32-v128:32-a:0:32-n32");
7013     AddrSpaceMap = &TCEOpenCLAddrSpaceMap;
7014     UseAddrSpaceMapMangling = true;
7015   }
7016 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7017   void getTargetDefines(const LangOptions &Opts,
7018                         MacroBuilder &Builder) const override {
7019     DefineStd(Builder, "tce", Opts);
7020     Builder.defineMacro("__TCE__");
7021     Builder.defineMacro("__TCE_V1__");
7022   }
hasFeature(StringRef Feature) const7023   bool hasFeature(StringRef Feature) const override { return Feature == "tce"; }
7024 
getTargetBuiltins() const7025   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
getClobbers() const7026   const char *getClobbers() const override { return ""; }
getBuiltinVaListKind() const7027   BuiltinVaListKind getBuiltinVaListKind() const override {
7028     return TargetInfo::VoidPtrBuiltinVaList;
7029   }
getGCCRegNames() const7030   ArrayRef<const char *> getGCCRegNames() const override { return None; }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const7031   bool validateAsmConstraint(const char *&Name,
7032                              TargetInfo::ConstraintInfo &info) const override {
7033     return true;
7034   }
getGCCRegAliases() const7035   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
7036     return None;
7037   }
7038 };
7039 
7040 class BPFTargetInfo : public TargetInfo {
7041 public:
BPFTargetInfo(const llvm::Triple & Triple,const TargetOptions &)7042   BPFTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
7043       : TargetInfo(Triple) {
7044     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
7045     SizeType    = UnsignedLong;
7046     PtrDiffType = SignedLong;
7047     IntPtrType  = SignedLong;
7048     IntMaxType  = SignedLong;
7049     Int64Type   = SignedLong;
7050     RegParmMax = 5;
7051     if (Triple.getArch() == llvm::Triple::bpfeb) {
7052       BigEndian = true;
7053       resetDataLayout("E-m:e-p:64:64-i64:64-n32:64-S128");
7054     } else {
7055       BigEndian = false;
7056       resetDataLayout("e-m:e-p:64:64-i64:64-n32:64-S128");
7057     }
7058     MaxAtomicPromoteWidth = 64;
7059     MaxAtomicInlineWidth = 64;
7060     TLSSupported = false;
7061   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7062   void getTargetDefines(const LangOptions &Opts,
7063                         MacroBuilder &Builder) const override {
7064     DefineStd(Builder, "bpf", Opts);
7065     Builder.defineMacro("__BPF__");
7066   }
hasFeature(StringRef Feature) const7067   bool hasFeature(StringRef Feature) const override {
7068     return Feature == "bpf";
7069   }
7070 
getTargetBuiltins() const7071   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
getClobbers() const7072   const char *getClobbers() const override {
7073     return "";
7074   }
getBuiltinVaListKind() const7075   BuiltinVaListKind getBuiltinVaListKind() const override {
7076     return TargetInfo::VoidPtrBuiltinVaList;
7077   }
getGCCRegNames() const7078   ArrayRef<const char *> getGCCRegNames() const override {
7079     return None;
7080   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const7081   bool validateAsmConstraint(const char *&Name,
7082                              TargetInfo::ConstraintInfo &info) const override {
7083     return true;
7084   }
getGCCRegAliases() const7085   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
7086     return None;
7087   }
7088 };
7089 
7090 class MipsTargetInfo : public TargetInfo {
setDataLayout()7091   void setDataLayout() {
7092     StringRef Layout;
7093 
7094     if (ABI == "o32")
7095       Layout = "m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64";
7096     else if (ABI == "n32")
7097       Layout = "m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128";
7098     else if (ABI == "n64")
7099       Layout = "m:m-i8:8:32-i16:16:32-i64:64-n32:64-S128";
7100     else
7101       llvm_unreachable("Invalid ABI");
7102 
7103     if (BigEndian)
7104       resetDataLayout(("E-" + Layout).str());
7105     else
7106       resetDataLayout(("e-" + Layout).str());
7107   }
7108 
7109 
7110   static const Builtin::Info BuiltinInfo[];
7111   std::string CPU;
7112   bool IsMips16;
7113   bool IsMicromips;
7114   bool IsNan2008;
7115   bool IsSingleFloat;
7116   enum MipsFloatABI {
7117     HardFloat, SoftFloat
7118   } FloatABI;
7119   enum DspRevEnum {
7120     NoDSP, DSP1, DSP2
7121   } DspRev;
7122   bool HasMSA;
7123 
7124 protected:
7125   bool HasFP64;
7126   std::string ABI;
7127 
7128 public:
MipsTargetInfo(const llvm::Triple & Triple,const TargetOptions &)7129   MipsTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
7130       : TargetInfo(Triple), IsMips16(false), IsMicromips(false),
7131         IsNan2008(false), IsSingleFloat(false), FloatABI(HardFloat),
7132         DspRev(NoDSP), HasMSA(false), HasFP64(false) {
7133     TheCXXABI.set(TargetCXXABI::GenericMIPS);
7134     BigEndian = getTriple().getArch() == llvm::Triple::mips ||
7135                 getTriple().getArch() == llvm::Triple::mips64;
7136 
7137     setABI((getTriple().getArch() == llvm::Triple::mips ||
7138             getTriple().getArch() == llvm::Triple::mipsel)
7139                ? "o32"
7140                : "n64");
7141 
7142     CPU = ABI == "o32" ? "mips32r2" : "mips64r2";
7143   }
7144 
isNaN2008Default() const7145   bool isNaN2008Default() const {
7146     return CPU == "mips32r6" || CPU == "mips64r6";
7147   }
7148 
isFP64Default() const7149   bool isFP64Default() const {
7150     return CPU == "mips32r6" || ABI == "n32" || ABI == "n64" || ABI == "64";
7151   }
7152 
isNan2008() const7153   bool isNan2008() const override {
7154     return IsNan2008;
7155   }
7156 
processorSupportsGPR64() const7157   bool processorSupportsGPR64() const {
7158     return llvm::StringSwitch<bool>(CPU)
7159         .Case("mips3", true)
7160         .Case("mips4", true)
7161         .Case("mips5", true)
7162         .Case("mips64", true)
7163         .Case("mips64r2", true)
7164         .Case("mips64r3", true)
7165         .Case("mips64r5", true)
7166         .Case("mips64r6", true)
7167         .Case("octeon", true)
7168         .Default(false);
7169     return false;
7170   }
7171 
getABI() const7172   StringRef getABI() const override { return ABI; }
setABI(const std::string & Name)7173   bool setABI(const std::string &Name) override {
7174     if (Name == "o32") {
7175       setO32ABITypes();
7176       ABI = Name;
7177       return true;
7178     }
7179 
7180     if (Name == "n32") {
7181       setN32ABITypes();
7182       ABI = Name;
7183       return true;
7184     }
7185     if (Name == "n64") {
7186       setN64ABITypes();
7187       ABI = Name;
7188       return true;
7189     }
7190     return false;
7191   }
7192 
setO32ABITypes()7193   void setO32ABITypes() {
7194     Int64Type = SignedLongLong;
7195     IntMaxType = Int64Type;
7196     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
7197     LongDoubleWidth = LongDoubleAlign = 64;
7198     LongWidth = LongAlign = 32;
7199     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32;
7200     PointerWidth = PointerAlign = 32;
7201     PtrDiffType = SignedInt;
7202     SizeType = UnsignedInt;
7203     SuitableAlign = 64;
7204   }
7205 
setN32N64ABITypes()7206   void setN32N64ABITypes() {
7207     LongDoubleWidth = LongDoubleAlign = 128;
7208     LongDoubleFormat = &llvm::APFloat::IEEEquad;
7209     if (getTriple().getOS() == llvm::Triple::FreeBSD) {
7210       LongDoubleWidth = LongDoubleAlign = 64;
7211       LongDoubleFormat = &llvm::APFloat::IEEEdouble;
7212     }
7213     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
7214     SuitableAlign = 128;
7215   }
7216 
setN64ABITypes()7217   void setN64ABITypes() {
7218     setN32N64ABITypes();
7219     Int64Type = SignedLong;
7220     IntMaxType = Int64Type;
7221     LongWidth = LongAlign = 64;
7222     PointerWidth = PointerAlign = 64;
7223     PtrDiffType = SignedLong;
7224     SizeType = UnsignedLong;
7225   }
7226 
setN32ABITypes()7227   void setN32ABITypes() {
7228     setN32N64ABITypes();
7229     Int64Type = SignedLongLong;
7230     IntMaxType = Int64Type;
7231     LongWidth = LongAlign = 32;
7232     PointerWidth = PointerAlign = 32;
7233     PtrDiffType = SignedInt;
7234     SizeType = UnsignedInt;
7235   }
7236 
setCPU(const std::string & Name)7237   bool setCPU(const std::string &Name) override {
7238     CPU = Name;
7239     return llvm::StringSwitch<bool>(Name)
7240         .Case("mips1", true)
7241         .Case("mips2", true)
7242         .Case("mips3", true)
7243         .Case("mips4", true)
7244         .Case("mips5", true)
7245         .Case("mips32", true)
7246         .Case("mips32r2", true)
7247         .Case("mips32r3", true)
7248         .Case("mips32r5", true)
7249         .Case("mips32r6", true)
7250         .Case("mips64", true)
7251         .Case("mips64r2", true)
7252         .Case("mips64r3", true)
7253         .Case("mips64r5", true)
7254         .Case("mips64r6", true)
7255         .Case("octeon", true)
7256         .Case("p5600", true)
7257         .Default(false);
7258   }
getCPU() const7259   const std::string& getCPU() const { return CPU; }
7260   bool
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const7261   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
7262                  StringRef CPU,
7263                  const std::vector<std::string> &FeaturesVec) const override {
7264     if (CPU.empty())
7265       CPU = getCPU();
7266     if (CPU == "octeon")
7267       Features["mips64r2"] = Features["cnmips"] = true;
7268     else
7269       Features[CPU] = true;
7270     return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
7271   }
7272 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7273   void getTargetDefines(const LangOptions &Opts,
7274                         MacroBuilder &Builder) const override {
7275     if (BigEndian) {
7276       DefineStd(Builder, "MIPSEB", Opts);
7277       Builder.defineMacro("_MIPSEB");
7278     } else {
7279       DefineStd(Builder, "MIPSEL", Opts);
7280       Builder.defineMacro("_MIPSEL");
7281     }
7282 
7283     Builder.defineMacro("__mips__");
7284     Builder.defineMacro("_mips");
7285     if (Opts.GNUMode)
7286       Builder.defineMacro("mips");
7287 
7288     if (ABI == "o32") {
7289       Builder.defineMacro("__mips", "32");
7290       Builder.defineMacro("_MIPS_ISA", "_MIPS_ISA_MIPS32");
7291     } else {
7292       Builder.defineMacro("__mips", "64");
7293       Builder.defineMacro("__mips64");
7294       Builder.defineMacro("__mips64__");
7295       Builder.defineMacro("_MIPS_ISA", "_MIPS_ISA_MIPS64");
7296     }
7297 
7298     const std::string ISARev = llvm::StringSwitch<std::string>(getCPU())
7299                                    .Cases("mips32", "mips64", "1")
7300                                    .Cases("mips32r2", "mips64r2", "2")
7301                                    .Cases("mips32r3", "mips64r3", "3")
7302                                    .Cases("mips32r5", "mips64r5", "5")
7303                                    .Cases("mips32r6", "mips64r6", "6")
7304                                    .Default("");
7305     if (!ISARev.empty())
7306       Builder.defineMacro("__mips_isa_rev", ISARev);
7307 
7308     if (ABI == "o32") {
7309       Builder.defineMacro("__mips_o32");
7310       Builder.defineMacro("_ABIO32", "1");
7311       Builder.defineMacro("_MIPS_SIM", "_ABIO32");
7312     } else if (ABI == "n32") {
7313       Builder.defineMacro("__mips_n32");
7314       Builder.defineMacro("_ABIN32", "2");
7315       Builder.defineMacro("_MIPS_SIM", "_ABIN32");
7316     } else if (ABI == "n64") {
7317       Builder.defineMacro("__mips_n64");
7318       Builder.defineMacro("_ABI64", "3");
7319       Builder.defineMacro("_MIPS_SIM", "_ABI64");
7320     } else
7321       llvm_unreachable("Invalid ABI.");
7322 
7323     Builder.defineMacro("__REGISTER_PREFIX__", "");
7324 
7325     switch (FloatABI) {
7326     case HardFloat:
7327       Builder.defineMacro("__mips_hard_float", Twine(1));
7328       break;
7329     case SoftFloat:
7330       Builder.defineMacro("__mips_soft_float", Twine(1));
7331       break;
7332     }
7333 
7334     if (IsSingleFloat)
7335       Builder.defineMacro("__mips_single_float", Twine(1));
7336 
7337     Builder.defineMacro("__mips_fpr", HasFP64 ? Twine(64) : Twine(32));
7338     Builder.defineMacro("_MIPS_FPSET",
7339                         Twine(32 / (HasFP64 || IsSingleFloat ? 1 : 2)));
7340 
7341     if (IsMips16)
7342       Builder.defineMacro("__mips16", Twine(1));
7343 
7344     if (IsMicromips)
7345       Builder.defineMacro("__mips_micromips", Twine(1));
7346 
7347     if (IsNan2008)
7348       Builder.defineMacro("__mips_nan2008", Twine(1));
7349 
7350     switch (DspRev) {
7351     default:
7352       break;
7353     case DSP1:
7354       Builder.defineMacro("__mips_dsp_rev", Twine(1));
7355       Builder.defineMacro("__mips_dsp", Twine(1));
7356       break;
7357     case DSP2:
7358       Builder.defineMacro("__mips_dsp_rev", Twine(2));
7359       Builder.defineMacro("__mips_dspr2", Twine(1));
7360       Builder.defineMacro("__mips_dsp", Twine(1));
7361       break;
7362     }
7363 
7364     if (HasMSA)
7365       Builder.defineMacro("__mips_msa", Twine(1));
7366 
7367     Builder.defineMacro("_MIPS_SZPTR", Twine(getPointerWidth(0)));
7368     Builder.defineMacro("_MIPS_SZINT", Twine(getIntWidth()));
7369     Builder.defineMacro("_MIPS_SZLONG", Twine(getLongWidth()));
7370 
7371     Builder.defineMacro("_MIPS_ARCH", "\"" + CPU + "\"");
7372     Builder.defineMacro("_MIPS_ARCH_" + StringRef(CPU).upper());
7373 
7374     // These shouldn't be defined for MIPS-I but there's no need to check
7375     // for that since MIPS-I isn't supported.
7376     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
7377     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
7378     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
7379 
7380     // 32-bit MIPS processors don't have the necessary lld/scd instructions
7381     // found in 64-bit processors. In the case of O32 on a 64-bit processor,
7382     // the instructions exist but using them violates the ABI since they
7383     // require 64-bit GPRs and O32 only supports 32-bit GPRs.
7384     if (ABI == "n32" || ABI == "n64")
7385       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
7386   }
7387 
getTargetBuiltins() const7388   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
7389     return llvm::makeArrayRef(BuiltinInfo,
7390                           clang::Mips::LastTSBuiltin - Builtin::FirstTSBuiltin);
7391   }
hasFeature(StringRef Feature) const7392   bool hasFeature(StringRef Feature) const override {
7393     return llvm::StringSwitch<bool>(Feature)
7394       .Case("mips", true)
7395       .Case("fp64", HasFP64)
7396       .Default(false);
7397   }
getBuiltinVaListKind() const7398   BuiltinVaListKind getBuiltinVaListKind() const override {
7399     return TargetInfo::VoidPtrBuiltinVaList;
7400   }
getGCCRegNames() const7401   ArrayRef<const char *> getGCCRegNames() const override {
7402     static const char *const GCCRegNames[] = {
7403       // CPU register names
7404       // Must match second column of GCCRegAliases
7405       "$0",   "$1",   "$2",   "$3",   "$4",   "$5",   "$6",   "$7",
7406       "$8",   "$9",   "$10",  "$11",  "$12",  "$13",  "$14",  "$15",
7407       "$16",  "$17",  "$18",  "$19",  "$20",  "$21",  "$22",  "$23",
7408       "$24",  "$25",  "$26",  "$27",  "$28",  "$29",  "$30",  "$31",
7409       // Floating point register names
7410       "$f0",  "$f1",  "$f2",  "$f3",  "$f4",  "$f5",  "$f6",  "$f7",
7411       "$f8",  "$f9",  "$f10", "$f11", "$f12", "$f13", "$f14", "$f15",
7412       "$f16", "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23",
7413       "$f24", "$f25", "$f26", "$f27", "$f28", "$f29", "$f30", "$f31",
7414       // Hi/lo and condition register names
7415       "hi",   "lo",   "",     "$fcc0","$fcc1","$fcc2","$fcc3","$fcc4",
7416       "$fcc5","$fcc6","$fcc7","$ac1hi","$ac1lo","$ac2hi","$ac2lo",
7417       "$ac3hi","$ac3lo",
7418       // MSA register names
7419       "$w0",  "$w1",  "$w2",  "$w3",  "$w4",  "$w5",  "$w6",  "$w7",
7420       "$w8",  "$w9",  "$w10", "$w11", "$w12", "$w13", "$w14", "$w15",
7421       "$w16", "$w17", "$w18", "$w19", "$w20", "$w21", "$w22", "$w23",
7422       "$w24", "$w25", "$w26", "$w27", "$w28", "$w29", "$w30", "$w31",
7423       // MSA control register names
7424       "$msair",      "$msacsr", "$msaaccess", "$msasave", "$msamodify",
7425       "$msarequest", "$msamap", "$msaunmap"
7426     };
7427     return llvm::makeArrayRef(GCCRegNames);
7428   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const7429   bool validateAsmConstraint(const char *&Name,
7430                              TargetInfo::ConstraintInfo &Info) const override {
7431     switch (*Name) {
7432     default:
7433       return false;
7434     case 'r': // CPU registers.
7435     case 'd': // Equivalent to "r" unless generating MIPS16 code.
7436     case 'y': // Equivalent to "r", backward compatibility only.
7437     case 'f': // floating-point registers.
7438     case 'c': // $25 for indirect jumps
7439     case 'l': // lo register
7440     case 'x': // hilo register pair
7441       Info.setAllowsRegister();
7442       return true;
7443     case 'I': // Signed 16-bit constant
7444     case 'J': // Integer 0
7445     case 'K': // Unsigned 16-bit constant
7446     case 'L': // Signed 32-bit constant, lower 16-bit zeros (for lui)
7447     case 'M': // Constants not loadable via lui, addiu, or ori
7448     case 'N': // Constant -1 to -65535
7449     case 'O': // A signed 15-bit constant
7450     case 'P': // A constant between 1 go 65535
7451       return true;
7452     case 'R': // An address that can be used in a non-macro load or store
7453       Info.setAllowsMemory();
7454       return true;
7455     case 'Z':
7456       if (Name[1] == 'C') { // An address usable by ll, and sc.
7457         Info.setAllowsMemory();
7458         Name++; // Skip over 'Z'.
7459         return true;
7460       }
7461       return false;
7462     }
7463   }
7464 
convertConstraint(const char * & Constraint) const7465   std::string convertConstraint(const char *&Constraint) const override {
7466     std::string R;
7467     switch (*Constraint) {
7468     case 'Z': // Two-character constraint; add "^" hint for later parsing.
7469       if (Constraint[1] == 'C') {
7470         R = std::string("^") + std::string(Constraint, 2);
7471         Constraint++;
7472         return R;
7473       }
7474       break;
7475     }
7476     return TargetInfo::convertConstraint(Constraint);
7477   }
7478 
getClobbers() const7479   const char *getClobbers() const override {
7480     // In GCC, $1 is not widely used in generated code (it's used only in a few
7481     // specific situations), so there is no real need for users to add it to
7482     // the clobbers list if they want to use it in their inline assembly code.
7483     //
7484     // In LLVM, $1 is treated as a normal GPR and is always allocatable during
7485     // code generation, so using it in inline assembly without adding it to the
7486     // clobbers list can cause conflicts between the inline assembly code and
7487     // the surrounding generated code.
7488     //
7489     // Another problem is that LLVM is allowed to choose $1 for inline assembly
7490     // operands, which will conflict with the ".set at" assembler option (which
7491     // we use only for inline assembly, in order to maintain compatibility with
7492     // GCC) and will also conflict with the user's usage of $1.
7493     //
7494     // The easiest way to avoid these conflicts and keep $1 as an allocatable
7495     // register for generated code is to automatically clobber $1 for all inline
7496     // assembly code.
7497     //
7498     // FIXME: We should automatically clobber $1 only for inline assembly code
7499     // which actually uses it. This would allow LLVM to use $1 for inline
7500     // assembly operands if the user's assembly code doesn't use it.
7501     return "~{$1}";
7502   }
7503 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)7504   bool handleTargetFeatures(std::vector<std::string> &Features,
7505                             DiagnosticsEngine &Diags) override {
7506     IsMips16 = false;
7507     IsMicromips = false;
7508     IsNan2008 = isNaN2008Default();
7509     IsSingleFloat = false;
7510     FloatABI = HardFloat;
7511     DspRev = NoDSP;
7512     HasFP64 = isFP64Default();
7513 
7514     for (const auto &Feature : Features) {
7515       if (Feature == "+single-float")
7516         IsSingleFloat = true;
7517       else if (Feature == "+soft-float")
7518         FloatABI = SoftFloat;
7519       else if (Feature == "+mips16")
7520         IsMips16 = true;
7521       else if (Feature == "+micromips")
7522         IsMicromips = true;
7523       else if (Feature == "+dsp")
7524         DspRev = std::max(DspRev, DSP1);
7525       else if (Feature == "+dspr2")
7526         DspRev = std::max(DspRev, DSP2);
7527       else if (Feature == "+msa")
7528         HasMSA = true;
7529       else if (Feature == "+fp64")
7530         HasFP64 = true;
7531       else if (Feature == "-fp64")
7532         HasFP64 = false;
7533       else if (Feature == "+nan2008")
7534         IsNan2008 = true;
7535       else if (Feature == "-nan2008")
7536         IsNan2008 = false;
7537     }
7538 
7539     setDataLayout();
7540 
7541     return true;
7542   }
7543 
getEHDataRegisterNumber(unsigned RegNo) const7544   int getEHDataRegisterNumber(unsigned RegNo) const override {
7545     if (RegNo == 0) return 4;
7546     if (RegNo == 1) return 5;
7547     return -1;
7548   }
7549 
isCLZForZeroUndef() const7550   bool isCLZForZeroUndef() const override { return false; }
7551 
getGCCRegAliases() const7552   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
7553     static const TargetInfo::GCCRegAlias O32RegAliases[] = {
7554         {{"at"}, "$1"},  {{"v0"}, "$2"},         {{"v1"}, "$3"},
7555         {{"a0"}, "$4"},  {{"a1"}, "$5"},         {{"a2"}, "$6"},
7556         {{"a3"}, "$7"},  {{"t0"}, "$8"},         {{"t1"}, "$9"},
7557         {{"t2"}, "$10"}, {{"t3"}, "$11"},        {{"t4"}, "$12"},
7558         {{"t5"}, "$13"}, {{"t6"}, "$14"},        {{"t7"}, "$15"},
7559         {{"s0"}, "$16"}, {{"s1"}, "$17"},        {{"s2"}, "$18"},
7560         {{"s3"}, "$19"}, {{"s4"}, "$20"},        {{"s5"}, "$21"},
7561         {{"s6"}, "$22"}, {{"s7"}, "$23"},        {{"t8"}, "$24"},
7562         {{"t9"}, "$25"}, {{"k0"}, "$26"},        {{"k1"}, "$27"},
7563         {{"gp"}, "$28"}, {{"sp", "$sp"}, "$29"}, {{"fp", "$fp"}, "$30"},
7564         {{"ra"}, "$31"}};
7565     static const TargetInfo::GCCRegAlias NewABIRegAliases[] = {
7566         {{"at"}, "$1"},  {{"v0"}, "$2"},         {{"v1"}, "$3"},
7567         {{"a0"}, "$4"},  {{"a1"}, "$5"},         {{"a2"}, "$6"},
7568         {{"a3"}, "$7"},  {{"a4"}, "$8"},         {{"a5"}, "$9"},
7569         {{"a6"}, "$10"}, {{"a7"}, "$11"},        {{"t0"}, "$12"},
7570         {{"t1"}, "$13"}, {{"t2"}, "$14"},        {{"t3"}, "$15"},
7571         {{"s0"}, "$16"}, {{"s1"}, "$17"},        {{"s2"}, "$18"},
7572         {{"s3"}, "$19"}, {{"s4"}, "$20"},        {{"s5"}, "$21"},
7573         {{"s6"}, "$22"}, {{"s7"}, "$23"},        {{"t8"}, "$24"},
7574         {{"t9"}, "$25"}, {{"k0"}, "$26"},        {{"k1"}, "$27"},
7575         {{"gp"}, "$28"}, {{"sp", "$sp"}, "$29"}, {{"fp", "$fp"}, "$30"},
7576         {{"ra"}, "$31"}};
7577     if (ABI == "o32")
7578       return llvm::makeArrayRef(O32RegAliases);
7579     return llvm::makeArrayRef(NewABIRegAliases);
7580   }
7581 
hasInt128Type() const7582   bool hasInt128Type() const override {
7583     return ABI == "n32" || ABI == "n64";
7584   }
7585 
validateTarget(DiagnosticsEngine & Diags) const7586   bool validateTarget(DiagnosticsEngine &Diags) const override {
7587     // FIXME: It's valid to use O32 on a 64-bit CPU but the backend can't handle
7588     //        this yet. It's better to fail here than on the backend assertion.
7589     if (processorSupportsGPR64() && ABI == "o32") {
7590       Diags.Report(diag::err_target_unsupported_abi) << ABI << CPU;
7591       return false;
7592     }
7593 
7594     // 64-bit ABI's require 64-bit CPU's.
7595     if (!processorSupportsGPR64() && (ABI == "n32" || ABI == "n64")) {
7596       Diags.Report(diag::err_target_unsupported_abi) << ABI << CPU;
7597       return false;
7598     }
7599 
7600     // FIXME: It's valid to use O32 on a mips64/mips64el triple but the backend
7601     //        can't handle this yet. It's better to fail here than on the
7602     //        backend assertion.
7603     if ((getTriple().getArch() == llvm::Triple::mips64 ||
7604          getTriple().getArch() == llvm::Triple::mips64el) &&
7605         ABI == "o32") {
7606       Diags.Report(diag::err_target_unsupported_abi_for_triple)
7607           << ABI << getTriple().str();
7608       return false;
7609     }
7610 
7611     // FIXME: It's valid to use N32/N64 on a mips/mipsel triple but the backend
7612     //        can't handle this yet. It's better to fail here than on the
7613     //        backend assertion.
7614     if ((getTriple().getArch() == llvm::Triple::mips ||
7615          getTriple().getArch() == llvm::Triple::mipsel) &&
7616         (ABI == "n32" || ABI == "n64")) {
7617       Diags.Report(diag::err_target_unsupported_abi_for_triple)
7618           << ABI << getTriple().str();
7619       return false;
7620     }
7621 
7622     return true;
7623   }
7624 };
7625 
7626 const Builtin::Info MipsTargetInfo::BuiltinInfo[] = {
7627 #define BUILTIN(ID, TYPE, ATTRS) \
7628   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
7629 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
7630   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
7631 #include "clang/Basic/BuiltinsMips.def"
7632 };
7633 
7634 class PNaClTargetInfo : public TargetInfo {
7635 public:
PNaClTargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)7636   PNaClTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
7637       : TargetInfo(Triple) {
7638     BigEndian = false;
7639     this->LongAlign = 32;
7640     this->LongWidth = 32;
7641     this->PointerAlign = 32;
7642     this->PointerWidth = 32;
7643     this->IntMaxType = TargetInfo::SignedLongLong;
7644     this->Int64Type = TargetInfo::SignedLongLong;
7645     this->DoubleAlign = 64;
7646     this->LongDoubleWidth = 64;
7647     this->LongDoubleAlign = 64;
7648     this->SizeType = TargetInfo::UnsignedInt;
7649     this->PtrDiffType = TargetInfo::SignedInt;
7650     this->IntPtrType = TargetInfo::SignedInt;
7651     this->RegParmMax = 0; // Disallow regparm
7652   }
7653 
getArchDefines(const LangOptions & Opts,MacroBuilder & Builder) const7654   void getArchDefines(const LangOptions &Opts, MacroBuilder &Builder) const {
7655     Builder.defineMacro("__le32__");
7656     Builder.defineMacro("__pnacl__");
7657   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7658   void getTargetDefines(const LangOptions &Opts,
7659                         MacroBuilder &Builder) const override {
7660     getArchDefines(Opts, Builder);
7661   }
hasFeature(StringRef Feature) const7662   bool hasFeature(StringRef Feature) const override {
7663     return Feature == "pnacl";
7664   }
getTargetBuiltins() const7665   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
getBuiltinVaListKind() const7666   BuiltinVaListKind getBuiltinVaListKind() const override {
7667     return TargetInfo::PNaClABIBuiltinVaList;
7668   }
7669   ArrayRef<const char *> getGCCRegNames() const override;
7670   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const7671   bool validateAsmConstraint(const char *&Name,
7672                              TargetInfo::ConstraintInfo &Info) const override {
7673     return false;
7674   }
7675 
getClobbers() const7676   const char *getClobbers() const override {
7677     return "";
7678   }
7679 };
7680 
getGCCRegNames() const7681 ArrayRef<const char *> PNaClTargetInfo::getGCCRegNames() const {
7682   return None;
7683 }
7684 
getGCCRegAliases() const7685 ArrayRef<TargetInfo::GCCRegAlias> PNaClTargetInfo::getGCCRegAliases() const {
7686   return None;
7687 }
7688 
7689 // We attempt to use PNaCl (le32) frontend and Mips32EL backend.
7690 class NaClMips32TargetInfo : public MipsTargetInfo {
7691 public:
NaClMips32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)7692   NaClMips32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
7693       : MipsTargetInfo(Triple, Opts) {}
7694 
getBuiltinVaListKind() const7695   BuiltinVaListKind getBuiltinVaListKind() const override {
7696     return TargetInfo::PNaClABIBuiltinVaList;
7697   }
7698 };
7699 
7700 class Le64TargetInfo : public TargetInfo {
7701   static const Builtin::Info BuiltinInfo[];
7702 
7703 public:
Le64TargetInfo(const llvm::Triple & Triple,const TargetOptions &)7704   Le64TargetInfo(const llvm::Triple &Triple, const TargetOptions &)
7705       : TargetInfo(Triple) {
7706     BigEndian = false;
7707     NoAsmVariants = true;
7708     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
7709     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
7710     resetDataLayout("e-m:e-v128:32-v16:16-v32:32-v96:32-n8:16:32:64-S128");
7711   }
7712 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7713   void getTargetDefines(const LangOptions &Opts,
7714                         MacroBuilder &Builder) const override {
7715     DefineStd(Builder, "unix", Opts);
7716     defineCPUMacros(Builder, "le64", /*Tuning=*/false);
7717     Builder.defineMacro("__ELF__");
7718   }
getTargetBuiltins() const7719   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
7720     return llvm::makeArrayRef(BuiltinInfo,
7721                           clang::Le64::LastTSBuiltin - Builtin::FirstTSBuiltin);
7722   }
getBuiltinVaListKind() const7723   BuiltinVaListKind getBuiltinVaListKind() const override {
7724     return TargetInfo::PNaClABIBuiltinVaList;
7725   }
getClobbers() const7726   const char *getClobbers() const override { return ""; }
getGCCRegNames() const7727   ArrayRef<const char *> getGCCRegNames() const override {
7728     return None;
7729   }
getGCCRegAliases() const7730   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
7731     return None;
7732   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const7733   bool validateAsmConstraint(const char *&Name,
7734                              TargetInfo::ConstraintInfo &Info) const override {
7735     return false;
7736   }
7737 
hasProtectedVisibility() const7738   bool hasProtectedVisibility() const override { return false; }
7739 };
7740 
7741 class WebAssemblyTargetInfo : public TargetInfo {
7742   static const Builtin::Info BuiltinInfo[];
7743 
7744   enum SIMDEnum {
7745     NoSIMD,
7746     SIMD128,
7747   } SIMDLevel;
7748 
7749 public:
WebAssemblyTargetInfo(const llvm::Triple & T,const TargetOptions &)7750   explicit WebAssemblyTargetInfo(const llvm::Triple &T, const TargetOptions &)
7751       : TargetInfo(T), SIMDLevel(NoSIMD) {
7752     BigEndian = false;
7753     NoAsmVariants = true;
7754     SuitableAlign = 128;
7755     LargeArrayMinWidth = 128;
7756     LargeArrayAlign = 128;
7757     SimdDefaultAlign = 128;
7758     SigAtomicType = SignedLong;
7759     LongDoubleWidth = LongDoubleAlign = 128;
7760     LongDoubleFormat = &llvm::APFloat::IEEEquad;
7761   }
7762 
7763 protected:
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7764   void getTargetDefines(const LangOptions &Opts,
7765                         MacroBuilder &Builder) const override {
7766     defineCPUMacros(Builder, "wasm", /*Tuning=*/false);
7767     if (SIMDLevel >= SIMD128)
7768       Builder.defineMacro("__wasm_simd128__");
7769   }
7770 
7771 private:
7772   bool
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const7773   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
7774                  StringRef CPU,
7775                  const std::vector<std::string> &FeaturesVec) const override {
7776     if (CPU == "bleeding-edge")
7777       Features["simd128"] = true;
7778     return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
7779   }
hasFeature(StringRef Feature) const7780   bool hasFeature(StringRef Feature) const final {
7781     return llvm::StringSwitch<bool>(Feature)
7782         .Case("simd128", SIMDLevel >= SIMD128)
7783         .Default(false);
7784   }
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)7785   bool handleTargetFeatures(std::vector<std::string> &Features,
7786                             DiagnosticsEngine &Diags) final {
7787     for (const auto &Feature : Features) {
7788       if (Feature == "+simd128") {
7789         SIMDLevel = std::max(SIMDLevel, SIMD128);
7790         continue;
7791       }
7792       if (Feature == "-simd128") {
7793         SIMDLevel = std::min(SIMDLevel, SIMDEnum(SIMD128 - 1));
7794         continue;
7795       }
7796 
7797       Diags.Report(diag::err_opt_not_valid_with_opt) << Feature
7798                                                      << "-target-feature";
7799       return false;
7800     }
7801     return true;
7802   }
setCPU(const std::string & Name)7803   bool setCPU(const std::string &Name) final {
7804     return llvm::StringSwitch<bool>(Name)
7805               .Case("mvp",           true)
7806               .Case("bleeding-edge", true)
7807               .Case("generic",       true)
7808               .Default(false);
7809   }
getTargetBuiltins() const7810   ArrayRef<Builtin::Info> getTargetBuiltins() const final {
7811     return llvm::makeArrayRef(BuiltinInfo,
7812                    clang::WebAssembly::LastTSBuiltin - Builtin::FirstTSBuiltin);
7813   }
getBuiltinVaListKind() const7814   BuiltinVaListKind getBuiltinVaListKind() const final {
7815     return VoidPtrBuiltinVaList;
7816   }
getGCCRegNames() const7817   ArrayRef<const char *> getGCCRegNames() const final {
7818     return None;
7819   }
getGCCRegAliases() const7820   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const final {
7821     return None;
7822   }
7823   bool
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const7824   validateAsmConstraint(const char *&Name,
7825                         TargetInfo::ConstraintInfo &Info) const final {
7826     return false;
7827   }
getClobbers() const7828   const char *getClobbers() const final { return ""; }
isCLZForZeroUndef() const7829   bool isCLZForZeroUndef() const final { return false; }
hasInt128Type() const7830   bool hasInt128Type() const final { return true; }
getIntTypeByWidth(unsigned BitWidth,bool IsSigned) const7831   IntType getIntTypeByWidth(unsigned BitWidth,
7832                             bool IsSigned) const final {
7833     // WebAssembly prefers long long for explicitly 64-bit integers.
7834     return BitWidth == 64 ? (IsSigned ? SignedLongLong : UnsignedLongLong)
7835                           : TargetInfo::getIntTypeByWidth(BitWidth, IsSigned);
7836   }
getLeastIntTypeByWidth(unsigned BitWidth,bool IsSigned) const7837   IntType getLeastIntTypeByWidth(unsigned BitWidth,
7838                                  bool IsSigned) const final {
7839     // WebAssembly uses long long for int_least64_t and int_fast64_t.
7840     return BitWidth == 64
7841                ? (IsSigned ? SignedLongLong : UnsignedLongLong)
7842                : TargetInfo::getLeastIntTypeByWidth(BitWidth, IsSigned);
7843   }
7844 };
7845 
7846 const Builtin::Info WebAssemblyTargetInfo::BuiltinInfo[] = {
7847 #define BUILTIN(ID, TYPE, ATTRS) \
7848   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
7849 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
7850   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
7851 #include "clang/Basic/BuiltinsWebAssembly.def"
7852 };
7853 
7854 class WebAssembly32TargetInfo : public WebAssemblyTargetInfo {
7855 public:
WebAssembly32TargetInfo(const llvm::Triple & T,const TargetOptions & Opts)7856   explicit WebAssembly32TargetInfo(const llvm::Triple &T,
7857                                    const TargetOptions &Opts)
7858       : WebAssemblyTargetInfo(T, Opts) {
7859     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32;
7860     resetDataLayout("e-m:e-p:32:32-i64:64-n32:64-S128");
7861   }
7862 
7863 protected:
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7864   void getTargetDefines(const LangOptions &Opts,
7865                         MacroBuilder &Builder) const override {
7866     WebAssemblyTargetInfo::getTargetDefines(Opts, Builder);
7867     defineCPUMacros(Builder, "wasm32", /*Tuning=*/false);
7868   }
7869 };
7870 
7871 class WebAssembly64TargetInfo : public WebAssemblyTargetInfo {
7872 public:
WebAssembly64TargetInfo(const llvm::Triple & T,const TargetOptions & Opts)7873   explicit WebAssembly64TargetInfo(const llvm::Triple &T,
7874                                    const TargetOptions &Opts)
7875       : WebAssemblyTargetInfo(T, Opts) {
7876     LongAlign = LongWidth = 64;
7877     PointerAlign = PointerWidth = 64;
7878     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
7879     resetDataLayout("e-m:e-p:64:64-i64:64-n32:64-S128");
7880   }
7881 
7882 protected:
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7883   void getTargetDefines(const LangOptions &Opts,
7884                         MacroBuilder &Builder) const override {
7885     WebAssemblyTargetInfo::getTargetDefines(Opts, Builder);
7886     defineCPUMacros(Builder, "wasm64", /*Tuning=*/false);
7887   }
7888 };
7889 
7890 const Builtin::Info Le64TargetInfo::BuiltinInfo[] = {
7891 #define BUILTIN(ID, TYPE, ATTRS)                                               \
7892   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
7893 #include "clang/Basic/BuiltinsLe64.def"
7894 };
7895 
7896 static const unsigned SPIRAddrSpaceMap[] = {
7897     1, // opencl_global
7898     3, // opencl_local
7899     2, // opencl_constant
7900     4, // opencl_generic
7901     0, // cuda_device
7902     0, // cuda_constant
7903     0  // cuda_shared
7904 };
7905 class SPIRTargetInfo : public TargetInfo {
7906 public:
SPIRTargetInfo(const llvm::Triple & Triple,const TargetOptions &)7907   SPIRTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
7908       : TargetInfo(Triple) {
7909     assert(getTriple().getOS() == llvm::Triple::UnknownOS &&
7910            "SPIR target must use unknown OS");
7911     assert(getTriple().getEnvironment() == llvm::Triple::UnknownEnvironment &&
7912            "SPIR target must use unknown environment type");
7913     BigEndian = false;
7914     TLSSupported = false;
7915     LongWidth = LongAlign = 64;
7916     AddrSpaceMap = &SPIRAddrSpaceMap;
7917     UseAddrSpaceMapMangling = true;
7918     // Define available target features
7919     // These must be defined in sorted order!
7920     NoAsmVariants = true;
7921   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7922   void getTargetDefines(const LangOptions &Opts,
7923                         MacroBuilder &Builder) const override {
7924     DefineStd(Builder, "SPIR", Opts);
7925   }
hasFeature(StringRef Feature) const7926   bool hasFeature(StringRef Feature) const override {
7927     return Feature == "spir";
7928   }
7929 
getTargetBuiltins() const7930   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
getClobbers() const7931   const char *getClobbers() const override { return ""; }
getGCCRegNames() const7932   ArrayRef<const char *> getGCCRegNames() const override { return None; }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const7933   bool validateAsmConstraint(const char *&Name,
7934                              TargetInfo::ConstraintInfo &info) const override {
7935     return true;
7936   }
getGCCRegAliases() const7937   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
7938     return None;
7939   }
getBuiltinVaListKind() const7940   BuiltinVaListKind getBuiltinVaListKind() const override {
7941     return TargetInfo::VoidPtrBuiltinVaList;
7942   }
7943 
checkCallingConvention(CallingConv CC) const7944   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
7945     return (CC == CC_SpirFunction || CC == CC_OpenCLKernel) ? CCCR_OK
7946                                                             : CCCR_Warning;
7947   }
7948 
getDefaultCallingConv(CallingConvMethodType MT) const7949   CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override {
7950     return CC_SpirFunction;
7951   }
7952 
setSupportedOpenCLOpts()7953   void setSupportedOpenCLOpts() override {
7954     // Assume all OpenCL extensions and optional core features are supported
7955     // for SPIR since it is a generic target.
7956     getSupportedOpenCLOpts().setAll();
7957   }
7958 };
7959 
7960 class SPIR32TargetInfo : public SPIRTargetInfo {
7961 public:
SPIR32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)7962   SPIR32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
7963       : SPIRTargetInfo(Triple, Opts) {
7964     PointerWidth = PointerAlign = 32;
7965     SizeType = TargetInfo::UnsignedInt;
7966     PtrDiffType = IntPtrType = TargetInfo::SignedInt;
7967     resetDataLayout("e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-"
7968                     "v96:128-v192:256-v256:256-v512:512-v1024:1024");
7969   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7970   void getTargetDefines(const LangOptions &Opts,
7971                         MacroBuilder &Builder) const override {
7972     DefineStd(Builder, "SPIR32", Opts);
7973   }
7974 };
7975 
7976 class SPIR64TargetInfo : public SPIRTargetInfo {
7977 public:
SPIR64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)7978   SPIR64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
7979       : SPIRTargetInfo(Triple, Opts) {
7980     PointerWidth = PointerAlign = 64;
7981     SizeType = TargetInfo::UnsignedLong;
7982     PtrDiffType = IntPtrType = TargetInfo::SignedLong;
7983     resetDataLayout("e-i64:64-v16:16-v24:32-v32:32-v48:64-"
7984                     "v96:128-v192:256-v256:256-v512:512-v1024:1024");
7985   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7986   void getTargetDefines(const LangOptions &Opts,
7987                         MacroBuilder &Builder) const override {
7988     DefineStd(Builder, "SPIR64", Opts);
7989   }
7990 };
7991 
7992 class XCoreTargetInfo : public TargetInfo {
7993   static const Builtin::Info BuiltinInfo[];
7994 public:
XCoreTargetInfo(const llvm::Triple & Triple,const TargetOptions &)7995   XCoreTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
7996       : TargetInfo(Triple) {
7997     BigEndian = false;
7998     NoAsmVariants = true;
7999     LongLongAlign = 32;
8000     SuitableAlign = 32;
8001     DoubleAlign = LongDoubleAlign = 32;
8002     SizeType = UnsignedInt;
8003     PtrDiffType = SignedInt;
8004     IntPtrType = SignedInt;
8005     WCharType = UnsignedChar;
8006     WIntType = UnsignedInt;
8007     UseZeroLengthBitfieldAlignment = true;
8008     resetDataLayout("e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i64:32"
8009                     "-f64:32-a:0:32-n32");
8010   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const8011   void getTargetDefines(const LangOptions &Opts,
8012                         MacroBuilder &Builder) const override {
8013     Builder.defineMacro("__XS1B__");
8014   }
getTargetBuiltins() const8015   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
8016     return llvm::makeArrayRef(BuiltinInfo,
8017                            clang::XCore::LastTSBuiltin-Builtin::FirstTSBuiltin);
8018   }
getBuiltinVaListKind() const8019   BuiltinVaListKind getBuiltinVaListKind() const override {
8020     return TargetInfo::VoidPtrBuiltinVaList;
8021   }
getClobbers() const8022   const char *getClobbers() const override {
8023     return "";
8024   }
getGCCRegNames() const8025   ArrayRef<const char *> getGCCRegNames() const override {
8026     static const char * const GCCRegNames[] = {
8027       "r0",   "r1",   "r2",   "r3",   "r4",   "r5",   "r6",   "r7",
8028       "r8",   "r9",   "r10",  "r11",  "cp",   "dp",   "sp",   "lr"
8029     };
8030     return llvm::makeArrayRef(GCCRegNames);
8031   }
getGCCRegAliases() const8032   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
8033     return None;
8034   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const8035   bool validateAsmConstraint(const char *&Name,
8036                              TargetInfo::ConstraintInfo &Info) const override {
8037     return false;
8038   }
getEHDataRegisterNumber(unsigned RegNo) const8039   int getEHDataRegisterNumber(unsigned RegNo) const override {
8040     // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
8041     return (RegNo < 2)? RegNo : -1;
8042   }
allowsLargerPreferedTypeAlignment() const8043   bool allowsLargerPreferedTypeAlignment() const override {
8044     return false;
8045   }
8046 };
8047 
8048 const Builtin::Info XCoreTargetInfo::BuiltinInfo[] = {
8049 #define BUILTIN(ID, TYPE, ATTRS) \
8050   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
8051 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
8052   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
8053 #include "clang/Basic/BuiltinsXCore.def"
8054 };
8055 
8056 // x86_32 Android target
8057 class AndroidX86_32TargetInfo : public LinuxTargetInfo<X86_32TargetInfo> {
8058 public:
AndroidX86_32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)8059   AndroidX86_32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
8060       : LinuxTargetInfo<X86_32TargetInfo>(Triple, Opts) {
8061     SuitableAlign = 32;
8062     LongDoubleWidth = 64;
8063     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
8064   }
8065 };
8066 
8067 // x86_64 Android target
8068 class AndroidX86_64TargetInfo : public LinuxTargetInfo<X86_64TargetInfo> {
8069 public:
AndroidX86_64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)8070   AndroidX86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
8071       : LinuxTargetInfo<X86_64TargetInfo>(Triple, Opts) {
8072     LongDoubleFormat = &llvm::APFloat::IEEEquad;
8073   }
8074 
useFloat128ManglingForLongDouble() const8075   bool useFloat128ManglingForLongDouble() const override {
8076     return true;
8077   }
8078 };
8079 
8080 // 32-bit RenderScript is armv7 with width and align of 'long' set to 8-bytes
8081 class RenderScript32TargetInfo : public ARMleTargetInfo {
8082 public:
RenderScript32TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)8083   RenderScript32TargetInfo(const llvm::Triple &Triple,
8084                            const TargetOptions &Opts)
8085       : ARMleTargetInfo(llvm::Triple("armv7", Triple.getVendorName(),
8086                                      Triple.getOSName(),
8087                                      Triple.getEnvironmentName()),
8088                         Opts) {
8089     IsRenderScriptTarget = true;
8090     LongWidth = LongAlign = 64;
8091   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const8092   void getTargetDefines(const LangOptions &Opts,
8093                         MacroBuilder &Builder) const override {
8094     Builder.defineMacro("__RENDERSCRIPT__");
8095     ARMleTargetInfo::getTargetDefines(Opts, Builder);
8096   }
8097 };
8098 
8099 // 64-bit RenderScript is aarch64
8100 class RenderScript64TargetInfo : public AArch64leTargetInfo {
8101 public:
RenderScript64TargetInfo(const llvm::Triple & Triple,const TargetOptions & Opts)8102   RenderScript64TargetInfo(const llvm::Triple &Triple,
8103                            const TargetOptions &Opts)
8104       : AArch64leTargetInfo(llvm::Triple("aarch64", Triple.getVendorName(),
8105                                          Triple.getOSName(),
8106                                          Triple.getEnvironmentName()),
8107                             Opts) {
8108     IsRenderScriptTarget = true;
8109   }
8110 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const8111   void getTargetDefines(const LangOptions &Opts,
8112                         MacroBuilder &Builder) const override {
8113     Builder.defineMacro("__RENDERSCRIPT__");
8114     AArch64leTargetInfo::getTargetDefines(Opts, Builder);
8115   }
8116 };
8117 
8118 } // end anonymous namespace
8119 
8120 //===----------------------------------------------------------------------===//
8121 // Driver code
8122 //===----------------------------------------------------------------------===//
8123 
AllocateTarget(const llvm::Triple & Triple,const TargetOptions & Opts)8124 static TargetInfo *AllocateTarget(const llvm::Triple &Triple,
8125                                   const TargetOptions &Opts) {
8126   llvm::Triple::OSType os = Triple.getOS();
8127 
8128   switch (Triple.getArch()) {
8129   default:
8130     return nullptr;
8131 
8132   case llvm::Triple::xcore:
8133     return new XCoreTargetInfo(Triple, Opts);
8134 
8135   case llvm::Triple::hexagon:
8136     return new HexagonTargetInfo(Triple, Opts);
8137 
8138   case llvm::Triple::lanai:
8139     return new LanaiTargetInfo(Triple, Opts);
8140 
8141   case llvm::Triple::aarch64:
8142     if (Triple.isOSDarwin())
8143       return new DarwinAArch64TargetInfo(Triple, Opts);
8144 
8145     switch (os) {
8146     case llvm::Triple::CloudABI:
8147       return new CloudABITargetInfo<AArch64leTargetInfo>(Triple, Opts);
8148     case llvm::Triple::FreeBSD:
8149       return new FreeBSDTargetInfo<AArch64leTargetInfo>(Triple, Opts);
8150     case llvm::Triple::Linux:
8151       return new LinuxTargetInfo<AArch64leTargetInfo>(Triple, Opts);
8152     case llvm::Triple::NetBSD:
8153       return new NetBSDTargetInfo<AArch64leTargetInfo>(Triple, Opts);
8154     default:
8155       return new AArch64leTargetInfo(Triple, Opts);
8156     }
8157 
8158   case llvm::Triple::aarch64_be:
8159     switch (os) {
8160     case llvm::Triple::FreeBSD:
8161       return new FreeBSDTargetInfo<AArch64beTargetInfo>(Triple, Opts);
8162     case llvm::Triple::Linux:
8163       return new LinuxTargetInfo<AArch64beTargetInfo>(Triple, Opts);
8164     case llvm::Triple::NetBSD:
8165       return new NetBSDTargetInfo<AArch64beTargetInfo>(Triple, Opts);
8166     default:
8167       return new AArch64beTargetInfo(Triple, Opts);
8168     }
8169 
8170   case llvm::Triple::arm:
8171   case llvm::Triple::thumb:
8172     if (Triple.isOSBinFormatMachO())
8173       return new DarwinARMTargetInfo(Triple, Opts);
8174 
8175     switch (os) {
8176     case llvm::Triple::Linux:
8177       return new LinuxTargetInfo<ARMleTargetInfo>(Triple, Opts);
8178     case llvm::Triple::FreeBSD:
8179       return new FreeBSDTargetInfo<ARMleTargetInfo>(Triple, Opts);
8180     case llvm::Triple::NetBSD:
8181       return new NetBSDTargetInfo<ARMleTargetInfo>(Triple, Opts);
8182     case llvm::Triple::OpenBSD:
8183       return new OpenBSDTargetInfo<ARMleTargetInfo>(Triple, Opts);
8184     case llvm::Triple::Bitrig:
8185       return new BitrigTargetInfo<ARMleTargetInfo>(Triple, Opts);
8186     case llvm::Triple::RTEMS:
8187       return new RTEMSTargetInfo<ARMleTargetInfo>(Triple, Opts);
8188     case llvm::Triple::NaCl:
8189       return new NaClTargetInfo<ARMleTargetInfo>(Triple, Opts);
8190     case llvm::Triple::Win32:
8191       switch (Triple.getEnvironment()) {
8192       case llvm::Triple::Cygnus:
8193         return new CygwinARMTargetInfo(Triple, Opts);
8194       case llvm::Triple::GNU:
8195         return new MinGWARMTargetInfo(Triple, Opts);
8196       case llvm::Triple::Itanium:
8197         return new ItaniumWindowsARMleTargetInfo(Triple, Opts);
8198       case llvm::Triple::MSVC:
8199       default: // Assume MSVC for unknown environments
8200         return new MicrosoftARMleTargetInfo(Triple, Opts);
8201       }
8202     default:
8203       return new ARMleTargetInfo(Triple, Opts);
8204     }
8205 
8206   case llvm::Triple::armeb:
8207   case llvm::Triple::thumbeb:
8208     if (Triple.isOSDarwin())
8209       return new DarwinARMTargetInfo(Triple, Opts);
8210 
8211     switch (os) {
8212     case llvm::Triple::Linux:
8213       return new LinuxTargetInfo<ARMbeTargetInfo>(Triple, Opts);
8214     case llvm::Triple::FreeBSD:
8215       return new FreeBSDTargetInfo<ARMbeTargetInfo>(Triple, Opts);
8216     case llvm::Triple::NetBSD:
8217       return new NetBSDTargetInfo<ARMbeTargetInfo>(Triple, Opts);
8218     case llvm::Triple::OpenBSD:
8219       return new OpenBSDTargetInfo<ARMbeTargetInfo>(Triple, Opts);
8220     case llvm::Triple::Bitrig:
8221       return new BitrigTargetInfo<ARMbeTargetInfo>(Triple, Opts);
8222     case llvm::Triple::RTEMS:
8223       return new RTEMSTargetInfo<ARMbeTargetInfo>(Triple, Opts);
8224     case llvm::Triple::NaCl:
8225       return new NaClTargetInfo<ARMbeTargetInfo>(Triple, Opts);
8226     default:
8227       return new ARMbeTargetInfo(Triple, Opts);
8228     }
8229 
8230   case llvm::Triple::bpfeb:
8231   case llvm::Triple::bpfel:
8232     return new BPFTargetInfo(Triple, Opts);
8233 
8234   case llvm::Triple::msp430:
8235     return new MSP430TargetInfo(Triple, Opts);
8236 
8237   case llvm::Triple::mips:
8238     switch (os) {
8239     case llvm::Triple::Linux:
8240       return new LinuxTargetInfo<MipsTargetInfo>(Triple, Opts);
8241     case llvm::Triple::RTEMS:
8242       return new RTEMSTargetInfo<MipsTargetInfo>(Triple, Opts);
8243     case llvm::Triple::FreeBSD:
8244       return new FreeBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8245     case llvm::Triple::NetBSD:
8246       return new NetBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8247     default:
8248       return new MipsTargetInfo(Triple, Opts);
8249     }
8250 
8251   case llvm::Triple::mipsel:
8252     switch (os) {
8253     case llvm::Triple::Linux:
8254       return new LinuxTargetInfo<MipsTargetInfo>(Triple, Opts);
8255     case llvm::Triple::RTEMS:
8256       return new RTEMSTargetInfo<MipsTargetInfo>(Triple, Opts);
8257     case llvm::Triple::FreeBSD:
8258       return new FreeBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8259     case llvm::Triple::NetBSD:
8260       return new NetBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8261     case llvm::Triple::NaCl:
8262       return new NaClTargetInfo<NaClMips32TargetInfo>(Triple, Opts);
8263     default:
8264       return new MipsTargetInfo(Triple, Opts);
8265     }
8266 
8267   case llvm::Triple::mips64:
8268     switch (os) {
8269     case llvm::Triple::Linux:
8270       return new LinuxTargetInfo<MipsTargetInfo>(Triple, Opts);
8271     case llvm::Triple::RTEMS:
8272       return new RTEMSTargetInfo<MipsTargetInfo>(Triple, Opts);
8273     case llvm::Triple::FreeBSD:
8274       return new FreeBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8275     case llvm::Triple::NetBSD:
8276       return new NetBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8277     case llvm::Triple::OpenBSD:
8278       return new OpenBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8279     default:
8280       return new MipsTargetInfo(Triple, Opts);
8281     }
8282 
8283   case llvm::Triple::mips64el:
8284     switch (os) {
8285     case llvm::Triple::Linux:
8286       return new LinuxTargetInfo<MipsTargetInfo>(Triple, Opts);
8287     case llvm::Triple::RTEMS:
8288       return new RTEMSTargetInfo<MipsTargetInfo>(Triple, Opts);
8289     case llvm::Triple::FreeBSD:
8290       return new FreeBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8291     case llvm::Triple::NetBSD:
8292       return new NetBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8293     case llvm::Triple::OpenBSD:
8294       return new OpenBSDTargetInfo<MipsTargetInfo>(Triple, Opts);
8295     default:
8296       return new MipsTargetInfo(Triple, Opts);
8297     }
8298 
8299   case llvm::Triple::le32:
8300     switch (os) {
8301     case llvm::Triple::NaCl:
8302       return new NaClTargetInfo<PNaClTargetInfo>(Triple, Opts);
8303     default:
8304       return nullptr;
8305     }
8306 
8307   case llvm::Triple::le64:
8308     return new Le64TargetInfo(Triple, Opts);
8309 
8310   case llvm::Triple::ppc:
8311     if (Triple.isOSDarwin())
8312       return new DarwinPPC32TargetInfo(Triple, Opts);
8313     switch (os) {
8314     case llvm::Triple::Linux:
8315       return new LinuxTargetInfo<PPC32TargetInfo>(Triple, Opts);
8316     case llvm::Triple::FreeBSD:
8317       return new FreeBSDTargetInfo<PPC32TargetInfo>(Triple, Opts);
8318     case llvm::Triple::NetBSD:
8319       return new NetBSDTargetInfo<PPC32TargetInfo>(Triple, Opts);
8320     case llvm::Triple::OpenBSD:
8321       return new OpenBSDTargetInfo<PPC32TargetInfo>(Triple, Opts);
8322     case llvm::Triple::RTEMS:
8323       return new RTEMSTargetInfo<PPC32TargetInfo>(Triple, Opts);
8324     default:
8325       return new PPC32TargetInfo(Triple, Opts);
8326     }
8327 
8328   case llvm::Triple::ppc64:
8329     if (Triple.isOSDarwin())
8330       return new DarwinPPC64TargetInfo(Triple, Opts);
8331     switch (os) {
8332     case llvm::Triple::Linux:
8333       return new LinuxTargetInfo<PPC64TargetInfo>(Triple, Opts);
8334     case llvm::Triple::Lv2:
8335       return new PS3PPUTargetInfo<PPC64TargetInfo>(Triple, Opts);
8336     case llvm::Triple::FreeBSD:
8337       return new FreeBSDTargetInfo<PPC64TargetInfo>(Triple, Opts);
8338     case llvm::Triple::NetBSD:
8339       return new NetBSDTargetInfo<PPC64TargetInfo>(Triple, Opts);
8340     default:
8341       return new PPC64TargetInfo(Triple, Opts);
8342     }
8343 
8344   case llvm::Triple::ppc64le:
8345     switch (os) {
8346     case llvm::Triple::Linux:
8347       return new LinuxTargetInfo<PPC64TargetInfo>(Triple, Opts);
8348     case llvm::Triple::NetBSD:
8349       return new NetBSDTargetInfo<PPC64TargetInfo>(Triple, Opts);
8350     default:
8351       return new PPC64TargetInfo(Triple, Opts);
8352     }
8353 
8354   case llvm::Triple::nvptx:
8355     return new NVPTX32TargetInfo(Triple, Opts);
8356   case llvm::Triple::nvptx64:
8357     return new NVPTX64TargetInfo(Triple, Opts);
8358 
8359   case llvm::Triple::amdgcn:
8360   case llvm::Triple::r600:
8361     return new AMDGPUTargetInfo(Triple, Opts);
8362 
8363   case llvm::Triple::sparc:
8364     switch (os) {
8365     case llvm::Triple::Linux:
8366       return new LinuxTargetInfo<SparcV8TargetInfo>(Triple, Opts);
8367     case llvm::Triple::Solaris:
8368       return new SolarisTargetInfo<SparcV8TargetInfo>(Triple, Opts);
8369     case llvm::Triple::NetBSD:
8370       return new NetBSDTargetInfo<SparcV8TargetInfo>(Triple, Opts);
8371     case llvm::Triple::OpenBSD:
8372       return new OpenBSDTargetInfo<SparcV8TargetInfo>(Triple, Opts);
8373     case llvm::Triple::RTEMS:
8374       return new RTEMSTargetInfo<SparcV8TargetInfo>(Triple, Opts);
8375     default:
8376       return new SparcV8TargetInfo(Triple, Opts);
8377     }
8378 
8379   // The 'sparcel' architecture copies all the above cases except for Solaris.
8380   case llvm::Triple::sparcel:
8381     switch (os) {
8382     case llvm::Triple::Linux:
8383       return new LinuxTargetInfo<SparcV8elTargetInfo>(Triple, Opts);
8384     case llvm::Triple::NetBSD:
8385       return new NetBSDTargetInfo<SparcV8elTargetInfo>(Triple, Opts);
8386     case llvm::Triple::OpenBSD:
8387       return new OpenBSDTargetInfo<SparcV8elTargetInfo>(Triple, Opts);
8388     case llvm::Triple::RTEMS:
8389       return new RTEMSTargetInfo<SparcV8elTargetInfo>(Triple, Opts);
8390     default:
8391       return new SparcV8elTargetInfo(Triple, Opts);
8392     }
8393 
8394   case llvm::Triple::sparcv9:
8395     switch (os) {
8396     case llvm::Triple::Linux:
8397       return new LinuxTargetInfo<SparcV9TargetInfo>(Triple, Opts);
8398     case llvm::Triple::Solaris:
8399       return new SolarisTargetInfo<SparcV9TargetInfo>(Triple, Opts);
8400     case llvm::Triple::NetBSD:
8401       return new NetBSDTargetInfo<SparcV9TargetInfo>(Triple, Opts);
8402     case llvm::Triple::OpenBSD:
8403       return new OpenBSDTargetInfo<SparcV9TargetInfo>(Triple, Opts);
8404     case llvm::Triple::FreeBSD:
8405       return new FreeBSDTargetInfo<SparcV9TargetInfo>(Triple, Opts);
8406     default:
8407       return new SparcV9TargetInfo(Triple, Opts);
8408     }
8409 
8410   case llvm::Triple::systemz:
8411     switch (os) {
8412     case llvm::Triple::Linux:
8413       return new LinuxTargetInfo<SystemZTargetInfo>(Triple, Opts);
8414     default:
8415       return new SystemZTargetInfo(Triple, Opts);
8416     }
8417 
8418   case llvm::Triple::tce:
8419     return new TCETargetInfo(Triple, Opts);
8420 
8421   case llvm::Triple::x86:
8422     if (Triple.isOSDarwin())
8423       return new DarwinI386TargetInfo(Triple, Opts);
8424 
8425     switch (os) {
8426     case llvm::Triple::CloudABI:
8427       return new CloudABITargetInfo<X86_32TargetInfo>(Triple, Opts);
8428     case llvm::Triple::Linux: {
8429       switch (Triple.getEnvironment()) {
8430       default:
8431         return new LinuxTargetInfo<X86_32TargetInfo>(Triple, Opts);
8432       case llvm::Triple::Android:
8433         return new AndroidX86_32TargetInfo(Triple, Opts);
8434       }
8435     }
8436     case llvm::Triple::DragonFly:
8437       return new DragonFlyBSDTargetInfo<X86_32TargetInfo>(Triple, Opts);
8438     case llvm::Triple::NetBSD:
8439       return new NetBSDI386TargetInfo(Triple, Opts);
8440     case llvm::Triple::OpenBSD:
8441       return new OpenBSDI386TargetInfo(Triple, Opts);
8442     case llvm::Triple::Bitrig:
8443       return new BitrigI386TargetInfo(Triple, Opts);
8444     case llvm::Triple::FreeBSD:
8445       return new FreeBSDTargetInfo<X86_32TargetInfo>(Triple, Opts);
8446     case llvm::Triple::KFreeBSD:
8447       return new KFreeBSDTargetInfo<X86_32TargetInfo>(Triple, Opts);
8448     case llvm::Triple::Minix:
8449       return new MinixTargetInfo<X86_32TargetInfo>(Triple, Opts);
8450     case llvm::Triple::Solaris:
8451       return new SolarisTargetInfo<X86_32TargetInfo>(Triple, Opts);
8452     case llvm::Triple::Win32: {
8453       switch (Triple.getEnvironment()) {
8454       case llvm::Triple::Cygnus:
8455         return new CygwinX86_32TargetInfo(Triple, Opts);
8456       case llvm::Triple::GNU:
8457         return new MinGWX86_32TargetInfo(Triple, Opts);
8458       case llvm::Triple::Itanium:
8459       case llvm::Triple::MSVC:
8460       default: // Assume MSVC for unknown environments
8461         return new MicrosoftX86_32TargetInfo(Triple, Opts);
8462       }
8463     }
8464     case llvm::Triple::Haiku:
8465       return new HaikuX86_32TargetInfo(Triple, Opts);
8466     case llvm::Triple::RTEMS:
8467       return new RTEMSX86_32TargetInfo(Triple, Opts);
8468     case llvm::Triple::NaCl:
8469       return new NaClTargetInfo<X86_32TargetInfo>(Triple, Opts);
8470     case llvm::Triple::ELFIAMCU:
8471       return new MCUX86_32TargetInfo(Triple, Opts);
8472     default:
8473       return new X86_32TargetInfo(Triple, Opts);
8474     }
8475 
8476   case llvm::Triple::x86_64:
8477     if (Triple.isOSDarwin() || Triple.isOSBinFormatMachO())
8478       return new DarwinX86_64TargetInfo(Triple, Opts);
8479 
8480     switch (os) {
8481     case llvm::Triple::CloudABI:
8482       return new CloudABITargetInfo<X86_64TargetInfo>(Triple, Opts);
8483     case llvm::Triple::Linux: {
8484       switch (Triple.getEnvironment()) {
8485       default:
8486         return new LinuxTargetInfo<X86_64TargetInfo>(Triple, Opts);
8487       case llvm::Triple::Android:
8488         return new AndroidX86_64TargetInfo(Triple, Opts);
8489       }
8490     }
8491     case llvm::Triple::DragonFly:
8492       return new DragonFlyBSDTargetInfo<X86_64TargetInfo>(Triple, Opts);
8493     case llvm::Triple::NetBSD:
8494       return new NetBSDTargetInfo<X86_64TargetInfo>(Triple, Opts);
8495     case llvm::Triple::OpenBSD:
8496       return new OpenBSDX86_64TargetInfo(Triple, Opts);
8497     case llvm::Triple::Bitrig:
8498       return new BitrigX86_64TargetInfo(Triple, Opts);
8499     case llvm::Triple::FreeBSD:
8500       return new FreeBSDTargetInfo<X86_64TargetInfo>(Triple, Opts);
8501     case llvm::Triple::KFreeBSD:
8502       return new KFreeBSDTargetInfo<X86_64TargetInfo>(Triple, Opts);
8503     case llvm::Triple::Solaris:
8504       return new SolarisTargetInfo<X86_64TargetInfo>(Triple, Opts);
8505     case llvm::Triple::Win32: {
8506       switch (Triple.getEnvironment()) {
8507       case llvm::Triple::Cygnus:
8508         return new CygwinX86_64TargetInfo(Triple, Opts);
8509       case llvm::Triple::GNU:
8510         return new MinGWX86_64TargetInfo(Triple, Opts);
8511       case llvm::Triple::MSVC:
8512       default: // Assume MSVC for unknown environments
8513         return new MicrosoftX86_64TargetInfo(Triple, Opts);
8514       }
8515     }
8516     case llvm::Triple::Haiku:
8517       return new HaikuTargetInfo<X86_64TargetInfo>(Triple, Opts);
8518     case llvm::Triple::NaCl:
8519       return new NaClTargetInfo<X86_64TargetInfo>(Triple, Opts);
8520     case llvm::Triple::PS4:
8521       return new PS4OSTargetInfo<X86_64TargetInfo>(Triple, Opts);
8522     default:
8523       return new X86_64TargetInfo(Triple, Opts);
8524     }
8525 
8526   case llvm::Triple::spir: {
8527     if (Triple.getOS() != llvm::Triple::UnknownOS ||
8528         Triple.getEnvironment() != llvm::Triple::UnknownEnvironment)
8529       return nullptr;
8530     return new SPIR32TargetInfo(Triple, Opts);
8531   }
8532   case llvm::Triple::spir64: {
8533     if (Triple.getOS() != llvm::Triple::UnknownOS ||
8534         Triple.getEnvironment() != llvm::Triple::UnknownEnvironment)
8535       return nullptr;
8536     return new SPIR64TargetInfo(Triple, Opts);
8537   }
8538   case llvm::Triple::wasm32:
8539     if (!(Triple == llvm::Triple("wasm32-unknown-unknown")))
8540       return nullptr;
8541     return new WebAssemblyOSTargetInfo<WebAssembly32TargetInfo>(Triple, Opts);
8542   case llvm::Triple::wasm64:
8543     if (!(Triple == llvm::Triple("wasm64-unknown-unknown")))
8544       return nullptr;
8545     return new WebAssemblyOSTargetInfo<WebAssembly64TargetInfo>(Triple, Opts);
8546 
8547   case llvm::Triple::renderscript32:
8548     return new LinuxTargetInfo<RenderScript32TargetInfo>(Triple, Opts);
8549   case llvm::Triple::renderscript64:
8550     return new LinuxTargetInfo<RenderScript64TargetInfo>(Triple, Opts);
8551   }
8552 }
8553 
8554 /// CreateTargetInfo - Return the target info object for the specified target
8555 /// options.
8556 TargetInfo *
CreateTargetInfo(DiagnosticsEngine & Diags,const std::shared_ptr<TargetOptions> & Opts)8557 TargetInfo::CreateTargetInfo(DiagnosticsEngine &Diags,
8558                              const std::shared_ptr<TargetOptions> &Opts) {
8559   llvm::Triple Triple(Opts->Triple);
8560 
8561   // Construct the target
8562   std::unique_ptr<TargetInfo> Target(AllocateTarget(Triple, *Opts));
8563   if (!Target) {
8564     Diags.Report(diag::err_target_unknown_triple) << Triple.str();
8565     return nullptr;
8566   }
8567   Target->TargetOpts = Opts;
8568 
8569   // Set the target CPU if specified.
8570   if (!Opts->CPU.empty() && !Target->setCPU(Opts->CPU)) {
8571     Diags.Report(diag::err_target_unknown_cpu) << Opts->CPU;
8572     return nullptr;
8573   }
8574 
8575   // Set the target ABI if specified.
8576   if (!Opts->ABI.empty() && !Target->setABI(Opts->ABI)) {
8577     Diags.Report(diag::err_target_unknown_abi) << Opts->ABI;
8578     return nullptr;
8579   }
8580 
8581   // Set the fp math unit.
8582   if (!Opts->FPMath.empty() && !Target->setFPMath(Opts->FPMath)) {
8583     Diags.Report(diag::err_target_unknown_fpmath) << Opts->FPMath;
8584     return nullptr;
8585   }
8586 
8587   // Compute the default target features, we need the target to handle this
8588   // because features may have dependencies on one another.
8589   llvm::StringMap<bool> Features;
8590   if (!Target->initFeatureMap(Features, Diags, Opts->CPU,
8591                               Opts->FeaturesAsWritten))
8592       return nullptr;
8593 
8594   // Add the features to the compile options.
8595   Opts->Features.clear();
8596   for (const auto &F : Features)
8597     Opts->Features.push_back((F.getValue() ? "+" : "-") + F.getKey().str());
8598 
8599   if (!Target->handleTargetFeatures(Opts->Features, Diags))
8600     return nullptr;
8601 
8602   Target->setSupportedOpenCLOpts();
8603 
8604   if (!Target->validateTarget(Diags))
8605     return nullptr;
8606 
8607   return Target.release();
8608 }
8609