c9d34703fcb73d80da63162d7d2aa75446020666
[oota-llvm.git] / lib / MC / SubtargetFeature.cpp
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/ADT/SmallSet.h"
15 #include "llvm/MC/SubtargetFeature.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/Format.h"
18 #include "llvm/Support/SourceMgr.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <algorithm>
21 #include <cassert>
22 #include <cctype>
23 #include <cstdlib>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //                          Static Helper Functions
28 //===----------------------------------------------------------------------===//
29
30 /// hasFlag - Determine if a feature has a flag; '+' or '-'
31 ///
32 static inline bool hasFlag(const StringRef Feature) {
33   assert(!Feature.empty() && "Empty string");
34   // Get first character
35   char Ch = Feature[0];
36   // Check if first character is '+' or '-' flag
37   return Ch == '+' || Ch =='-';
38 }
39
40 /// StripFlag - Return string stripped of flag.
41 ///
42 static inline std::string StripFlag(const StringRef Feature) {
43   return hasFlag(Feature) ? Feature.substr(1) : Feature;
44 }
45
46 /// isEnabled - Return true if enable flag; '+'.
47 ///
48 static inline bool isEnabled(const StringRef Feature) {
49   assert(!Feature.empty() && "Empty string");
50   // Get first character
51   char Ch = Feature[0];
52   // Check if first character is '+' for enabled
53   return Ch == '+';
54 }
55
56 /// PrependFlag - Return a string with a prepended flag; '+' or '-'.
57 ///
58 static inline std::string PrependFlag(const StringRef Feature,
59                                     bool IsEnabled) {
60   assert(!Feature.empty() && "Empty string");
61   if (hasFlag(Feature))
62     return Feature;
63   std::string Prefix = IsEnabled ? "+" : "-";
64   Prefix += Feature;
65   return Prefix;
66 }
67
68 /// Split - Splits a string of comma separated items in to a vector of strings.
69 ///
70 static void Split(std::vector<std::string> &V, const StringRef S) {
71   if (S.empty())
72     return;
73
74   // Start at beginning of string.
75   size_t Pos = 0;
76   while (true) {
77     // Find the next comma
78     size_t Comma = S.find(',', Pos);
79     // If no comma found then the rest of the string is used
80     if (Comma == std::string::npos) {
81       // Add string to vector
82       V.push_back(S.substr(Pos));
83       break;
84     }
85     // Otherwise add substring to vector
86     V.push_back(S.substr(Pos, Comma - Pos));
87     // Advance to next item
88     Pos = Comma + 1;
89   }
90 }
91
92 /// Join a vector of strings to a string with a comma separating each element.
93 ///
94 static std::string Join(const std::vector<std::string> &V) {
95   // Start with empty string.
96   std::string Result;
97   // If the vector is not empty
98   if (!V.empty()) {
99     // Start with the first feature
100     Result = V[0];
101     // For each successive feature
102     for (size_t i = 1; i < V.size(); i++) {
103       // Add a comma
104       Result += ",";
105       // Add the feature
106       Result += V[i];
107     }
108   }
109   // Return the features string
110   return Result;
111 }
112
113 /// Adding features.
114 void SubtargetFeatures::AddFeature(const StringRef String,
115                                    bool IsEnabled) {
116   // Don't add empty features
117   if (!String.empty()) {
118     // Convert to lowercase, prepend flag and add to vector
119     Features.push_back(PrependFlag(String.lower(), IsEnabled));
120   }
121 }
122
123 // This needs to be shared between the instantiations of Find<>
124 typedef std::pair<std::string,std::string> KeyWithType;
125 static SmallSet<KeyWithType,10> reportedAsUnrecognized;
126
127 /// Find KV in array using binary search.
128 template<typename T>
129 const T *SubtargetFeatures::Find(StringRef Key, const T *Array, size_t Length,
130                                  const char* KeyType) {
131   // Determine the end of the array
132   const T *Hi = Array + Length;
133   // Binary search the array
134   const T *F = std::lower_bound(Array, Hi, Key);
135   // If not found then return NULL
136   if (F == Hi || StringRef(F->Key) != Key) {
137     // If not yet reported, report now
138     KeyWithType current(KeyType, Key);
139     if(!reportedAsUnrecognized.count(current)) {
140       SmallString<1024> storage;
141       StringRef message = ("'" + Key +
142                            "' is not a recognized " + KeyType +
143                            " for this target (ignoring " + KeyType +
144                            ")").toStringRef(storage);
145       SMDiagnostic(StringRef(), SourceMgr::DK_Warning, message)
146         .print(0, errs());
147       reportedAsUnrecognized.insert(current);
148     }
149     return NULL;
150   }
151   // Return the found array item
152   return F;
153 }
154
155 // Instantiate with <SubtargetInfoKV> for use in MCSubtargetInfo
156 template const SubtargetInfoKV *SubtargetFeatures::Find<SubtargetInfoKV>
157   (StringRef Key, const SubtargetInfoKV *Array, size_t Length, const char* KeyType);
158
159 /// getLongestEntryLength - Return the length of the longest entry in the table.
160 ///
161 static size_t getLongestEntryLength(const SubtargetFeatureKV *Table,
162                                     size_t Size) {
163   size_t MaxLen = 0;
164   for (size_t i = 0; i < Size; i++)
165     MaxLen = std::max(MaxLen, std::strlen(Table[i].Key));
166   return MaxLen;
167 }
168
169 /// Display help for feature choices.
170 ///
171 static void Help(const SubtargetFeatureKV *CPUTable, size_t CPUTableSize,
172                  const SubtargetFeatureKV *FeatTable, size_t FeatTableSize) {
173   // Determine the length of the longest CPU and Feature entries.
174   unsigned MaxCPULen  = getLongestEntryLength(CPUTable, CPUTableSize);
175   unsigned MaxFeatLen = getLongestEntryLength(FeatTable, FeatTableSize);
176
177   // Print the CPU table.
178   errs() << "Available CPUs for this target:\n\n";
179   for (size_t i = 0; i != CPUTableSize; i++)
180     errs() << format("  %-*s - %s.\n",
181                      MaxCPULen, CPUTable[i].Key, CPUTable[i].Desc);
182   errs() << '\n';
183
184   // Print the Feature table.
185   errs() << "Available features for this target:\n\n";
186   for (size_t i = 0; i != FeatTableSize; i++)
187     errs() << format("  %-*s - %s.\n",
188                      MaxFeatLen, FeatTable[i].Key, FeatTable[i].Desc);
189   errs() << '\n';
190
191   errs() << "Use +feature to enable a feature, or -feature to disable it.\n"
192             "For example, llc -mcpu=mycpu -mattr=+feature1,-feature2\n";
193   std::exit(1);
194 }
195
196 //===----------------------------------------------------------------------===//
197 //                    SubtargetFeatures Implementation
198 //===----------------------------------------------------------------------===//
199
200 SubtargetFeatures::SubtargetFeatures(const StringRef Initial) {
201   // Break up string into separate features
202   Split(Features, Initial);
203 }
204
205
206 std::string SubtargetFeatures::getString() const {
207   return Join(Features);
208 }
209
210 /// SetImpliedBits - For each feature that is (transitively) implied by this
211 /// feature, set it.
212 ///
213 static
214 void SetImpliedBits(uint64_t &Bits, const SubtargetFeatureKV *FeatureEntry,
215                     const SubtargetFeatureKV *FeatureTable,
216                     size_t FeatureTableSize) {
217   for (size_t i = 0; i < FeatureTableSize; ++i) {
218     const SubtargetFeatureKV &FE = FeatureTable[i];
219
220     if (FeatureEntry->Value == FE.Value) continue;
221
222     if (FeatureEntry->Implies & FE.Value) {
223       Bits |= FE.Value;
224       SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);
225     }
226   }
227 }
228
229 /// ClearImpliedBits - For each feature that (transitively) implies this
230 /// feature, clear it.
231 ///
232 static
233 void ClearImpliedBits(uint64_t &Bits, const SubtargetFeatureKV *FeatureEntry,
234                       const SubtargetFeatureKV *FeatureTable,
235                       size_t FeatureTableSize) {
236   for (size_t i = 0; i < FeatureTableSize; ++i) {
237     const SubtargetFeatureKV &FE = FeatureTable[i];
238
239     if (FeatureEntry->Value == FE.Value) continue;
240
241     if (FE.Implies & FeatureEntry->Value) {
242       Bits &= ~FE.Value;
243       ClearImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);
244     }
245   }
246 }
247
248 /// ToggleFeature - Toggle a feature and returns the newly updated feature
249 /// bits.
250 uint64_t
251 SubtargetFeatures::ToggleFeature(uint64_t Bits, const StringRef Feature,
252                                  const SubtargetFeatureKV *FeatureTable,
253                                  size_t FeatureTableSize) {
254   // Find feature in table.
255   const SubtargetFeatureKV *FeatureEntry =
256     Find(StripFlag(Feature), FeatureTable, FeatureTableSize, "feature");
257   // If there is a match
258   if (FeatureEntry) {
259     if ((Bits & FeatureEntry->Value) == FeatureEntry->Value) {
260       Bits &= ~FeatureEntry->Value;
261
262       // For each feature that implies this, clear it.
263       ClearImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);
264     } else {
265       Bits |=  FeatureEntry->Value;
266
267       // For each feature that this implies, set it.
268       SetImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);
269     }
270   }
271
272   return Bits;
273 }
274
275
276 /// getFeatureBits - Get feature bits a CPU.
277 ///
278 uint64_t SubtargetFeatures::getFeatureBits(const StringRef CPU,
279                                          const SubtargetFeatureKV *CPUTable,
280                                          size_t CPUTableSize,
281                                          const SubtargetFeatureKV *FeatureTable,
282                                          size_t FeatureTableSize) {
283   if (!FeatureTableSize || !CPUTableSize)
284     return 0;
285
286 #ifndef NDEBUG
287   for (size_t i = 1; i < CPUTableSize; i++) {
288     assert(strcmp(CPUTable[i - 1].Key, CPUTable[i].Key) < 0 &&
289            "CPU table is not sorted");
290   }
291   for (size_t i = 1; i < FeatureTableSize; i++) {
292     assert(strcmp(FeatureTable[i - 1].Key, FeatureTable[i].Key) < 0 &&
293           "CPU features table is not sorted");
294   }
295 #endif
296   uint64_t Bits = 0;                    // Resulting bits
297
298   // Check if help is needed
299   if (CPU == "help")
300     Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize);
301
302   // Find CPU entry if CPU name is specified.
303   if (!CPU.empty()) {
304     const SubtargetFeatureKV *CPUEntry = Find(CPU, CPUTable, CPUTableSize,
305                                               "processor");
306     // If there is a match
307     if (CPUEntry) {
308       // Set base feature bits
309       Bits = CPUEntry->Value;
310
311       // Set the feature implied by this CPU feature, if any.
312       for (size_t i = 0; i < FeatureTableSize; ++i) {
313         const SubtargetFeatureKV &FE = FeatureTable[i];
314         if (CPUEntry->Value & FE.Value)
315           SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);
316       }
317     }
318   }
319
320   // Iterate through each feature
321   for (size_t i = 0, E = Features.size(); i < E; i++) {
322     const StringRef Feature = Features[i];
323
324     // Check for help
325     if (Feature == "+help")
326       Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize);
327
328     // Find feature in table.
329     const SubtargetFeatureKV *FeatureEntry =
330             Find(StripFlag(Feature), FeatureTable, FeatureTableSize, "feature");
331     // If there is a match
332     if (FeatureEntry) {
333       // Enable/disable feature in bits
334       if (isEnabled(Feature)) {
335         Bits |=  FeatureEntry->Value;
336
337         // For each feature that this implies, set it.
338         SetImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);
339       } else {
340         Bits &= ~FeatureEntry->Value;
341
342         // For each feature that implies this, clear it.
343         ClearImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);
344       }
345     }
346   }
347
348   return Bits;
349 }
350
351 /// print - Print feature string.
352 ///
353 void SubtargetFeatures::print(raw_ostream &OS) const {
354   for (size_t i = 0, e = Features.size(); i != e; ++i)
355     OS << Features[i] << "  ";
356   OS << "\n";
357 }
358
359 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
360 /// dump - Dump feature info.
361 ///
362 void SubtargetFeatures::dump() const {
363   print(dbgs());
364 }
365 #endif
366
367 /// Adds the default features for the specified target triple.
368 ///
369 /// FIXME: This is an inelegant way of specifying the features of a
370 /// subtarget. It would be better if we could encode this information
371 /// into the IR. See <rdar://5972456>.
372 ///
373 void SubtargetFeatures::getDefaultSubtargetFeatures(const Triple& Triple) {
374   if (Triple.getVendor() == Triple::Apple) {
375     if (Triple.getArch() == Triple::ppc) {
376       // powerpc-apple-*
377       AddFeature("altivec");
378     } else if (Triple.getArch() == Triple::ppc64) {
379       // powerpc64-apple-*
380       AddFeature("64bit");
381       AddFeature("altivec");
382     }
383   }
384 }