1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
|
//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting LLVMC configuration code.
//
//===----------------------------------------------------------------------===//
#include "LLVMCConfigurationEmitter.h"
#include "Record.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/Streams.h"
#include <algorithm>
#include <cassert>
#include <functional>
#include <string>
using namespace llvm;
namespace {
//===----------------------------------------------------------------------===//
/// Typedefs
typedef std::vector<Record*> RecordVector;
typedef std::vector<std::string> StrVector;
//===----------------------------------------------------------------------===//
/// Constants
// Indentation strings.
const char * Indent1 = " ";
const char * Indent2 = " ";
const char * Indent3 = " ";
const char * Indent4 = " ";
// Default help string.
const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
// Name for the "sink" option.
const char * SinkOptionName = "AutoGeneratedSinkOption";
//===----------------------------------------------------------------------===//
/// Helper functions
const std::string& InitPtrToString(const Init* ptr) {
const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
return val.getValue();
}
int InitPtrToInt(const Init* ptr) {
const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
return val.getValue();
}
const DagInit& InitPtrToDagInitRef(const Init* ptr) {
const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
return val;
}
// checkNumberOfArguments - Ensure that the number of args in d is
// less than or equal to min_arguments, otherwise throw an exception.
void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
if (d->getNumArgs() < min_arguments)
throw "Property " + d->getOperator()->getAsString()
+ " has too few arguments!";
}
// isDagEmpty - is this DAG marked with an empty marker?
bool isDagEmpty (const DagInit* d) {
return d->getOperator()->getAsString() == "empty";
}
//===----------------------------------------------------------------------===//
/// Back-end specific code
// A command-line option can have one of the following types:
//
// Switch - a simple switch w/o arguments, e.g. -O2
//
// Parameter - an option that takes one(and only one) argument, e.g. -o file,
// --output=file
//
// ParameterList - same as Parameter, but more than one occurence
// of the option is allowed, e.g. -lm -lpthread
//
// Prefix - argument is everything after the prefix,
// e.g. -Wa,-foo,-bar, -DNAME=VALUE
//
// PrefixList - same as Prefix, but more than one option occurence is
// allowed
namespace OptionType {
enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
}
bool IsListOptionType (OptionType::OptionType t) {
return (t == OptionType::ParameterList || t == OptionType::PrefixList);
}
// Code duplication here is necessary because one option can affect
// several tools and those tools may have different actions associated
// with this option. GlobalOptionDescriptions are used to generate
// the option registration code, while ToolOptionDescriptions are used
// to generate tool-specific code.
/// OptionDescription - Base class for option descriptions.
struct OptionDescription {
OptionType::OptionType Type;
std::string Name;
OptionDescription(OptionType::OptionType t = OptionType::Switch,
const std::string& n = "")
: Type(t), Name(n)
{}
const char* GenTypeDeclaration() const {
switch (Type) {
case OptionType::PrefixList:
case OptionType::ParameterList:
return "cl::list<std::string>";
case OptionType::Switch:
return "cl::opt<bool>";
case OptionType::Parameter:
case OptionType::Prefix:
default:
return "cl::opt<std::string>";
}
}
// Escape commas and other symbols not allowed in the C++ variable
// names. Makes it possible to use options with names like "Wa,"
// (useful for prefix options).
std::string EscapeVariableName(const std::string& Var) const {
std::string ret;
for (unsigned i = 0; i != Var.size(); ++i) {
if (Var[i] == ',') {
ret += "_comma_";
}
else {
ret.push_back(Var[i]);
}
}
return ret;
}
std::string GenVariableName() const {
const std::string& EscapedName = EscapeVariableName(Name);
switch (Type) {
case OptionType::Switch:
return "AutoGeneratedSwitch" + EscapedName;
case OptionType::Prefix:
return "AutoGeneratedPrefix" + EscapedName;
case OptionType::PrefixList:
return "AutoGeneratedPrefixList" + EscapedName;
case OptionType::Parameter:
return "AutoGeneratedParameter" + EscapedName;
case OptionType::ParameterList:
default:
return "AutoGeneratedParameterList" + EscapedName;
}
}
};
// Global option description.
namespace GlobalOptionDescriptionFlags {
enum GlobalOptionDescriptionFlags { Required = 0x1 };
}
struct GlobalOptionDescription : public OptionDescription {
std::string Help;
unsigned Flags;
// We need to provide a default constructor because
// StringMap can only store DefaultConstructible objects.
GlobalOptionDescription() : OptionDescription(), Flags(0)
{}
GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
: OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
{}
bool isRequired() const {
return Flags & GlobalOptionDescriptionFlags::Required;
}
void setRequired() {
Flags |= GlobalOptionDescriptionFlags::Required;
}
/// Merge - Merge two option descriptions.
void Merge (const GlobalOptionDescription& other)
{
if (other.Type != Type)
throw "Conflicting definitions for the option " + Name + "!";
if (Help == DefaultHelpString)
Help = other.Help;
else if (other.Help != DefaultHelpString) {
llvm::cerr << "Warning: more than one help string defined for option "
+ Name + "\n";
}
Flags |= other.Flags;
}
};
/// GlobalOptionDescriptions - A GlobalOptionDescription array
/// together with some flags affecting generation of option
/// declarations.
struct GlobalOptionDescriptions {
typedef StringMap<GlobalOptionDescription> container_type;
typedef container_type::const_iterator const_iterator;
/// Descriptions - A list of GlobalOptionDescriptions.
container_type Descriptions;
/// HasSink - Should the emitter generate a "cl::sink" option?
bool HasSink;
const GlobalOptionDescription& FindOption(const std::string& OptName) const {
const_iterator I = Descriptions.find(OptName);
if (I != Descriptions.end())
return I->second;
else
throw OptName + ": no such option!";
}
// Support for STL-style iteration
const_iterator begin() const { return Descriptions.begin(); }
const_iterator end() const { return Descriptions.end(); }
};
// Tool-local option description.
// Properties without arguments are implemented as flags.
namespace ToolOptionDescriptionFlags {
enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
Forward = 0x2, UnpackValues = 0x4};
}
namespace OptionPropertyType {
enum OptionPropertyType { AppendCmd };
}
typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
OptionProperty;
typedef SmallVector<OptionProperty, 4> OptionPropertyList;
struct ToolOptionDescription : public OptionDescription {
unsigned Flags;
OptionPropertyList Props;
// StringMap can only store DefaultConstructible objects
ToolOptionDescription() : OptionDescription(), Flags(0) {}
ToolOptionDescription (OptionType::OptionType t, const std::string& n)
: OptionDescription(t, n)
{}
// Various boolean properties
bool isStopCompilation() const {
return Flags & ToolOptionDescriptionFlags::StopCompilation;
}
void setStopCompilation() {
Flags |= ToolOptionDescriptionFlags::StopCompilation;
}
bool isForward() const {
return Flags & ToolOptionDescriptionFlags::Forward;
}
void setForward() {
Flags |= ToolOptionDescriptionFlags::Forward;
}
bool isUnpackValues() const {
return Flags & ToolOptionDescriptionFlags::UnpackValues;
}
void setUnpackValues() {
Flags |= ToolOptionDescriptionFlags::UnpackValues;
}
void AddProperty (OptionPropertyType::OptionPropertyType t,
const std::string& val)
{
Props.push_back(std::make_pair(t, val));
}
};
typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
// Tool information record
namespace ToolFlags {
enum ToolFlags { Join = 0x1, Sink = 0x2 };
}
struct ToolProperties : public RefCountedBase<ToolProperties> {
std::string Name;
Init* CmdLine;
std::string InLanguage;
std::string OutLanguage;
std::string OutputSuffix;
unsigned Flags;
ToolOptionDescriptions OptDescs;
// Various boolean properties
void setSink() { Flags |= ToolFlags::Sink; }
bool isSink() const { return Flags & ToolFlags::Sink; }
void setJoin() { Flags |= ToolFlags::Join; }
bool isJoin() const { return Flags & ToolFlags::Join; }
// Default ctor here is needed because StringMap can only store
// DefaultConstructible objects
ToolProperties() : Flags(0) {}
ToolProperties (const std::string& n) : Name(n), Flags(0) {}
};
/// ToolPropertiesList - A list of Tool information records
/// IntrusiveRefCntPtrs are used here because StringMap has no copy
/// constructor (and we want to avoid copying ToolProperties anyway).
typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
/// CollectProperties - Function object for iterating over a list of
/// tool property records.
class CollectProperties {
private:
/// Implementation details
/// PropertyHandler - a function that extracts information
/// about a given tool property from its DAG representation
typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
/// PropertyHandlerMap - A map from property names to property
/// handlers.
typedef StringMap<PropertyHandler> PropertyHandlerMap;
/// OptionPropertyHandler - a function that extracts information
/// about a given option property from its DAG representation.
typedef void (CollectProperties::* OptionPropertyHandler)
(const DagInit*, GlobalOptionDescription &);
/// OptionPropertyHandlerMap - A map from option property names to
/// option property handlers
typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
// Static maps from strings to CollectProperties methods("handlers")
static PropertyHandlerMap propertyHandlers_;
static OptionPropertyHandlerMap optionPropertyHandlers_;
static bool staticMembersInitialized_;
/// This is where the information is stored
/// toolProps_ - Properties of the current Tool.
ToolProperties& toolProps_;
/// optDescs_ - OptionDescriptions table (used to register options
/// globally).
GlobalOptionDescriptions& optDescs_;
public:
explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
: toolProps_(p), optDescs_(d)
{
if (!staticMembersInitialized_) {
// Init tool property handlers
propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
propertyHandlers_["join"] = &CollectProperties::onJoin;
propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
propertyHandlers_["parameter_option"]
= &CollectProperties::onParameter;
propertyHandlers_["parameter_list_option"] =
&CollectProperties::onParameterList;
propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
propertyHandlers_["prefix_list_option"] =
&CollectProperties::onPrefixList;
propertyHandlers_["sink"] = &CollectProperties::onSink;
propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
// Init option property handlers
optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
optionPropertyHandlers_["stop_compilation"] =
&CollectProperties::onStopCompilation;
optionPropertyHandlers_["unpack_values"] =
&CollectProperties::onUnpackValues;
staticMembersInitialized_ = true;
}
}
/// operator() - Gets called for every tool property; Just forwards
/// to the corresponding property handler.
void operator() (Init* i) {
const DagInit& d = InitPtrToDagInitRef(i);
const std::string& property_name = d.getOperator()->getAsString();
PropertyHandlerMap::iterator method
= propertyHandlers_.find(property_name);
if (method != propertyHandlers_.end()) {
PropertyHandler h = method->second;
(this->*h)(&d);
}
else {
throw "Unknown tool property: " + property_name + "!";
}
}
private:
/// Property handlers --
/// Functions that extract information about tool properties from
/// DAG representation.
void onCmdLine (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolProps_.CmdLine = d->getArg(0);
}
void onInLanguage (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolProps_.InLanguage = InitPtrToString(d->getArg(0));
}
void onJoin (const DagInit* d) {
checkNumberOfArguments(d, 0);
toolProps_.setJoin();
}
void onOutLanguage (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
}
void onOutputSuffix (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
}
void onSink (const DagInit* d) {
checkNumberOfArguments(d, 0);
optDescs_.HasSink = true;
toolProps_.setSink();
}
void onSwitch (const DagInit* d) {
addOption(d, OptionType::Switch);
}
void onParameter (const DagInit* d) {
addOption(d, OptionType::Parameter);
}
void onParameterList (const DagInit* d) {
addOption(d, OptionType::ParameterList);
}
void onPrefix (const DagInit* d) {
addOption(d, OptionType::Prefix);
}
void onPrefixList (const DagInit* d) {
addOption(d, OptionType::PrefixList);
}
/// Option property handlers --
/// Methods that handle properties that are common for all types of
/// options (like append_cmd, stop_compilation)
void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
checkNumberOfArguments(d, 1);
std::string const& cmd = InitPtrToString(d->getArg(0));
toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
}
void onForward (const DagInit* d, GlobalOptionDescription& o) {
checkNumberOfArguments(d, 0);
toolProps_.OptDescs[o.Name].setForward();
}
void onHelp (const DagInit* d, GlobalOptionDescription& o) {
checkNumberOfArguments(d, 1);
const std::string& help_message = InitPtrToString(d->getArg(0));
o.Help = help_message;
}
void onRequired (const DagInit* d, GlobalOptionDescription& o) {
checkNumberOfArguments(d, 0);
o.setRequired();
}
void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
checkNumberOfArguments(d, 0);
if (o.Type != OptionType::Switch)
throw std::string("Only options of type Switch can stop compilation!");
toolProps_.OptDescs[o.Name].setStopCompilation();
}
void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
checkNumberOfArguments(d, 0);
toolProps_.OptDescs[o.Name].setUnpackValues();
}
/// Helper functions
// Add an option of type t
void addOption (const DagInit* d, OptionType::OptionType t) {
checkNumberOfArguments(d, 2);
const std::string& name = InitPtrToString(d->getArg(0));
GlobalOptionDescription o(t, name);
toolProps_.OptDescs[name].Type = t;
toolProps_.OptDescs[name].Name = name;
processOptionProperties(d, o);
insertDescription(o);
}
// Insert new GlobalOptionDescription into GlobalOptionDescriptions list
void insertDescription (const GlobalOptionDescription& o)
{
if (optDescs_.Descriptions.count(o.Name)) {
GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
D.Merge(o);
}
else {
optDescs_.Descriptions[o.Name] = o;
}
}
/// processOptionProperties - Go through the list of option
/// properties and call a corresponding handler for each.
///
/// Parameters:
/// name - option name
/// d - option property list
void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
// First argument is option name
checkNumberOfArguments(d, 2);
for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
const DagInit& option_property
= InitPtrToDagInitRef(d->getArg(B));
const std::string& option_property_name
= option_property.getOperator()->getAsString();
OptionPropertyHandlerMap::iterator method
= optionPropertyHandlers_.find(option_property_name);
if (method != optionPropertyHandlers_.end()) {
OptionPropertyHandler h = method->second;
(this->*h)(&option_property, o);
}
else {
throw "Unknown option property: " + option_property_name + "!";
}
}
}
};
// Static members of CollectProperties
CollectProperties::PropertyHandlerMap
CollectProperties::propertyHandlers_;
CollectProperties::OptionPropertyHandlerMap
CollectProperties::optionPropertyHandlers_;
bool CollectProperties::staticMembersInitialized_ = false;
/// CollectToolProperties - Gather information from the parsed
/// TableGen data (basically a wrapper for the CollectProperties
/// function object).
void CollectToolProperties (RecordVector::const_iterator B,
RecordVector::const_iterator E,
ToolPropertiesList& TPList,
GlobalOptionDescriptions& OptDescs)
{
// Iterate over a properties list of every Tool definition
for (;B!=E;++B) {
RecordVector::value_type T = *B;
ListInit* PropList = T->getValueAsListInit("properties");
IntrusiveRefCntPtr<ToolProperties>
ToolProps(new ToolProperties(T->getName()));
std::for_each(PropList->begin(), PropList->end(),
CollectProperties(*ToolProps, OptDescs));
TPList.push_back(ToolProps);
}
}
/// EmitCaseTest1Arg - Helper function used by
/// EmitCaseConstructHandler.
bool EmitCaseTest1Arg(const std::string& TestName,
const DagInit& d,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
checkNumberOfArguments(&d, 1);
const std::string& OptName = InitPtrToString(d.getArg(0));
if (TestName == "switch_on") {
const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
if (OptDesc.Type != OptionType::Switch)
throw OptName + ": incorrect option type!";
O << OptDesc.GenVariableName();
return true;
} else if (TestName == "input_languages_contain") {
O << "InLangs.count(\"" << OptName << "\") != 0";
return true;
}
return false;
}
/// EmitCaseTest2Args - Helper function used by
/// EmitCaseConstructHandler.
bool EmitCaseTest2Args(const std::string& TestName,
const DagInit& d,
const char* IndentLevel,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
checkNumberOfArguments(&d, 2);
const std::string& OptName = InitPtrToString(d.getArg(0));
const std::string& OptArg = InitPtrToString(d.getArg(1));
const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
if (TestName == "parameter_equals") {
if (OptDesc.Type != OptionType::Parameter
&& OptDesc.Type != OptionType::Prefix)
throw OptName + ": incorrect option type!";
O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
return true;
}
else if (TestName == "element_in_list") {
if (OptDesc.Type != OptionType::ParameterList
&& OptDesc.Type != OptionType::PrefixList)
throw OptName + ": incorrect option type!";
const std::string& VarName = OptDesc.GenVariableName();
O << "std::find(" << VarName << ".begin(),\n"
<< IndentLevel << Indent1 << VarName << ".end(), \""
<< OptArg << "\") != " << VarName << ".end()";
return true;
}
return false;
}
// Forward declaration.
// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
void EmitCaseTest(const DagInit& d, const char* IndentLevel,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O);
/// EmitLogicalOperationTest - Helper function used by
/// EmitCaseConstructHandler.
void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
const char* IndentLevel,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
O << '(';
for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
const DagInit& InnerTest = InitPtrToDagInitRef(d.getArg(j));
EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
if (j != NumArgs - 1)
O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
else
O << ')';
}
}
/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
void EmitCaseTest(const DagInit& d, const char* IndentLevel,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
const std::string& TestName = d.getOperator()->getAsString();
if (TestName == "and")
EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
else if (TestName == "or")
EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
return;
else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
return;
else
throw TestName + ": unknown edge property!";
}
// Emit code that handles the 'case' construct.
// Takes a function object that should emit code for every case clause.
// Callback's type is
// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
template <typename F>
void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
const F& Callback,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
assert(d->getOperator()->getAsString() == "case");
for (unsigned i = 0, numArgs = d->getNumArgs(); i != numArgs; ++i) {
const DagInit& Test = InitPtrToDagInitRef(d->getArg(i));
if (Test.getOperator()->getAsString() == "default") {
if (i+2 != numArgs)
throw std::string("The 'default' clause should be the last in the"
"'case' construct!");
O << IndentLevel << "else {\n";
}
else {
O << IndentLevel << "if (";
EmitCaseTest(Test, IndentLevel, OptDescs, O);
O << ") {\n";
}
++i;
if (i == numArgs)
throw "Case construct handler: no corresponding action "
"found for the test " + Test.getAsString() + '!';
Callback(d->getArg(i), IndentLevel, O);
O << IndentLevel << "}\n";
}
}
/// EmitForwardOptionPropertyHandlingCode - Helper function used to
/// implement EmitOptionPropertyHandlingCode(). Emits code for
/// handling the (forward) option property.
void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
std::ostream& O) {
switch (D.Type) {
case OptionType::Switch:
O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
break;
case OptionType::Parameter:
O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
break;
case OptionType::Prefix:
O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
<< D.GenVariableName() << ");\n";
break;
case OptionType::PrefixList:
O << Indent3 << "for (" << D.GenTypeDeclaration()
<< "::iterator B = " << D.GenVariableName() << ".begin(),\n"
<< Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
<< Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
<< "*B);\n";
break;
case OptionType::ParameterList:
O << Indent3 << "for (" << D.GenTypeDeclaration()
<< "::iterator B = " << D.GenVariableName() << ".begin(),\n"
<< Indent3 << "E = " << D.GenVariableName()
<< ".end() ; B != E; ++B) {\n"
<< Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
<< Indent4 << "vec.push_back(*B);\n"
<< Indent3 << "}\n";
break;
}
}
/// EmitOptionPropertyHandlingCode - Helper function used by
/// EmitGenerateActionMethod(). Emits code that handles option
/// properties.
void EmitOptionPropertyHandlingCode (const ToolProperties& P,
const ToolOptionDescription& D,
std::ostream& O)
{
// Start of the if-clause.
O << Indent2 << "if (";
if (D.Type == OptionType::Switch)
O << D.GenVariableName();
else
O << '!' << D.GenVariableName() << ".empty()";
O <<") {\n";
// Handle option properties that take an argument.
for (OptionPropertyList::const_iterator B = D.Props.begin(),
E = D.Props.end(); B!=E; ++B) {
const OptionProperty& val = *B;
switch (val.first) {
// (append_cmd cmd) property
case OptionPropertyType::AppendCmd:
O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
break;
// Other properties with argument
default:
break;
}
}
// Handle flags
// (forward) property
if (D.isForward())
EmitForwardOptionPropertyHandlingCode(D, O);
// (unpack_values) property
if (D.isUnpackValues()) {
if (IsListOptionType(D.Type)) {
O << Indent3 << "for (" << D.GenTypeDeclaration()
<< "::iterator B = " << D.GenVariableName() << ".begin(),\n"
<< Indent3 << "E = " << D.GenVariableName()
<< ".end(); B != E; ++B)\n"
<< Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
}
else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
O << Indent3 << "llvm::SplitString("
<< D.GenVariableName() << ", vec, \",\");\n";
}
else {
throw std::string("Switches can't have unpack_values property!");
}
}
// End of the if-clause.
O << Indent2 << "}\n";
}
void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
bool Version, const char* IndentLevel,
std::ostream& O) {
StrVector StrVec;
SplitString(InitPtrToString(CmdLine), StrVec);
if (InitPtrToString(CmdLine).empty())
throw "Tool " + ToolName + " has empty command line!";
StrVector::const_iterator I = StrVec.begin();
++I;
for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
const std::string& cmd = *I;
O << IndentLevel;
if (cmd == "$INFILE") {
if (Version)
O << "for (PathVector::const_iterator B = inFiles.begin()"
<< ", E = inFiles.end();\n"
<< IndentLevel << "B != E; ++B)\n"
<< IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
else
O << "vec.push_back(inFile.toString());\n";
}
else if (cmd == "$OUTFILE") {
O << "vec.push_back(outFile.toString());\n";
}
else {
O << "vec.push_back(\"" << cmd << "\");\n";
}
}
O << IndentLevel << "ret = Action(\"" << StrVec.at(0) << "\", vec);\n";
}
class EmitCmdLineVecFillCallback {
bool Version;
const std::string& ToolName;
public:
EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
: Version(Ver), ToolName(TN) {}
void operator()(const Init* Statement, const char* IndentLevel,
std::ostream& O) const
{
EmitCmdLineVecFill(Statement, ToolName, Version, IndentLevel, O);
}
};
// EmitGenerateActionMethod - Emit one of two versions of the
// Tool::GenerateAction() method.
void EmitGenerateActionMethod (const ToolProperties& P,
const GlobalOptionDescriptions& OptDescs,
bool Version, std::ostream& O) {
if (Version)
O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
else
O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
O << Indent2 << "const sys::Path& outFile,\n"
<< Indent2 << "const InputLanguagesSet& InLangs) const\n"
<< Indent1 << "{\n"
<< Indent2 << "Action ret;\n"
<< Indent2 << "std::vector<std::string> vec;\n";
// cmd_line is either a string or a 'case' construct.
if (typeid(*P.CmdLine) == typeid(StringInit))
EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
else
EmitCaseConstructHandler(&InitPtrToDagInitRef(P.CmdLine), Indent2,
EmitCmdLineVecFillCallback(Version, P.Name),
OptDescs, O);
// For every understood option, emit handling code.
for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
E = P.OptDescs.end(); B != E; ++B) {
const ToolOptionDescription& val = B->second;
EmitOptionPropertyHandlingCode(P, val, O);
}
// Handle the Sink property.
if (P.isSink()) {
O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
<< Indent3 << "vec.insert(vec.end(), "
<< SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
<< Indent2 << "}\n";
}
O << Indent2 << "return ret;\n"
<< Indent1 << "}\n\n";
}
/// EmitGenerateActionMethods - Emit two GenerateAction() methods for
/// a given Tool class.
void EmitGenerateActionMethods (const ToolProperties& P,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
if (!P.isJoin())
O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
<< Indent2 << "const llvm::sys::Path& outFile,\n"
<< Indent2 << "const InputLanguagesSet& InLangs) const\n"
<< Indent1 << "{\n"
<< Indent2 << "throw std::runtime_error(\"" << P.Name
<< " is not a Join tool!\");\n"
<< Indent1 << "}\n\n";
else
EmitGenerateActionMethod(P, OptDescs, true, O);
EmitGenerateActionMethod(P, OptDescs, false, O);
}
/// EmitIsLastMethod - Emit the IsLast() method for a given Tool
/// class.
void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "bool IsLast() const {\n"
<< Indent2 << "bool last = false;\n";
for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
E = P.OptDescs.end(); B != E; ++B) {
const ToolOptionDescription& val = B->second;
if (val.isStopCompilation())
O << Indent2
<< "if (" << val.GenVariableName()
<< ")\n" << Indent3 << "last = true;\n";
}
O << Indent2 << "return last;\n"
<< Indent1 << "}\n\n";
}
/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
/// methods for a given Tool class.
void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "const char* InputLanguage() const {\n"
<< Indent2 << "return \"" << P.InLanguage << "\";\n"
<< Indent1 << "}\n\n";
O << Indent1 << "const char* OutputLanguage() const {\n"
<< Indent2 << "return \"" << P.OutLanguage << "\";\n"
<< Indent1 << "}\n\n";
}
/// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
/// given Tool class.
void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "const char* OutputSuffix() const {\n"
<< Indent2 << "return \"" << P.OutputSuffix << "\";\n"
<< Indent1 << "}\n\n";
}
/// EmitNameMethod - Emit the Name() method for a given Tool class.
void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "const char* Name() const {\n"
<< Indent2 << "return \"" << P.Name << "\";\n"
<< Indent1 << "}\n\n";
}
/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
/// class.
void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
O << Indent1 << "bool IsJoin() const {\n";
if (P.isJoin())
O << Indent2 << "return true;\n";
else
O << Indent2 << "return false;\n";
O << Indent1 << "}\n\n";
}
/// EmitToolClassDefinition - Emit a Tool class definition.
void EmitToolClassDefinition (const ToolProperties& P,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
if (P.Name == "root")
return;
// Header
O << "class " << P.Name << " : public ";
if (P.isJoin())
O << "JoinTool";
else
O << "Tool";
O << " {\npublic:\n";
EmitNameMethod(P, O);
EmitInOutLanguageMethods(P, O);
EmitOutputSuffixMethod(P, O);
EmitIsJoinMethod(P, O);
EmitGenerateActionMethods(P, OptDescs, O);
EmitIsLastMethod(P, O);
// Close class definition
O << "};\n\n";
}
/// EmitOptionDescriptions - Iterate over a list of option
/// descriptions and emit registration code.
void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
std::ostream& O)
{
// Emit static cl::Option variables
for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
E = descs.end(); B!=E; ++B) {
const GlobalOptionDescription& val = B->second;
O << val.GenTypeDeclaration() << ' '
<< val.GenVariableName()
<< "(\"" << val.Name << '\"';
if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
O << ", cl::Prefix";
if (val.isRequired()) {
switch (val.Type) {
case OptionType::PrefixList:
case OptionType::ParameterList:
O << ", cl::OneOrMore";
break;
default:
O << ", cl::Required";
}
}
O << ", cl::desc(\"" << val.Help << "\"));\n";
}
if (descs.HasSink)
O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
O << '\n';
}
/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
{
// Get the relevant field out of RecordKeeper
Record* LangMapRecord = Records.getDef("LanguageMap");
if (!LangMapRecord)
throw std::string("Language map definition not found!");
ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
if (!LangsToSuffixesList)
throw std::string("Error in the language map definition!");
// Generate code
O << "void llvmc::PopulateLanguageMap(LanguageMap& language_map) {\n";
for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
const std::string& Lang = LangToSuffixes->getValueAsString("lang");
const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
for (unsigned i = 0; i < Suffixes->size(); ++i)
O << Indent1 << "language_map[\""
<< InitPtrToString(Suffixes->getElement(i))
<< "\"] = \"" << Lang << "\";\n";
}
O << "}\n\n";
}
/// FillInToolToLang - Fills in two tables that map tool names to
/// (input, output) languages. Used by the typechecker.
void FillInToolToLang (const ToolPropertiesList& TPList,
StringMap<std::string>& ToolToInLang,
StringMap<std::string>& ToolToOutLang) {
for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
B != E; ++B) {
const ToolProperties& P = *(*B);
ToolToInLang[P.Name] = P.InLanguage;
ToolToOutLang[P.Name] = P.OutLanguage;
}
}
/// TypecheckGraph - Check that names for output and input languages
/// on all edges do match.
// TOFIX: check for cycles.
// TOFIX: check for multiple default edges.
void TypecheckGraph (Record* CompilationGraph,
const ToolPropertiesList& TPList) {
StringMap<std::string> ToolToInLang;
StringMap<std::string> ToolToOutLang;
FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
ListInit* edges = CompilationGraph->getValueAsListInit("edges");
StringMap<std::string>::iterator IAE = ToolToInLang.end();
StringMap<std::string>::iterator IBE = ToolToOutLang.end();
for (unsigned i = 0; i < edges->size(); ++i) {
Record* Edge = edges->getElementAsRecord(i);
Record* A = Edge->getValueAsDef("a");
Record* B = Edge->getValueAsDef("b");
StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
if (IA == IAE)
throw A->getName() + ": no such tool!";
if (IB == IBE)
throw B->getName() + ": no such tool!";
if (A->getName() != "root" && IA->second != IB->second)
throw "Edge " + A->getName() + "->" + B->getName()
+ ": output->input language mismatch";
if (B->getName() == "root")
throw std::string("Edges back to the root are not allowed!");
}
}
// Helper function passed to EmitCaseConstructHandler by EmitEdgeClass.
void IncDecWeight (const Init* i, const char* IndentLevel,
std::ostream& O) {
const DagInit& d = InitPtrToDagInitRef(i);
const std::string& OpName = d.getOperator()->getAsString();
if (OpName == "inc_weight")
O << IndentLevel << Indent1 << "ret += ";
else if (OpName == "dec_weight")
O << IndentLevel << Indent1 << "ret -= ";
else
throw "Unknown operator in edge properties list: " + OpName + '!';
if (d.getNumArgs() > 0)
O << InitPtrToInt(d.getArg(0)) << ";\n";
else
O << "2;\n";
}
/// EmitEdgeClass - Emit a single Edge# class.
void EmitEdgeClass (unsigned N, const std::string& Target,
DagInit* Case, const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
// Class constructor.
O << "class Edge" << N << ": public Edge {\n"
<< "public:\n"
<< Indent1 << "Edge" << N << "() : Edge(\"" << Target
<< "\") {}\n\n"
// Function Weight().
<< Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
<< Indent2 << "unsigned ret = 0;\n";
// Handle the 'case' construct.
EmitCaseConstructHandler(Case, Indent2, IncDecWeight, OptDescs, O);
O << Indent2 << "return ret;\n"
<< Indent1 << "};\n\n};\n\n";
}
// Emit Edge* classes that represent graph edges.
void EmitEdgeClasses (Record* CompilationGraph,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
ListInit* edges = CompilationGraph->getValueAsListInit("edges");
for (unsigned i = 0; i < edges->size(); ++i) {
Record* Edge = edges->getElementAsRecord(i);
Record* B = Edge->getValueAsDef("b");
DagInit* Weight = Edge->getValueAsDag("weight");
if (isDagEmpty(Weight))
continue;
EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
}
}
/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
/// function.
void EmitPopulateCompilationGraph (Record* CompilationGraph,
std::ostream& O)
{
ListInit* edges = CompilationGraph->getValueAsListInit("edges");
// Generate code
O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
<< Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
// Insert vertices
RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
if (Tools.empty())
throw std::string("No tool definitions found!");
for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
const std::string& Name = (*B)->getName();
if (Name != "root")
O << Indent1 << "G.insertNode(new "
<< Name << "());\n";
}
O << '\n';
// Insert edges
for (unsigned i = 0; i < edges->size(); ++i) {
Record* Edge = edges->getElementAsRecord(i);
Record* A = Edge->getValueAsDef("a");
Record* B = Edge->getValueAsDef("b");
DagInit* Weight = Edge->getValueAsDag("weight");
O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
if (isDagEmpty(Weight))
O << "new SimpleEdge(\"" << B->getName() << "\")";
else
O << "new Edge" << i << "()";
O << ");\n";
}
O << "}\n\n";
}
// End of anonymous namespace
}
/// run - The back-end entry point.
void LLVMCConfigurationEmitter::run (std::ostream &O) {
// Emit file header.
EmitSourceFileHeader("LLVMC Configuration Library", O);
// Get a list of all defined Tools.
RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
if (Tools.empty())
throw std::string("No tool definitions found!");
// Gather information from the Tool description dags.
ToolPropertiesList tool_props;
GlobalOptionDescriptions opt_descs;
CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
// Emit global option registration code.
EmitOptionDescriptions(opt_descs, O);
// Emit PopulateLanguageMap() function
// (a language map maps from file extensions to language names).
EmitPopulateLanguageMap(Records, O);
// Emit Tool classes.
for (ToolPropertiesList::const_iterator B = tool_props.begin(),
E = tool_props.end(); B!=E; ++B)
EmitToolClassDefinition(*(*B), opt_descs, O);
Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
if (!CompilationGraphRecord)
throw std::string("Compilation graph description not found!");
// Typecheck the compilation graph.
TypecheckGraph(CompilationGraphRecord, tool_props);
// Emit Edge# classes.
EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
// Emit PopulateCompilationGraph() function.
EmitPopulateCompilationGraph(CompilationGraphRecord, O);
// EOF
}
|