[ARM] Reject invalid -march values
[oota-llvm.git] / lib / Support / Triple.cpp
1 //===--- Triple.cpp - Target triple helper class --------------------------===//
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 #include "llvm/ADT/Triple.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/Support/ErrorHandling.h"
15 #include <cstring>
16 using namespace llvm;
17
18 const char *Triple::getArchTypeName(ArchType Kind) {
19   switch (Kind) {
20   case UnknownArch: return "unknown";
21
22   case aarch64:     return "aarch64";
23   case aarch64_be:  return "aarch64_be";
24   case arm:         return "arm";
25   case armeb:       return "armeb";
26   case bpf:         return "bpf";
27   case hexagon:     return "hexagon";
28   case mips:        return "mips";
29   case mipsel:      return "mipsel";
30   case mips64:      return "mips64";
31   case mips64el:    return "mips64el";
32   case msp430:      return "msp430";
33   case ppc64:       return "powerpc64";
34   case ppc64le:     return "powerpc64le";
35   case ppc:         return "powerpc";
36   case r600:        return "r600";
37   case amdgcn:      return "amdgcn";
38   case sparc:       return "sparc";
39   case sparcv9:     return "sparcv9";
40   case sparcel:     return "sparcel";
41   case systemz:     return "s390x";
42   case tce:         return "tce";
43   case thumb:       return "thumb";
44   case thumbeb:     return "thumbeb";
45   case x86:         return "i386";
46   case x86_64:      return "x86_64";
47   case xcore:       return "xcore";
48   case nvptx:       return "nvptx";
49   case nvptx64:     return "nvptx64";
50   case le32:        return "le32";
51   case le64:        return "le64";
52   case amdil:       return "amdil";
53   case amdil64:     return "amdil64";
54   case hsail:       return "hsail";
55   case hsail64:     return "hsail64";
56   case spir:        return "spir";
57   case spir64:      return "spir64";
58   case kalimba:     return "kalimba";
59   }
60
61   llvm_unreachable("Invalid ArchType!");
62 }
63
64 const char *Triple::getArchTypePrefix(ArchType Kind) {
65   switch (Kind) {
66   default:
67     return nullptr;
68
69   case aarch64:
70   case aarch64_be:  return "aarch64";
71
72   case arm:
73   case armeb:
74   case thumb:
75   case thumbeb:     return "arm";
76
77   case ppc64:
78   case ppc64le:
79   case ppc:         return "ppc";
80
81   case mips:
82   case mipsel:
83   case mips64:
84   case mips64el:    return "mips";
85
86   case hexagon:     return "hexagon";
87
88   case amdgcn:
89   case r600:        return "amdgpu";
90
91   case bpf:         return "bpf";
92
93   case sparcv9:
94   case sparcel:
95   case sparc:       return "sparc";
96
97   case systemz:     return "s390";
98
99   case x86:
100   case x86_64:      return "x86";
101
102   case xcore:       return "xcore";
103
104   case nvptx:       return "nvptx";
105   case nvptx64:     return "nvptx";
106
107   case le32:        return "le32";
108   case le64:        return "le64";
109
110   case amdil:
111   case amdil64:     return "amdil";
112
113   case hsail:
114   case hsail64:     return "hsail";
115
116   case spir:
117   case spir64:      return "spir";
118   case kalimba:     return "kalimba";
119   }
120 }
121
122 const char *Triple::getVendorTypeName(VendorType Kind) {
123   switch (Kind) {
124   case UnknownVendor: return "unknown";
125
126   case Apple: return "apple";
127   case PC: return "pc";
128   case SCEI: return "scei";
129   case BGP: return "bgp";
130   case BGQ: return "bgq";
131   case Freescale: return "fsl";
132   case IBM: return "ibm";
133   case ImaginationTechnologies: return "img";
134   case MipsTechnologies: return "mti";
135   case NVIDIA: return "nvidia";
136   case CSR: return "csr";
137   }
138
139   llvm_unreachable("Invalid VendorType!");
140 }
141
142 const char *Triple::getOSTypeName(OSType Kind) {
143   switch (Kind) {
144   case UnknownOS: return "unknown";
145
146   case CloudABI: return "cloudabi";
147   case Darwin: return "darwin";
148   case DragonFly: return "dragonfly";
149   case FreeBSD: return "freebsd";
150   case IOS: return "ios";
151   case KFreeBSD: return "kfreebsd";
152   case Linux: return "linux";
153   case Lv2: return "lv2";
154   case MacOSX: return "macosx";
155   case NetBSD: return "netbsd";
156   case OpenBSD: return "openbsd";
157   case Solaris: return "solaris";
158   case Win32: return "windows";
159   case Haiku: return "haiku";
160   case Minix: return "minix";
161   case RTEMS: return "rtems";
162   case NaCl: return "nacl";
163   case CNK: return "cnk";
164   case Bitrig: return "bitrig";
165   case AIX: return "aix";
166   case CUDA: return "cuda";
167   case NVCL: return "nvcl";
168   case AMDHSA: return "amdhsa";
169   case PS4: return "ps4";
170   }
171
172   llvm_unreachable("Invalid OSType");
173 }
174
175 const char *Triple::getEnvironmentTypeName(EnvironmentType Kind) {
176   switch (Kind) {
177   case UnknownEnvironment: return "unknown";
178   case GNU: return "gnu";
179   case GNUEABIHF: return "gnueabihf";
180   case GNUEABI: return "gnueabi";
181   case GNUX32: return "gnux32";
182   case CODE16: return "code16";
183   case EABI: return "eabi";
184   case EABIHF: return "eabihf";
185   case Android: return "android";
186   case MSVC: return "msvc";
187   case Itanium: return "itanium";
188   case Cygnus: return "cygnus";
189   }
190
191   llvm_unreachable("Invalid EnvironmentType!");
192 }
193
194 Triple::ArchType Triple::getArchTypeForLLVMName(StringRef Name) {
195   return StringSwitch<Triple::ArchType>(Name)
196     .Case("aarch64", aarch64)
197     .Case("aarch64_be", aarch64_be)
198     .Case("arm64", aarch64) // "arm64" is an alias for "aarch64"
199     .Case("arm", arm)
200     .Case("armeb", armeb)
201     .Case("bpf", bpf)
202     .Case("mips", mips)
203     .Case("mipsel", mipsel)
204     .Case("mips64", mips64)
205     .Case("mips64el", mips64el)
206     .Case("msp430", msp430)
207     .Case("ppc64", ppc64)
208     .Case("ppc32", ppc)
209     .Case("ppc", ppc)
210     .Case("ppc64le", ppc64le)
211     .Case("r600", r600)
212     .Case("amdgcn", amdgcn)
213     .Case("hexagon", hexagon)
214     .Case("sparc", sparc)
215     .Case("sparcel", sparcel)
216     .Case("sparcv9", sparcv9)
217     .Case("systemz", systemz)
218     .Case("tce", tce)
219     .Case("thumb", thumb)
220     .Case("thumbeb", thumbeb)
221     .Case("x86", x86)
222     .Case("x86-64", x86_64)
223     .Case("xcore", xcore)
224     .Case("nvptx", nvptx)
225     .Case("nvptx64", nvptx64)
226     .Case("le32", le32)
227     .Case("le64", le64)
228     .Case("amdil", amdil)
229     .Case("amdil64", amdil64)
230     .Case("hsail", hsail)
231     .Case("hsail64", hsail64)
232     .Case("spir", spir)
233     .Case("spir64", spir64)
234     .Case("kalimba", kalimba)
235     .Default(UnknownArch);
236 }
237
238 static Triple::ArchType parseARMArch(StringRef ArchName) {
239   size_t offset = StringRef::npos;
240   Triple::ArchType arch = Triple::UnknownArch;
241   bool isThumb = ArchName.startswith("thumb");
242
243   if (ArchName.equals("arm"))
244     return Triple::arm;
245   if (ArchName.equals("armeb"))
246     return Triple::armeb;
247   if (ArchName.equals("thumb"))
248     return Triple::thumb;
249   if (ArchName.equals("thumbeb"))
250     return Triple::thumbeb;
251   if (ArchName.equals("arm64") || ArchName.equals("aarch64"))
252     return Triple::aarch64;
253   if (ArchName.equals("aarch64_be"))
254     return Triple::aarch64_be;
255
256   if (ArchName.startswith("armv")) {
257     offset = 3;
258     if (ArchName.endswith("eb")) {
259       arch = Triple::armeb;
260       ArchName = ArchName.substr(0, ArchName.size() - 2);
261     } else
262       arch = Triple::arm;
263   } else if (ArchName.startswith("armebv")) {
264     offset = 5;
265     arch = Triple::armeb;
266   } else if (ArchName.startswith("thumbv")) {
267     offset = 5;
268     if (ArchName.endswith("eb")) {
269       arch = Triple::thumbeb;
270       ArchName = ArchName.substr(0, ArchName.size() - 2);
271     } else
272       arch = Triple::thumb;
273   } else if (ArchName.startswith("thumbebv")) {
274     offset = 7;
275     arch = Triple::thumbeb;
276   }
277   return StringSwitch<Triple::ArchType>(ArchName.substr(offset))
278     .Cases("v2", "v2a", isThumb ? Triple::UnknownArch : arch)
279     .Cases("v3", "v3m", isThumb ? Triple::UnknownArch : arch)
280     .Cases("v4", "v4t", arch)
281     .Cases("v5", "v5e", "v5t", "v5te", "v5tej", arch)
282     .Cases("v6", "v6hl", "v6j", "v6k", arch)
283     .Cases("v6m", "v6sm", arch)
284     .Cases("v6t2", "v6z", "v6zk", arch)
285     .Cases("v7", "v7a", "v7em", "v7hl", "v7l", arch)
286     .Cases("v7m", "v7r", "v7s", arch)
287     .Cases("v8", "v8a", arch)
288     .Cases("v8.1", "v8.1a", arch)
289     .Default(Triple::UnknownArch);
290 }
291
292 static Triple::ArchType parseArch(StringRef ArchName) {
293   Triple::ArchType ARMArch(parseARMArch(ArchName));
294
295   return StringSwitch<Triple::ArchType>(ArchName)
296     .Cases("i386", "i486", "i586", "i686", Triple::x86)
297     // FIXME: Do we need to support these?
298     .Cases("i786", "i886", "i986", Triple::x86)
299     .Cases("amd64", "x86_64", "x86_64h", Triple::x86_64)
300     .Case("powerpc", Triple::ppc)
301     .Cases("powerpc64", "ppu", Triple::ppc64)
302     .Case("powerpc64le", Triple::ppc64le)
303     .Case("xscale", Triple::arm)
304     .Case("xscaleeb", Triple::armeb)
305     .StartsWith("arm", ARMArch)
306     .StartsWith("thumb", ARMArch)
307     .StartsWith("aarch64", ARMArch)
308     .Case("msp430", Triple::msp430)
309     .Cases("mips", "mipseb", "mipsallegrex", Triple::mips)
310     .Cases("mipsel", "mipsallegrexel", Triple::mipsel)
311     .Cases("mips64", "mips64eb", Triple::mips64)
312     .Case("mips64el", Triple::mips64el)
313     .Case("r600", Triple::r600)
314     .Case("amdgcn", Triple::amdgcn)
315     .Case("bpf", Triple::bpf)
316     .Case("hexagon", Triple::hexagon)
317     .Case("s390x", Triple::systemz)
318     .Case("sparc", Triple::sparc)
319     .Case("sparcel", Triple::sparcel)
320     .Cases("sparcv9", "sparc64", Triple::sparcv9)
321     .Case("tce", Triple::tce)
322     .Case("xcore", Triple::xcore)
323     .Case("nvptx", Triple::nvptx)
324     .Case("nvptx64", Triple::nvptx64)
325     .Case("le32", Triple::le32)
326     .Case("le64", Triple::le64)
327     .Case("amdil", Triple::amdil)
328     .Case("amdil64", Triple::amdil64)
329     .Case("hsail", Triple::hsail)
330     .Case("hsail64", Triple::hsail64)
331     .Case("spir", Triple::spir)
332     .Case("spir64", Triple::spir64)
333     .StartsWith("kalimba", Triple::kalimba)
334     .Default(Triple::UnknownArch);
335 }
336
337 static Triple::VendorType parseVendor(StringRef VendorName) {
338   return StringSwitch<Triple::VendorType>(VendorName)
339     .Case("apple", Triple::Apple)
340     .Case("pc", Triple::PC)
341     .Case("scei", Triple::SCEI)
342     .Case("bgp", Triple::BGP)
343     .Case("bgq", Triple::BGQ)
344     .Case("fsl", Triple::Freescale)
345     .Case("ibm", Triple::IBM)
346     .Case("img", Triple::ImaginationTechnologies)
347     .Case("mti", Triple::MipsTechnologies)
348     .Case("nvidia", Triple::NVIDIA)
349     .Case("csr", Triple::CSR)
350     .Default(Triple::UnknownVendor);
351 }
352
353 static Triple::OSType parseOS(StringRef OSName) {
354   return StringSwitch<Triple::OSType>(OSName)
355     .StartsWith("cloudabi", Triple::CloudABI)
356     .StartsWith("darwin", Triple::Darwin)
357     .StartsWith("dragonfly", Triple::DragonFly)
358     .StartsWith("freebsd", Triple::FreeBSD)
359     .StartsWith("ios", Triple::IOS)
360     .StartsWith("kfreebsd", Triple::KFreeBSD)
361     .StartsWith("linux", Triple::Linux)
362     .StartsWith("lv2", Triple::Lv2)
363     .StartsWith("macosx", Triple::MacOSX)
364     .StartsWith("netbsd", Triple::NetBSD)
365     .StartsWith("openbsd", Triple::OpenBSD)
366     .StartsWith("solaris", Triple::Solaris)
367     .StartsWith("win32", Triple::Win32)
368     .StartsWith("windows", Triple::Win32)
369     .StartsWith("haiku", Triple::Haiku)
370     .StartsWith("minix", Triple::Minix)
371     .StartsWith("rtems", Triple::RTEMS)
372     .StartsWith("nacl", Triple::NaCl)
373     .StartsWith("cnk", Triple::CNK)
374     .StartsWith("bitrig", Triple::Bitrig)
375     .StartsWith("aix", Triple::AIX)
376     .StartsWith("cuda", Triple::CUDA)
377     .StartsWith("nvcl", Triple::NVCL)
378     .StartsWith("amdhsa", Triple::AMDHSA)
379     .StartsWith("ps4", Triple::PS4)
380     .Default(Triple::UnknownOS);
381 }
382
383 static Triple::EnvironmentType parseEnvironment(StringRef EnvironmentName) {
384   return StringSwitch<Triple::EnvironmentType>(EnvironmentName)
385     .StartsWith("eabihf", Triple::EABIHF)
386     .StartsWith("eabi", Triple::EABI)
387     .StartsWith("gnueabihf", Triple::GNUEABIHF)
388     .StartsWith("gnueabi", Triple::GNUEABI)
389     .StartsWith("gnux32", Triple::GNUX32)
390     .StartsWith("code16", Triple::CODE16)
391     .StartsWith("gnu", Triple::GNU)
392     .StartsWith("android", Triple::Android)
393     .StartsWith("msvc", Triple::MSVC)
394     .StartsWith("itanium", Triple::Itanium)
395     .StartsWith("cygnus", Triple::Cygnus)
396     .Default(Triple::UnknownEnvironment);
397 }
398
399 static Triple::ObjectFormatType parseFormat(StringRef EnvironmentName) {
400   return StringSwitch<Triple::ObjectFormatType>(EnvironmentName)
401     .EndsWith("coff", Triple::COFF)
402     .EndsWith("elf", Triple::ELF)
403     .EndsWith("macho", Triple::MachO)
404     .Default(Triple::UnknownObjectFormat);
405 }
406
407 static Triple::SubArchType parseSubArch(StringRef SubArchName) {
408   if (SubArchName.endswith("eb"))
409     SubArchName = SubArchName.substr(0, SubArchName.size() - 2);
410
411   return StringSwitch<Triple::SubArchType>(SubArchName)
412     .EndsWith("v8.1a", Triple::ARMSubArch_v8_1a)
413     .EndsWith("v8", Triple::ARMSubArch_v8)
414     .EndsWith("v8a", Triple::ARMSubArch_v8)
415     .EndsWith("v7", Triple::ARMSubArch_v7)
416     .EndsWith("v7a", Triple::ARMSubArch_v7)
417     .EndsWith("v7em", Triple::ARMSubArch_v7em)
418     .EndsWith("v7l", Triple::ARMSubArch_v7)
419     .EndsWith("v7m", Triple::ARMSubArch_v7m)
420     .EndsWith("v7r", Triple::ARMSubArch_v7)
421     .EndsWith("v7s", Triple::ARMSubArch_v7s)
422     .EndsWith("v6", Triple::ARMSubArch_v6)
423     .EndsWith("v6m", Triple::ARMSubArch_v6m)
424     .EndsWith("v6sm", Triple::ARMSubArch_v6m)
425     .EndsWith("v6k", Triple::ARMSubArch_v6k)
426     .EndsWith("v6t2", Triple::ARMSubArch_v6t2)
427     .EndsWith("v5", Triple::ARMSubArch_v5)
428     .EndsWith("v5e", Triple::ARMSubArch_v5)
429     .EndsWith("v5t", Triple::ARMSubArch_v5)
430     .EndsWith("v5te", Triple::ARMSubArch_v5te)
431     .EndsWith("v4t", Triple::ARMSubArch_v4t)
432     .EndsWith("kalimba3", Triple::KalimbaSubArch_v3)
433     .EndsWith("kalimba4", Triple::KalimbaSubArch_v4)
434     .EndsWith("kalimba5", Triple::KalimbaSubArch_v5)
435     .Default(Triple::NoSubArch);
436 }
437
438 static const char *getObjectFormatTypeName(Triple::ObjectFormatType Kind) {
439   switch (Kind) {
440   case Triple::UnknownObjectFormat: return "";
441   case Triple::COFF: return "coff";
442   case Triple::ELF: return "elf";
443   case Triple::MachO: return "macho";
444   }
445   llvm_unreachable("unknown object format type");
446 }
447
448 static Triple::ObjectFormatType getDefaultFormat(const Triple &T) {
449   switch (T.getArch()) {
450   default:
451     break;
452   case Triple::hexagon:
453   case Triple::mips:
454   case Triple::mipsel:
455   case Triple::mips64:
456   case Triple::mips64el:
457   case Triple::r600:
458   case Triple::amdgcn:
459   case Triple::sparc:
460   case Triple::sparcv9:
461   case Triple::systemz:
462   case Triple::xcore:
463   case Triple::ppc64le:
464     return Triple::ELF;
465
466   case Triple::ppc:
467   case Triple::ppc64:
468     if (T.isOSDarwin())
469       return Triple::MachO;
470     return Triple::ELF;
471   }
472
473   if (T.isOSDarwin())
474     return Triple::MachO;
475   else if (T.isOSWindows())
476     return Triple::COFF;
477   return Triple::ELF;
478 }
479
480 /// \brief Construct a triple from the string representation provided.
481 ///
482 /// This stores the string representation and parses the various pieces into
483 /// enum members.
484 Triple::Triple(const Twine &Str)
485     : Data(Str.str()),
486       Arch(parseArch(getArchName())),
487       SubArch(parseSubArch(getArchName())),
488       Vendor(parseVendor(getVendorName())),
489       OS(parseOS(getOSName())),
490       Environment(parseEnvironment(getEnvironmentName())),
491       ObjectFormat(parseFormat(getEnvironmentName())) {
492   if (ObjectFormat == Triple::UnknownObjectFormat)
493     ObjectFormat = getDefaultFormat(*this);
494 }
495
496 /// \brief Construct a triple from string representations of the architecture,
497 /// vendor, and OS.
498 ///
499 /// This joins each argument into a canonical string representation and parses
500 /// them into enum members. It leaves the environment unknown and omits it from
501 /// the string representation.
502 Triple::Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr)
503     : Data((ArchStr + Twine('-') + VendorStr + Twine('-') + OSStr).str()),
504       Arch(parseArch(ArchStr.str())),
505       SubArch(parseSubArch(ArchStr.str())),
506       Vendor(parseVendor(VendorStr.str())),
507       OS(parseOS(OSStr.str())),
508       Environment(), ObjectFormat(Triple::UnknownObjectFormat) {
509   ObjectFormat = getDefaultFormat(*this);
510 }
511
512 /// \brief Construct a triple from string representations of the architecture,
513 /// vendor, OS, and environment.
514 ///
515 /// This joins each argument into a canonical string representation and parses
516 /// them into enum members.
517 Triple::Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr,
518                const Twine &EnvironmentStr)
519     : Data((ArchStr + Twine('-') + VendorStr + Twine('-') + OSStr + Twine('-') +
520             EnvironmentStr).str()),
521       Arch(parseArch(ArchStr.str())),
522       SubArch(parseSubArch(ArchStr.str())),
523       Vendor(parseVendor(VendorStr.str())),
524       OS(parseOS(OSStr.str())),
525       Environment(parseEnvironment(EnvironmentStr.str())),
526       ObjectFormat(parseFormat(EnvironmentStr.str())) {
527   if (ObjectFormat == Triple::UnknownObjectFormat)
528     ObjectFormat = getDefaultFormat(*this);
529 }
530
531 std::string Triple::normalize(StringRef Str) {
532   bool IsMinGW32 = false;
533   bool IsCygwin = false;
534
535   // Parse into components.
536   SmallVector<StringRef, 4> Components;
537   Str.split(Components, "-");
538
539   // If the first component corresponds to a known architecture, preferentially
540   // use it for the architecture.  If the second component corresponds to a
541   // known vendor, preferentially use it for the vendor, etc.  This avoids silly
542   // component movement when a component parses as (eg) both a valid arch and a
543   // valid os.
544   ArchType Arch = UnknownArch;
545   if (Components.size() > 0)
546     Arch = parseArch(Components[0]);
547   VendorType Vendor = UnknownVendor;
548   if (Components.size() > 1)
549     Vendor = parseVendor(Components[1]);
550   OSType OS = UnknownOS;
551   if (Components.size() > 2) {
552     OS = parseOS(Components[2]);
553     IsCygwin = Components[2].startswith("cygwin");
554     IsMinGW32 = Components[2].startswith("mingw");
555   }
556   EnvironmentType Environment = UnknownEnvironment;
557   if (Components.size() > 3)
558     Environment = parseEnvironment(Components[3]);
559   ObjectFormatType ObjectFormat = UnknownObjectFormat;
560   if (Components.size() > 4)
561     ObjectFormat = parseFormat(Components[4]);
562
563   // Note which components are already in their final position.  These will not
564   // be moved.
565   bool Found[4];
566   Found[0] = Arch != UnknownArch;
567   Found[1] = Vendor != UnknownVendor;
568   Found[2] = OS != UnknownOS;
569   Found[3] = Environment != UnknownEnvironment;
570
571   // If they are not there already, permute the components into their canonical
572   // positions by seeing if they parse as a valid architecture, and if so moving
573   // the component to the architecture position etc.
574   for (unsigned Pos = 0; Pos != array_lengthof(Found); ++Pos) {
575     if (Found[Pos])
576       continue; // Already in the canonical position.
577
578     for (unsigned Idx = 0; Idx != Components.size(); ++Idx) {
579       // Do not reparse any components that already matched.
580       if (Idx < array_lengthof(Found) && Found[Idx])
581         continue;
582
583       // Does this component parse as valid for the target position?
584       bool Valid = false;
585       StringRef Comp = Components[Idx];
586       switch (Pos) {
587       default: llvm_unreachable("unexpected component type!");
588       case 0:
589         Arch = parseArch(Comp);
590         Valid = Arch != UnknownArch;
591         break;
592       case 1:
593         Vendor = parseVendor(Comp);
594         Valid = Vendor != UnknownVendor;
595         break;
596       case 2:
597         OS = parseOS(Comp);
598         IsCygwin = Comp.startswith("cygwin");
599         IsMinGW32 = Comp.startswith("mingw");
600         Valid = OS != UnknownOS || IsCygwin || IsMinGW32;
601         break;
602       case 3:
603         Environment = parseEnvironment(Comp);
604         Valid = Environment != UnknownEnvironment;
605         if (!Valid) {
606           ObjectFormat = parseFormat(Comp);
607           Valid = ObjectFormat != UnknownObjectFormat;
608         }
609         break;
610       }
611       if (!Valid)
612         continue; // Nope, try the next component.
613
614       // Move the component to the target position, pushing any non-fixed
615       // components that are in the way to the right.  This tends to give
616       // good results in the common cases of a forgotten vendor component
617       // or a wrongly positioned environment.
618       if (Pos < Idx) {
619         // Insert left, pushing the existing components to the right.  For
620         // example, a-b-i386 -> i386-a-b when moving i386 to the front.
621         StringRef CurrentComponent(""); // The empty component.
622         // Replace the component we are moving with an empty component.
623         std::swap(CurrentComponent, Components[Idx]);
624         // Insert the component being moved at Pos, displacing any existing
625         // components to the right.
626         for (unsigned i = Pos; !CurrentComponent.empty(); ++i) {
627           // Skip over any fixed components.
628           while (i < array_lengthof(Found) && Found[i])
629             ++i;
630           // Place the component at the new position, getting the component
631           // that was at this position - it will be moved right.
632           std::swap(CurrentComponent, Components[i]);
633         }
634       } else if (Pos > Idx) {
635         // Push right by inserting empty components until the component at Idx
636         // reaches the target position Pos.  For example, pc-a -> -pc-a when
637         // moving pc to the second position.
638         do {
639           // Insert one empty component at Idx.
640           StringRef CurrentComponent(""); // The empty component.
641           for (unsigned i = Idx; i < Components.size();) {
642             // Place the component at the new position, getting the component
643             // that was at this position - it will be moved right.
644             std::swap(CurrentComponent, Components[i]);
645             // If it was placed on top of an empty component then we are done.
646             if (CurrentComponent.empty())
647               break;
648             // Advance to the next component, skipping any fixed components.
649             while (++i < array_lengthof(Found) && Found[i])
650               ;
651           }
652           // The last component was pushed off the end - append it.
653           if (!CurrentComponent.empty())
654             Components.push_back(CurrentComponent);
655
656           // Advance Idx to the component's new position.
657           while (++Idx < array_lengthof(Found) && Found[Idx])
658             ;
659         } while (Idx < Pos); // Add more until the final position is reached.
660       }
661       assert(Pos < Components.size() && Components[Pos] == Comp &&
662              "Component moved wrong!");
663       Found[Pos] = true;
664       break;
665     }
666   }
667
668   // Special case logic goes here.  At this point Arch, Vendor and OS have the
669   // correct values for the computed components.
670
671   if (OS == Triple::Win32) {
672     Components.resize(4);
673     Components[2] = "windows";
674     if (Environment == UnknownEnvironment) {
675       if (ObjectFormat == UnknownObjectFormat || ObjectFormat == Triple::COFF)
676         Components[3] = "msvc";
677       else
678         Components[3] = getObjectFormatTypeName(ObjectFormat);
679     }
680   } else if (IsMinGW32) {
681     Components.resize(4);
682     Components[2] = "windows";
683     Components[3] = "gnu";
684   } else if (IsCygwin) {
685     Components.resize(4);
686     Components[2] = "windows";
687     Components[3] = "cygnus";
688   }
689   if (IsMinGW32 || IsCygwin ||
690       (OS == Triple::Win32 && Environment != UnknownEnvironment)) {
691     if (ObjectFormat != UnknownObjectFormat && ObjectFormat != Triple::COFF) {
692       Components.resize(5);
693       Components[4] = getObjectFormatTypeName(ObjectFormat);
694     }
695   }
696
697   // Stick the corrected components back together to form the normalized string.
698   std::string Normalized;
699   for (unsigned i = 0, e = Components.size(); i != e; ++i) {
700     if (i) Normalized += '-';
701     Normalized += Components[i];
702   }
703   return Normalized;
704 }
705
706 StringRef Triple::getArchName() const {
707   return StringRef(Data).split('-').first;           // Isolate first component
708 }
709
710 StringRef Triple::getVendorName() const {
711   StringRef Tmp = StringRef(Data).split('-').second; // Strip first component
712   return Tmp.split('-').first;                       // Isolate second component
713 }
714
715 StringRef Triple::getOSName() const {
716   StringRef Tmp = StringRef(Data).split('-').second; // Strip first component
717   Tmp = Tmp.split('-').second;                       // Strip second component
718   return Tmp.split('-').first;                       // Isolate third component
719 }
720
721 StringRef Triple::getEnvironmentName() const {
722   StringRef Tmp = StringRef(Data).split('-').second; // Strip first component
723   Tmp = Tmp.split('-').second;                       // Strip second component
724   return Tmp.split('-').second;                      // Strip third component
725 }
726
727 StringRef Triple::getOSAndEnvironmentName() const {
728   StringRef Tmp = StringRef(Data).split('-').second; // Strip first component
729   return Tmp.split('-').second;                      // Strip second component
730 }
731
732 static unsigned EatNumber(StringRef &Str) {
733   assert(!Str.empty() && Str[0] >= '0' && Str[0] <= '9' && "Not a number");
734   unsigned Result = 0;
735
736   do {
737     // Consume the leading digit.
738     Result = Result*10 + (Str[0] - '0');
739
740     // Eat the digit.
741     Str = Str.substr(1);
742   } while (!Str.empty() && Str[0] >= '0' && Str[0] <= '9');
743
744   return Result;
745 }
746
747 void Triple::getOSVersion(unsigned &Major, unsigned &Minor,
748                           unsigned &Micro) const {
749   StringRef OSName = getOSName();
750
751   // For Android, we care about the Android version rather than the Linux
752   // version.
753   if (getEnvironment() == Android) {
754     OSName = getEnvironmentName().substr(strlen("android"));
755     if (OSName.startswith("eabi"))
756       OSName = OSName.substr(strlen("eabi"));
757   }
758
759   // Assume that the OS portion of the triple starts with the canonical name.
760   StringRef OSTypeName = getOSTypeName(getOS());
761   if (OSName.startswith(OSTypeName))
762     OSName = OSName.substr(OSTypeName.size());
763
764   // Any unset version defaults to 0.
765   Major = Minor = Micro = 0;
766
767   // Parse up to three components.
768   unsigned *Components[3] = { &Major, &Minor, &Micro };
769   for (unsigned i = 0; i != 3; ++i) {
770     if (OSName.empty() || OSName[0] < '0' || OSName[0] > '9')
771       break;
772
773     // Consume the leading number.
774     *Components[i] = EatNumber(OSName);
775
776     // Consume the separator, if present.
777     if (OSName.startswith("."))
778       OSName = OSName.substr(1);
779   }
780 }
781
782 bool Triple::getMacOSXVersion(unsigned &Major, unsigned &Minor,
783                               unsigned &Micro) const {
784   getOSVersion(Major, Minor, Micro);
785
786   switch (getOS()) {
787   default: llvm_unreachable("unexpected OS for Darwin triple");
788   case Darwin:
789     // Default to darwin8, i.e., MacOSX 10.4.
790     if (Major == 0)
791       Major = 8;
792     // Darwin version numbers are skewed from OS X versions.
793     if (Major < 4)
794       return false;
795     Micro = 0;
796     Minor = Major - 4;
797     Major = 10;
798     break;
799   case MacOSX:
800     // Default to 10.4.
801     if (Major == 0) {
802       Major = 10;
803       Minor = 4;
804     }
805     if (Major != 10)
806       return false;
807     break;
808   case IOS:
809     // Ignore the version from the triple.  This is only handled because the
810     // the clang driver combines OS X and IOS support into a common Darwin
811     // toolchain that wants to know the OS X version number even when targeting
812     // IOS.
813     Major = 10;
814     Minor = 4;
815     Micro = 0;
816     break;
817   }
818   return true;
819 }
820
821 void Triple::getiOSVersion(unsigned &Major, unsigned &Minor,
822                            unsigned &Micro) const {
823   switch (getOS()) {
824   default: llvm_unreachable("unexpected OS for Darwin triple");
825   case Darwin:
826   case MacOSX:
827     // Ignore the version from the triple.  This is only handled because the
828     // the clang driver combines OS X and IOS support into a common Darwin
829     // toolchain that wants to know the iOS version number even when targeting
830     // OS X.
831     Major = 5;
832     Minor = 0;
833     Micro = 0;
834     break;
835   case IOS:
836     getOSVersion(Major, Minor, Micro);
837     // Default to 5.0 (or 7.0 for arm64).
838     if (Major == 0)
839       Major = (getArch() == aarch64) ? 7 : 5;
840     break;
841   }
842 }
843
844 void Triple::setTriple(const Twine &Str) {
845   *this = Triple(Str);
846 }
847
848 void Triple::setArch(ArchType Kind) {
849   setArchName(getArchTypeName(Kind));
850 }
851
852 void Triple::setVendor(VendorType Kind) {
853   setVendorName(getVendorTypeName(Kind));
854 }
855
856 void Triple::setOS(OSType Kind) {
857   setOSName(getOSTypeName(Kind));
858 }
859
860 void Triple::setEnvironment(EnvironmentType Kind) {
861   if (ObjectFormat == getDefaultFormat(*this))
862     return setEnvironmentName(getEnvironmentTypeName(Kind));
863
864   setEnvironmentName((getEnvironmentTypeName(Kind) + Twine("-") +
865                       getObjectFormatTypeName(ObjectFormat)).str());
866 }
867
868 void Triple::setObjectFormat(ObjectFormatType Kind) {
869   if (Environment == UnknownEnvironment)
870     return setEnvironmentName(getObjectFormatTypeName(Kind));
871
872   setEnvironmentName((getEnvironmentTypeName(Environment) + Twine("-") +
873                       getObjectFormatTypeName(Kind)).str());
874 }
875
876 void Triple::setArchName(StringRef Str) {
877   // Work around a miscompilation bug for Twines in gcc 4.0.3.
878   SmallString<64> Triple;
879   Triple += Str;
880   Triple += "-";
881   Triple += getVendorName();
882   Triple += "-";
883   Triple += getOSAndEnvironmentName();
884   setTriple(Triple);
885 }
886
887 void Triple::setVendorName(StringRef Str) {
888   setTriple(getArchName() + "-" + Str + "-" + getOSAndEnvironmentName());
889 }
890
891 void Triple::setOSName(StringRef Str) {
892   if (hasEnvironment())
893     setTriple(getArchName() + "-" + getVendorName() + "-" + Str +
894               "-" + getEnvironmentName());
895   else
896     setTriple(getArchName() + "-" + getVendorName() + "-" + Str);
897 }
898
899 void Triple::setEnvironmentName(StringRef Str) {
900   setTriple(getArchName() + "-" + getVendorName() + "-" + getOSName() +
901             "-" + Str);
902 }
903
904 void Triple::setOSAndEnvironmentName(StringRef Str) {
905   setTriple(getArchName() + "-" + getVendorName() + "-" + Str);
906 }
907
908 static unsigned getArchPointerBitWidth(llvm::Triple::ArchType Arch) {
909   switch (Arch) {
910   case llvm::Triple::UnknownArch:
911     return 0;
912
913   case llvm::Triple::msp430:
914     return 16;
915
916   case llvm::Triple::arm:
917   case llvm::Triple::armeb:
918   case llvm::Triple::hexagon:
919   case llvm::Triple::le32:
920   case llvm::Triple::mips:
921   case llvm::Triple::mipsel:
922   case llvm::Triple::nvptx:
923   case llvm::Triple::ppc:
924   case llvm::Triple::r600:
925   case llvm::Triple::sparc:
926   case llvm::Triple::sparcel:
927   case llvm::Triple::tce:
928   case llvm::Triple::thumb:
929   case llvm::Triple::thumbeb:
930   case llvm::Triple::x86:
931   case llvm::Triple::xcore:
932   case llvm::Triple::amdil:
933   case llvm::Triple::hsail:
934   case llvm::Triple::spir:
935   case llvm::Triple::kalimba:
936     return 32;
937
938   case llvm::Triple::aarch64:
939   case llvm::Triple::aarch64_be:
940   case llvm::Triple::amdgcn:
941   case llvm::Triple::bpf:
942   case llvm::Triple::le64:
943   case llvm::Triple::mips64:
944   case llvm::Triple::mips64el:
945   case llvm::Triple::nvptx64:
946   case llvm::Triple::ppc64:
947   case llvm::Triple::ppc64le:
948   case llvm::Triple::sparcv9:
949   case llvm::Triple::systemz:
950   case llvm::Triple::x86_64:
951   case llvm::Triple::amdil64:
952   case llvm::Triple::hsail64:
953   case llvm::Triple::spir64:
954     return 64;
955   }
956   llvm_unreachable("Invalid architecture value");
957 }
958
959 bool Triple::isArch64Bit() const {
960   return getArchPointerBitWidth(getArch()) == 64;
961 }
962
963 bool Triple::isArch32Bit() const {
964   return getArchPointerBitWidth(getArch()) == 32;
965 }
966
967 bool Triple::isArch16Bit() const {
968   return getArchPointerBitWidth(getArch()) == 16;
969 }
970
971 Triple Triple::get32BitArchVariant() const {
972   Triple T(*this);
973   switch (getArch()) {
974   case Triple::UnknownArch:
975   case Triple::aarch64:
976   case Triple::aarch64_be:
977   case Triple::amdgcn:
978   case Triple::bpf:
979   case Triple::msp430:
980   case Triple::systemz:
981   case Triple::ppc64le:
982     T.setArch(UnknownArch);
983     break;
984
985   case Triple::amdil:
986   case Triple::hsail:
987   case Triple::spir:
988   case Triple::arm:
989   case Triple::armeb:
990   case Triple::hexagon:
991   case Triple::kalimba:
992   case Triple::le32:
993   case Triple::mips:
994   case Triple::mipsel:
995   case Triple::nvptx:
996   case Triple::ppc:
997   case Triple::r600:
998   case Triple::sparc:
999   case Triple::sparcel:
1000   case Triple::tce:
1001   case Triple::thumb:
1002   case Triple::thumbeb:
1003   case Triple::x86:
1004   case Triple::xcore:
1005     // Already 32-bit.
1006     break;
1007
1008   case Triple::le64:      T.setArch(Triple::le32);    break;
1009   case Triple::mips64:    T.setArch(Triple::mips);    break;
1010   case Triple::mips64el:  T.setArch(Triple::mipsel);  break;
1011   case Triple::nvptx64:   T.setArch(Triple::nvptx);   break;
1012   case Triple::ppc64:     T.setArch(Triple::ppc);     break;
1013   case Triple::sparcv9:   T.setArch(Triple::sparc);   break;
1014   case Triple::x86_64:    T.setArch(Triple::x86);     break;
1015   case Triple::amdil64:   T.setArch(Triple::amdil);   break;
1016   case Triple::hsail64:   T.setArch(Triple::hsail);   break;
1017   case Triple::spir64:    T.setArch(Triple::spir);    break;
1018   }
1019   return T;
1020 }
1021
1022 Triple Triple::get64BitArchVariant() const {
1023   Triple T(*this);
1024   switch (getArch()) {
1025   case Triple::UnknownArch:
1026   case Triple::arm:
1027   case Triple::armeb:
1028   case Triple::hexagon:
1029   case Triple::kalimba:
1030   case Triple::msp430:
1031   case Triple::r600:
1032   case Triple::tce:
1033   case Triple::thumb:
1034   case Triple::thumbeb:
1035   case Triple::xcore:
1036   case Triple::sparcel:
1037     T.setArch(UnknownArch);
1038     break;
1039
1040   case Triple::aarch64:
1041   case Triple::aarch64_be:
1042   case Triple::bpf:
1043   case Triple::le64:
1044   case Triple::amdil64:
1045   case Triple::amdgcn:
1046   case Triple::hsail64:
1047   case Triple::spir64:
1048   case Triple::mips64:
1049   case Triple::mips64el:
1050   case Triple::nvptx64:
1051   case Triple::ppc64:
1052   case Triple::ppc64le:
1053   case Triple::sparcv9:
1054   case Triple::systemz:
1055   case Triple::x86_64:
1056     // Already 64-bit.
1057     break;
1058
1059   case Triple::le32:    T.setArch(Triple::le64);      break;
1060   case Triple::mips:    T.setArch(Triple::mips64);    break;
1061   case Triple::mipsel:  T.setArch(Triple::mips64el);  break;
1062   case Triple::nvptx:   T.setArch(Triple::nvptx64);   break;
1063   case Triple::ppc:     T.setArch(Triple::ppc64);     break;
1064   case Triple::sparc:   T.setArch(Triple::sparcv9);   break;
1065   case Triple::x86:     T.setArch(Triple::x86_64);    break;
1066   case Triple::amdil:   T.setArch(Triple::amdil64);   break;
1067   case Triple::hsail:   T.setArch(Triple::hsail64);   break;
1068   case Triple::spir:    T.setArch(Triple::spir64);    break;
1069   }
1070   return T;
1071 }
1072
1073 // FIXME: tblgen this.
1074 const char *Triple::getARMCPUForArch(StringRef MArch) const {
1075   if (MArch.empty())
1076     MArch = getArchName();
1077
1078   switch (getOS()) {
1079   case llvm::Triple::FreeBSD:
1080   case llvm::Triple::NetBSD:
1081     if (MArch == "armv6")
1082       return "arm1176jzf-s";
1083     break;
1084   case llvm::Triple::Win32:
1085     // FIXME: this is invalid for WindowsCE
1086     return "cortex-a9";
1087   default:
1088     break;
1089   }
1090
1091   // MArch is expected to be of the form (arm|thumb)?(eb)?(v.+)?(eb)?
1092   // Only the (v.+) part is relevant for determining the CPU, as it determines
1093   // the architecture version, so we first remove the surrounding parts.
1094   // (ep9312|iwmmxt|xscale)(eb)? is also permitted, so we have to be a bit
1095   // careful when removing the leading (arm|thumb)?(eb)? as we don't want to
1096   // permit things like armep9312.
1097   const char *result = nullptr;
1098   size_t offset = StringRef::npos;
1099   if (MArch.startswith("arm"))
1100     offset = 3;
1101   else if (MArch.startswith("thumb"))
1102     offset = 5;
1103   if (offset != StringRef::npos && MArch.substr(offset, 2) == "eb")
1104     offset += 2;
1105   else if (MArch.endswith("eb"))
1106     MArch = MArch.substr(0, MArch.size() - 2);
1107   if (offset != StringRef::npos && (offset == MArch.size() || MArch[offset] == 'v'))
1108     MArch = MArch.substr(offset);
1109
1110   if (MArch == "") {
1111     // If no specific architecture version is requested, return the minimum CPU
1112     // required by the OS and environment.
1113     switch (getOS()) {
1114     case llvm::Triple::NetBSD:
1115       switch (getEnvironment()) {
1116       case llvm::Triple::GNUEABIHF:
1117       case llvm::Triple::GNUEABI:
1118       case llvm::Triple::EABIHF:
1119       case llvm::Triple::EABI:
1120         return "arm926ej-s";
1121       default:
1122         return "strongarm";
1123       }
1124     case llvm::Triple::NaCl:
1125       return "cortex-a8";
1126     default:
1127       switch (getEnvironment()) {
1128       case llvm::Triple::EABIHF:
1129       case llvm::Triple::GNUEABIHF:
1130         return "arm1176jzf-s";
1131       default:
1132         return "arm7tdmi";
1133       }
1134     }
1135   } else {
1136     result = llvm::StringSwitch<const char *>(MArch)
1137       .Cases("v2", "v2a", "arm2")
1138       .Case("v3", "arm6")
1139       .Case("v3m", "arm7m")
1140       .Case("v4", "strongarm")
1141       .Case("v4t", "arm7tdmi")
1142       .Cases("v5", "v5t", "arm10tdmi")
1143       .Cases("v5e", "v5te", "arm1022e")
1144       .Case("v5tej", "arm926ej-s")
1145       .Case("v6", "arm1136jf-s")
1146       .Case("v6j", "arm1136j-s")
1147       .Cases("v6k", "v6z", "v6zk", "arm1176jzf-s")
1148       .Case("v6t2", "arm1156t2-s")
1149       .Cases("v6m", "v6-m", "v6sm", "v6s-m", "cortex-m0")
1150       .Cases("v7", "v7a", "v7-a", "v7l", "v7-l", "cortex-a8")
1151       .Cases("v7s", "v7-s", "swift")
1152       .Cases("v7r", "v7-r", "cortex-r4")
1153       .Cases("v7m", "v7-m", "cortex-m3")
1154       .Cases("v7em", "v7e-m", "cortex-m4")
1155       .Cases("v8", "v8a", "v8-a", "cortex-a53")
1156       .Cases("v8.1a", "v8.1-a", "generic")
1157       .Case("ep9312", "ep9312")
1158       .Case("iwmmxt", "iwmmxt")
1159       .Case("xscale", "xscale")
1160       .Default(nullptr);
1161   }
1162
1163   return result;
1164 }