1//===- SubtargetFeature.cpp - CPU characteristics Implementation ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SubtargetFeature interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/MC/SubtargetFeature.h"
15#include "llvm/Support/Debug.h"
16#include "llvm/Support/Format.h"
17#include "llvm/Support/raw_ostream.h"
18#include <algorithm>
19#include <cassert>
20#include <cctype>
21#include <cstdlib>
22using namespace llvm;
23
24//===----------------------------------------------------------------------===//
25//                          Static Helper Functions
26//===----------------------------------------------------------------------===//
27
28/// hasFlag - Determine if a feature has a flag; '+' or '-'
29///
30static inline bool hasFlag(StringRef Feature) {
31  assert(!Feature.empty() && "Empty string");
32  // Get first character
33  char Ch = Feature[0];
34  // Check if first character is '+' or '-' flag
35  return Ch == '+' || Ch =='-';
36}
37
38/// StripFlag - Return string stripped of flag.
39///
40static inline std::string StripFlag(StringRef Feature) {
41  return hasFlag(Feature) ? Feature.substr(1) : Feature;
42}
43
44/// isEnabled - Return true if enable flag; '+'.
45///
46static inline bool isEnabled(StringRef Feature) {
47  assert(!Feature.empty() && "Empty string");
48  // Get first character
49  char Ch = Feature[0];
50  // Check if first character is '+' for enabled
51  return Ch == '+';
52}
53
54/// Split - Splits a string of comma separated items in to a vector of strings.
55///
56static void Split(std::vector<std::string> &V, StringRef S) {
57  SmallVector<StringRef, 3> Tmp;
58  S.split(Tmp, ",", -1, false /* KeepEmpty */);
59  V.assign(Tmp.begin(), Tmp.end());
60}
61
62/// Join a vector of strings to a string with a comma separating each element.
63///
64static std::string Join(const std::vector<std::string> &V) {
65  // Start with empty string.
66  std::string Result;
67  // If the vector is not empty
68  if (!V.empty()) {
69    // Start with the first feature
70    Result = V[0];
71    // For each successive feature
72    for (size_t i = 1; i < V.size(); i++) {
73      // Add a comma
74      Result += ",";
75      // Add the feature
76      Result += V[i];
77    }
78  }
79  // Return the features string
80  return Result;
81}
82
83/// Adding features.
84void SubtargetFeatures::AddFeature(StringRef String, bool Enable) {
85  // Don't add empty features.
86  if (!String.empty())
87    // Convert to lowercase, prepend flag if we don't already have a flag.
88    Features.push_back(hasFlag(String) ? String.lower()
89                                       : (Enable ? "+" : "-") + String.lower());
90}
91
92/// Find KV in array using binary search.
93static const SubtargetFeatureKV *Find(StringRef S,
94                                      ArrayRef<SubtargetFeatureKV> A) {
95  // Binary search the array
96  auto F = std::lower_bound(A.begin(), A.end(), S);
97  // If not found then return NULL
98  if (F == A.end() || StringRef(F->Key) != S) return nullptr;
99  // Return the found array item
100  return F;
101}
102
103/// getLongestEntryLength - Return the length of the longest entry in the table.
104///
105static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
106  size_t MaxLen = 0;
107  for (auto &I : Table)
108    MaxLen = std::max(MaxLen, std::strlen(I.Key));
109  return MaxLen;
110}
111
112/// Display help for feature choices.
113///
114static void Help(ArrayRef<SubtargetFeatureKV> CPUTable,
115                 ArrayRef<SubtargetFeatureKV> FeatTable) {
116  // Determine the length of the longest CPU and Feature entries.
117  unsigned MaxCPULen  = getLongestEntryLength(CPUTable);
118  unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
119
120  // Print the CPU table.
121  errs() << "Available CPUs for this target:\n\n";
122  for (auto &CPU : CPUTable)
123    errs() << format("  %-*s - %s.\n", MaxCPULen, CPU.Key, CPU.Desc);
124  errs() << '\n';
125
126  // Print the Feature table.
127  errs() << "Available features for this target:\n\n";
128  for (auto &Feature : FeatTable)
129    errs() << format("  %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
130  errs() << '\n';
131
132  errs() << "Use +feature to enable a feature, or -feature to disable it.\n"
133            "For example, llc -mcpu=mycpu -mattr=+feature1,-feature2\n";
134}
135
136//===----------------------------------------------------------------------===//
137//                    SubtargetFeatures Implementation
138//===----------------------------------------------------------------------===//
139
140SubtargetFeatures::SubtargetFeatures(StringRef Initial) {
141  // Break up string into separate features
142  Split(Features, Initial);
143}
144
145
146std::string SubtargetFeatures::getString() const {
147  return Join(Features);
148}
149
150/// SetImpliedBits - For each feature that is (transitively) implied by this
151/// feature, set it.
152///
153static
154void SetImpliedBits(uint64_t &Bits, const SubtargetFeatureKV *FeatureEntry,
155                    ArrayRef<SubtargetFeatureKV> FeatureTable) {
156  for (auto &FE : FeatureTable) {
157    if (FeatureEntry->Value == FE.Value) continue;
158
159    if (FeatureEntry->Implies & FE.Value) {
160      Bits |= FE.Value;
161      SetImpliedBits(Bits, &FE, FeatureTable);
162    }
163  }
164}
165
166/// ClearImpliedBits - For each feature that (transitively) implies this
167/// feature, clear it.
168///
169static
170void ClearImpliedBits(uint64_t &Bits, const SubtargetFeatureKV *FeatureEntry,
171                      ArrayRef<SubtargetFeatureKV> FeatureTable) {
172  for (auto &FE : FeatureTable) {
173    if (FeatureEntry->Value == FE.Value) continue;
174
175    if (FE.Implies & FeatureEntry->Value) {
176      Bits &= ~FE.Value;
177      ClearImpliedBits(Bits, &FE, FeatureTable);
178    }
179  }
180}
181
182/// ToggleFeature - Toggle a feature and returns the newly updated feature
183/// bits.
184uint64_t
185SubtargetFeatures::ToggleFeature(uint64_t Bits, StringRef Feature,
186                                 ArrayRef<SubtargetFeatureKV> FeatureTable) {
187
188  // Find feature in table.
189  const SubtargetFeatureKV *FeatureEntry =
190      Find(StripFlag(Feature), FeatureTable);
191  // If there is a match
192  if (FeatureEntry) {
193    if ((Bits & FeatureEntry->Value) == FeatureEntry->Value) {
194      Bits &= ~FeatureEntry->Value;
195
196      // For each feature that implies this, clear it.
197      ClearImpliedBits(Bits, FeatureEntry, FeatureTable);
198    } else {
199      Bits |=  FeatureEntry->Value;
200
201      // For each feature that this implies, set it.
202      SetImpliedBits(Bits, FeatureEntry, FeatureTable);
203    }
204  } else {
205    // Bug: 20140355
206    // Silence this warning for now
207    if (false) {
208      errs() << "'" << Feature
209             << "' is not a recognized feature for this target"
210             << " (ignoring feature)\n";
211    }
212  }
213
214  return Bits;
215}
216
217
218/// getFeatureBits - Get feature bits a CPU.
219///
220uint64_t
221SubtargetFeatures::getFeatureBits(StringRef CPU,
222                                  ArrayRef<SubtargetFeatureKV> CPUTable,
223                                  ArrayRef<SubtargetFeatureKV> FeatureTable) {
224
225  if (CPUTable.empty() || FeatureTable.empty())
226    return 0;
227
228#ifndef NDEBUG
229  for (size_t i = 1, e = CPUTable.size(); i != e; ++i) {
230    assert(strcmp(CPUTable[i - 1].Key, CPUTable[i].Key) < 0 &&
231           "CPU table is not sorted");
232  }
233  for (size_t i = 1, e = FeatureTable.size(); i != e; ++i) {
234    assert(strcmp(FeatureTable[i - 1].Key, FeatureTable[i].Key) < 0 &&
235          "CPU features table is not sorted");
236  }
237#endif
238  uint64_t Bits = 0;                    // Resulting bits
239
240  // Check if help is needed
241  if (CPU == "help")
242    Help(CPUTable, FeatureTable);
243
244  // Find CPU entry if CPU name is specified.
245  else if (!CPU.empty()) {
246    const SubtargetFeatureKV *CPUEntry = Find(CPU, CPUTable);
247
248    // If there is a match
249    if (CPUEntry) {
250      // Set base feature bits
251      Bits = CPUEntry->Value;
252
253      // Set the feature implied by this CPU feature, if any.
254      for (auto &FE : FeatureTable) {
255        if (CPUEntry->Value & FE.Value)
256          SetImpliedBits(Bits, &FE, FeatureTable);
257      }
258    } else {
259      errs() << "'" << CPU
260             << "' is not a recognized processor for this target"
261             << " (ignoring processor)\n";
262    }
263  }
264
265  // Iterate through each feature
266  for (auto &Feature : Features) {
267    // Check for help
268    if (Feature == "+help")
269      Help(CPUTable, FeatureTable);
270
271    // Find feature in table.
272    const SubtargetFeatureKV *FeatureEntry =
273        Find(StripFlag(Feature), FeatureTable);
274    // If there is a match
275    if (FeatureEntry) {
276      // Enable/disable feature in bits
277      if (isEnabled(Feature)) {
278        Bits |=  FeatureEntry->Value;
279
280        // For each feature that this implies, set it.
281        SetImpliedBits(Bits, FeatureEntry, FeatureTable);
282      } else {
283        Bits &= ~FeatureEntry->Value;
284
285        // For each feature that implies this, clear it.
286        ClearImpliedBits(Bits, FeatureEntry, FeatureTable);
287      }
288    } else {
289      // Bug: 20140355
290      // Silence this warning for now
291      if (false) {
292        errs() << "'" << Feature
293               << "' is not a recognized feature for this target"
294               << " (ignoring feature)\n";
295      }
296    }
297  }
298
299  return Bits;
300}
301
302/// print - Print feature string.
303///
304void SubtargetFeatures::print(raw_ostream &OS) const {
305  for (auto &F : Features)
306    OS << F << " ";
307  OS << "\n";
308}
309
310#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
311/// dump - Dump feature info.
312///
313void SubtargetFeatures::dump() const {
314  print(dbgs());
315}
316#endif
317
318/// Adds the default features for the specified target triple.
319///
320/// FIXME: This is an inelegant way of specifying the features of a
321/// subtarget. It would be better if we could encode this information
322/// into the IR. See <rdar://5972456>.
323///
324void SubtargetFeatures::getDefaultSubtargetFeatures(const Triple& Triple) {
325  if (Triple.getVendor() == Triple::Apple) {
326    if (Triple.getArch() == Triple::ppc) {
327      // powerpc-apple-*
328      AddFeature("altivec");
329    } else if (Triple.getArch() == Triple::ppc64) {
330      // powerpc64-apple-*
331      AddFeature("64bit");
332      AddFeature("altivec");
333    }
334  }
335}
336