1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class wrap target description classes used by the various code
11 // generation TableGen backends.  This makes it easier to access the data and
12 // provides a single place that needs to check it for validity.  All of these
13 // classes throw exceptions on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "Record.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Streams.h"
23 #include <set>
24 #include <algorithm>
25 using namespace llvm;
26 
27 static cl::opt<unsigned>
28 AsmWriterNum("asmwriternum", cl::init(0),
29              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
30 
31 /// getValueType - Return the MCV::ValueType that the specified TableGen record
32 /// corresponds to.
33 MVT::ValueType llvm::getValueType(Record *Rec) {
34   return (MVT::ValueType)Rec->getValueAsInt("Value");
35 }
36 
37 std::string llvm::getName(MVT::ValueType T) {
38   switch (T) {
39   case MVT::Other: return "UNKNOWN";
40   case MVT::i1:    return "MVT::i1";
41   case MVT::i8:    return "MVT::i8";
42   case MVT::i16:   return "MVT::i16";
43   case MVT::i32:   return "MVT::i32";
44   case MVT::i64:   return "MVT::i64";
45   case MVT::i128:  return "MVT::i128";
46   case MVT::iAny:  return "MVT::iAny";
47   case MVT::f32:   return "MVT::f32";
48   case MVT::f64:   return "MVT::f64";
49   case MVT::f80:   return "MVT::f80";
50   case MVT::f128:  return "MVT::f128";
51   case MVT::Flag:  return "MVT::Flag";
52   case MVT::isVoid:return "MVT::void";
53   case MVT::v8i8:  return "MVT::v8i8";
54   case MVT::v4i16: return "MVT::v4i16";
55   case MVT::v2i32: return "MVT::v2i32";
56   case MVT::v1i64: return "MVT::v1i64";
57   case MVT::v16i8: return "MVT::v16i8";
58   case MVT::v8i16: return "MVT::v8i16";
59   case MVT::v4i32: return "MVT::v4i32";
60   case MVT::v2i64: return "MVT::v2i64";
61   case MVT::v2f32: return "MVT::v2f32";
62   case MVT::v4f32: return "MVT::v4f32";
63   case MVT::v2f64: return "MVT::v2f64";
64   case MVT::v3i32: return "MVT::v3i32";
65   case MVT::v3f32: return "MVT::v3f32";
66   case MVT::iPTR:  return "TLI.getPointerTy()";
67   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
68   }
69 }
70 
71 std::string llvm::getEnumName(MVT::ValueType T) {
72   switch (T) {
73   case MVT::Other: return "MVT::Other";
74   case MVT::i1:    return "MVT::i1";
75   case MVT::i8:    return "MVT::i8";
76   case MVT::i16:   return "MVT::i16";
77   case MVT::i32:   return "MVT::i32";
78   case MVT::i64:   return "MVT::i64";
79   case MVT::i128:  return "MVT::i128";
80   case MVT::iAny:  return "MVT::iAny";
81   case MVT::f32:   return "MVT::f32";
82   case MVT::f64:   return "MVT::f64";
83   case MVT::f80:   return "MVT::f80";
84   case MVT::f128:  return "MVT::f128";
85   case MVT::Flag:  return "MVT::Flag";
86   case MVT::isVoid:return "MVT::isVoid";
87   case MVT::v8i8:  return "MVT::v8i8";
88   case MVT::v4i16: return "MVT::v4i16";
89   case MVT::v2i32: return "MVT::v2i32";
90   case MVT::v1i64: return "MVT::v1i64";
91   case MVT::v16i8: return "MVT::v16i8";
92   case MVT::v8i16: return "MVT::v8i16";
93   case MVT::v4i32: return "MVT::v4i32";
94   case MVT::v2i64: return "MVT::v2i64";
95   case MVT::v2f32: return "MVT::v2f32";
96   case MVT::v4f32: return "MVT::v4f32";
97   case MVT::v2f64: return "MVT::v2f64";
98   case MVT::v3i32: return "MVT::v3i32";
99   case MVT::v3f32: return "MVT::v3f32";
100   case MVT::iPTR:  return "TLI.getPointerTy()";
101   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
102   }
103 }
104 
105 
106 /// getTarget - Return the current instance of the Target class.
107 ///
108 CodeGenTarget::CodeGenTarget() {
109   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
110   if (Targets.size() == 0)
111     throw std::string("ERROR: No 'Target' subclasses defined!");
112   if (Targets.size() != 1)
113     throw std::string("ERROR: Multiple subclasses of Target defined!");
114   TargetRec = Targets[0];
115 }
116 
117 
118 const std::string &CodeGenTarget::getName() const {
119   return TargetRec->getName();
120 }
121 
122 Record *CodeGenTarget::getInstructionSet() const {
123   return TargetRec->getValueAsDef("InstructionSet");
124 }
125 
126 /// getAsmWriter - Return the AssemblyWriter definition for this target.
127 ///
128 Record *CodeGenTarget::getAsmWriter() const {
129   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
130   if (AsmWriterNum >= LI.size())
131     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
132   return LI[AsmWriterNum];
133 }
134 
135 void CodeGenTarget::ReadRegisters() const {
136   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
137   if (Regs.empty())
138     throw std::string("No 'Register' subclasses defined!");
139 
140   Registers.reserve(Regs.size());
141   Registers.assign(Regs.begin(), Regs.end());
142 }
143 
144 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
145   DeclaredSpillSize = R->getValueAsInt("SpillSize");
146   DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
147 }
148 
149 const std::string &CodeGenRegister::getName() const {
150   return TheDef->getName();
151 }
152 
153 void CodeGenTarget::ReadRegisterClasses() const {
154   std::vector<Record*> RegClasses =
155     Records.getAllDerivedDefinitions("RegisterClass");
156   if (RegClasses.empty())
157     throw std::string("No 'RegisterClass' subclasses defined!");
158 
159   RegisterClasses.reserve(RegClasses.size());
160   RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
161 }
162 
163 std::vector<unsigned char> CodeGenTarget::getRegisterVTs(Record *R) const {
164   std::vector<unsigned char> Result;
165   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
166   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
167     const CodeGenRegisterClass &RC = RegisterClasses[i];
168     for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
169       if (R == RC.Elements[ei]) {
170         const std::vector<MVT::ValueType> &InVTs = RC.getValueTypes();
171         for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
172           Result.push_back(InVTs[i]);
173       }
174     }
175   }
176   return Result;
177 }
178 
179 
180 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
181   // Rename anonymous register classes.
182   if (R->getName().size() > 9 && R->getName()[9] == '.') {
183     static unsigned AnonCounter = 0;
184     R->setName("AnonRegClass_"+utostr(AnonCounter++));
185   }
186 
187   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
188   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
189     Record *Type = TypeList[i];
190     if (!Type->isSubClassOf("ValueType"))
191       throw "RegTypes list member '" + Type->getName() +
192         "' does not derive from the ValueType class!";
193     VTs.push_back(getValueType(Type));
194   }
195   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
196 
197   std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
198   for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
199     Record *Reg = RegList[i];
200     if (!Reg->isSubClassOf("Register"))
201       throw "Register Class member '" + Reg->getName() +
202             "' does not derive from the Register class!";
203     Elements.push_back(Reg);
204   }
205 
206   std::vector<Record*> SubRegClassList =
207                         R->getValueAsListOfDefs("SubRegClassList");
208   for (unsigned i = 0, e = SubRegClassList.size(); i != e; ++i) {
209     Record *SubRegClass = SubRegClassList[i];
210     if (!SubRegClass->isSubClassOf("RegisterClass"))
211       throw "Register Class member '" + SubRegClass->getName() +
212             "' does not derive from the RegisterClass class!";
213     SubRegClasses.push_back(SubRegClass);
214   }
215 
216   // Allow targets to override the size in bits of the RegisterClass.
217   unsigned Size = R->getValueAsInt("Size");
218 
219   Namespace = R->getValueAsString("Namespace");
220   SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);
221   SpillAlignment = R->getValueAsInt("Alignment");
222   MethodBodies = R->getValueAsCode("MethodBodies");
223   MethodProtos = R->getValueAsCode("MethodProtos");
224 }
225 
226 const std::string &CodeGenRegisterClass::getName() const {
227   return TheDef->getName();
228 }
229 
230 void CodeGenTarget::ReadLegalValueTypes() const {
231   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
232   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
233     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
234       LegalValueTypes.push_back(RCs[i].VTs[ri]);
235 
236   // Remove duplicates.
237   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
238   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
239                                     LegalValueTypes.end()),
240                         LegalValueTypes.end());
241 }
242 
243 
244 void CodeGenTarget::ReadInstructions() const {
245   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
246   if (Insts.size() <= 2)
247     throw std::string("No 'Instruction' subclasses defined!");
248 
249   // Parse the instructions defined in the .td file.
250   std::string InstFormatName =
251     getAsmWriter()->getValueAsString("InstFormatName");
252 
253   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
254     std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
255     Instructions.insert(std::make_pair(Insts[i]->getName(),
256                                        CodeGenInstruction(Insts[i], AsmStr)));
257   }
258 }
259 
260 /// getInstructionsByEnumValue - Return all of the instructions defined by the
261 /// target, ordered by their enum value.
262 void CodeGenTarget::
263 getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
264                                                  &NumberedInstructions) {
265   std::map<std::string, CodeGenInstruction>::const_iterator I;
266   I = getInstructions().find("PHI");
267   if (I == Instructions.end()) throw "Could not find 'PHI' instruction!";
268   const CodeGenInstruction *PHI = &I->second;
269 
270   I = getInstructions().find("INLINEASM");
271   if (I == Instructions.end()) throw "Could not find 'INLINEASM' instruction!";
272   const CodeGenInstruction *INLINEASM = &I->second;
273 
274   I = getInstructions().find("LABEL");
275   if (I == Instructions.end()) throw "Could not find 'LABEL' instruction!";
276   const CodeGenInstruction *LABEL = &I->second;
277 
278   // Print out the rest of the instructions now.
279   NumberedInstructions.push_back(PHI);
280   NumberedInstructions.push_back(INLINEASM);
281   NumberedInstructions.push_back(LABEL);
282   for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
283     if (&II->second != PHI &&
284         &II->second != INLINEASM &&
285         &II->second != LABEL)
286       NumberedInstructions.push_back(&II->second);
287 }
288 
289 
290 /// isLittleEndianEncoding - Return whether this target encodes its instruction
291 /// in little-endian format, i.e. bits laid out in the order [0..n]
292 ///
293 bool CodeGenTarget::isLittleEndianEncoding() const {
294   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
295 }
296 
297 
298 
299 static void ParseConstraint(const std::string &CStr, CodeGenInstruction *I) {
300   // FIXME: Only supports TIED_TO for now.
301   std::string::size_type pos = CStr.find_first_of('=');
302   assert(pos != std::string::npos && "Unrecognized constraint");
303   std::string Name = CStr.substr(0, pos);
304 
305   // TIED_TO: $src1 = $dst
306   std::string::size_type wpos = Name.find_first_of(" \t");
307   if (wpos == std::string::npos)
308     throw "Illegal format for tied-to constraint: '" + CStr + "'";
309   std::string DestOpName = Name.substr(0, wpos);
310   std::pair<unsigned,unsigned> DestOp = I->ParseOperandName(DestOpName, false);
311 
312   Name = CStr.substr(pos+1);
313   wpos = Name.find_first_not_of(" \t");
314   if (wpos == std::string::npos)
315     throw "Illegal format for tied-to constraint: '" + CStr + "'";
316 
317   std::pair<unsigned,unsigned> SrcOp =
318     I->ParseOperandName(Name.substr(wpos), false);
319   if (SrcOp > DestOp)
320     throw "Illegal tied-to operand constraint '" + CStr + "'";
321 
322 
323   unsigned FlatOpNo = I->getFlattenedOperandNumber(SrcOp);
324   // Build the string for the operand.
325   std::string OpConstraint =
326     "((" + utostr(FlatOpNo) + " << 16) | (1 << TOI::TIED_TO))";
327 
328 
329   if (!I->OperandList[DestOp.first].Constraints[DestOp.second].empty())
330     throw "Operand '" + DestOpName + "' cannot have multiple constraints!";
331   I->OperandList[DestOp.first].Constraints[DestOp.second] = OpConstraint;
332 }
333 
334 static void ParseConstraints(const std::string &CStr, CodeGenInstruction *I) {
335   // Make sure the constraints list for each operand is large enough to hold
336   // constraint info, even if none is present.
337   for (unsigned i = 0, e = I->OperandList.size(); i != e; ++i)
338     I->OperandList[i].Constraints.resize(I->OperandList[i].MINumOperands);
339 
340   if (CStr.empty()) return;
341 
342   const std::string delims(",");
343   std::string::size_type bidx, eidx;
344 
345   bidx = CStr.find_first_not_of(delims);
346   while (bidx != std::string::npos) {
347     eidx = CStr.find_first_of(delims, bidx);
348     if (eidx == std::string::npos)
349       eidx = CStr.length();
350 
351     ParseConstraint(CStr.substr(bidx, eidx), I);
352     bidx = CStr.find_first_not_of(delims, eidx);
353   }
354 }
355 
356 CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)
357   : TheDef(R), AsmString(AsmStr) {
358   Name      = R->getValueAsString("Name");
359   Namespace = R->getValueAsString("Namespace");
360 
361   isReturn     = R->getValueAsBit("isReturn");
362   isBranch     = R->getValueAsBit("isBranch");
363   isBarrier    = R->getValueAsBit("isBarrier");
364   isCall       = R->getValueAsBit("isCall");
365   isLoad       = R->getValueAsBit("isLoad");
366   isStore      = R->getValueAsBit("isStore");
367   bool isTwoAddress = R->getValueAsBit("isTwoAddress");
368   isPredicable = R->getValueAsBit("isPredicable");
369   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
370   isCommutable = R->getValueAsBit("isCommutable");
371   isTerminator = R->getValueAsBit("isTerminator");
372   isReMaterializable = R->getValueAsBit("isReMaterializable");
373   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
374   usesCustomDAGSchedInserter = R->getValueAsBit("usesCustomDAGSchedInserter");
375   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
376   isNotDuplicable = R->getValueAsBit("isNotDuplicable");
377   hasOptionalDef = false;
378   hasVariableNumberOfOperands = false;
379 
380   DagInit *DI;
381   try {
382     DI = R->getValueAsDag("OutOperandList");
383   } catch (...) {
384     // Error getting operand list, just ignore it (sparcv9).
385     AsmString.clear();
386     OperandList.clear();
387     return;
388   }
389   NumDefs = DI->getNumArgs();
390 
391   DagInit *IDI;
392   try {
393     IDI = R->getValueAsDag("InOperandList");
394   } catch (...) {
395     // Error getting operand list, just ignore it (sparcv9).
396     AsmString.clear();
397     OperandList.clear();
398     return;
399   }
400   DI = (DagInit*)(new BinOpInit(BinOpInit::CONCAT, DI, IDI))->Fold();
401 
402   unsigned MIOperandNo = 0;
403   std::set<std::string> OperandNames;
404   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
405     DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));
406     if (!Arg)
407       throw "Illegal operand for the '" + R->getName() + "' instruction!";
408 
409     Record *Rec = Arg->getDef();
410     std::string PrintMethod = "printOperand";
411     unsigned NumOps = 1;
412     DagInit *MIOpInfo = 0;
413     if (Rec->isSubClassOf("Operand")) {
414       PrintMethod = Rec->getValueAsString("PrintMethod");
415       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
416 
417       // Verify that MIOpInfo has an 'ops' root value.
418       if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ||
419           dynamic_cast<DefInit*>(MIOpInfo->getOperator())
420                ->getDef()->getName() != "ops")
421         throw "Bad value for MIOperandInfo in operand '" + Rec->getName() +
422               "'\n";
423 
424       // If we have MIOpInfo, then we have #operands equal to number of entries
425       // in MIOperandInfo.
426       if (unsigned NumArgs = MIOpInfo->getNumArgs())
427         NumOps = NumArgs;
428 
429       if (Rec->isSubClassOf("PredicateOperand"))
430         isPredicable = true;
431       else if (Rec->isSubClassOf("OptionalDefOperand"))
432         hasOptionalDef = true;
433     } else if (Rec->getName() == "variable_ops") {
434       hasVariableNumberOfOperands = true;
435       continue;
436     } else if (!Rec->isSubClassOf("RegisterClass") &&
437                Rec->getName() != "ptr_rc")
438       throw "Unknown operand class '" + Rec->getName() +
439             "' in instruction '" + R->getName() + "' instruction!";
440 
441     // Check that the operand has a name and that it's unique.
442     if (DI->getArgName(i).empty())
443       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
444         " has no name!";
445     if (!OperandNames.insert(DI->getArgName(i)).second)
446       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
447         " has the same name as a previous operand!";
448 
449     OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod,
450                                       MIOperandNo, NumOps, MIOpInfo));
451     MIOperandNo += NumOps;
452   }
453 
454   // Parse Constraints.
455   ParseConstraints(R->getValueAsString("Constraints"), this);
456 
457   // For backward compatibility: isTwoAddress means operand 1 is tied to
458   // operand 0.
459   if (isTwoAddress) {
460     if (!OperandList[1].Constraints[0].empty())
461       throw R->getName() + ": cannot use isTwoAddress property: instruction "
462             "already has constraint set!";
463     OperandList[1].Constraints[0] = "((0 << 16) | (1 << TOI::TIED_TO))";
464   }
465 
466   // Any operands with unset constraints get 0 as their constraint.
467   for (unsigned op = 0, e = OperandList.size(); op != e; ++op)
468     for (unsigned j = 0, e = OperandList[op].MINumOperands; j != e; ++j)
469       if (OperandList[op].Constraints[j].empty())
470         OperandList[op].Constraints[j] = "0";
471 
472   // Parse the DisableEncoding field.
473   std::string DisableEncoding = R->getValueAsString("DisableEncoding");
474   while (1) {
475     std::string OpName = getToken(DisableEncoding, " ,\t");
476     if (OpName.empty()) break;
477 
478     // Figure out which operand this is.
479     std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
480 
481     // Mark the operand as not-to-be encoded.
482     if (Op.second >= OperandList[Op.first].DoNotEncode.size())
483       OperandList[Op.first].DoNotEncode.resize(Op.second+1);
484     OperandList[Op.first].DoNotEncode[Op.second] = true;
485   }
486 }
487 
488 
489 
490 /// getOperandNamed - Return the index of the operand with the specified
491 /// non-empty name.  If the instruction does not have an operand with the
492 /// specified name, throw an exception.
493 ///
494 unsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {
495   assert(!Name.empty() && "Cannot search for operand with no name!");
496   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
497     if (OperandList[i].Name == Name) return i;
498   throw "Instruction '" + TheDef->getName() +
499         "' does not have an operand named '$" + Name + "'!";
500 }
501 
502 std::pair<unsigned,unsigned>
503 CodeGenInstruction::ParseOperandName(const std::string &Op,
504                                      bool AllowWholeOp) {
505   if (Op.empty() || Op[0] != '$')
506     throw TheDef->getName() + ": Illegal operand name: '" + Op + "'";
507 
508   std::string OpName = Op.substr(1);
509   std::string SubOpName;
510 
511   // Check to see if this is $foo.bar.
512   std::string::size_type DotIdx = OpName.find_first_of(".");
513   if (DotIdx != std::string::npos) {
514     SubOpName = OpName.substr(DotIdx+1);
515     if (SubOpName.empty())
516       throw TheDef->getName() + ": illegal empty suboperand name in '" +Op +"'";
517     OpName = OpName.substr(0, DotIdx);
518   }
519 
520   unsigned OpIdx = getOperandNamed(OpName);
521 
522   if (SubOpName.empty()) {  // If no suboperand name was specified:
523     // If one was needed, throw.
524     if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
525         SubOpName.empty())
526       throw TheDef->getName() + ": Illegal to refer to"
527             " whole operand part of complex operand '" + Op + "'";
528 
529     // Otherwise, return the operand.
530     return std::make_pair(OpIdx, 0U);
531   }
532 
533   // Find the suboperand number involved.
534   DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
535   if (MIOpInfo == 0)
536     throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
537 
538   // Find the operand with the right name.
539   for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
540     if (MIOpInfo->getArgName(i) == SubOpName)
541       return std::make_pair(OpIdx, i);
542 
543   // Otherwise, didn't find it!
544   throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
545 }
546 
547 
548 
549 
550 //===----------------------------------------------------------------------===//
551 // ComplexPattern implementation
552 //
553 ComplexPattern::ComplexPattern(Record *R) {
554   Ty          = ::getValueType(R->getValueAsDef("Ty"));
555   NumOperands = R->getValueAsInt("NumOperands");
556   SelectFunc  = R->getValueAsString("SelectFunc");
557   RootNodes   = R->getValueAsListOfDefs("RootNodes");
558 
559   // Parse the properties.
560   Properties = 0;
561   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
562   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
563     if (PropList[i]->getName() == "SDNPHasChain") {
564       Properties |= 1 << SDNPHasChain;
565     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
566       Properties |= 1 << SDNPOptInFlag;
567     } else {
568       cerr << "Unsupported SD Node property '" << PropList[i]->getName()
569            << "' on ComplexPattern '" << R->getName() << "'!\n";
570       exit(1);
571     }
572 }
573 
574 //===----------------------------------------------------------------------===//
575 // CodeGenIntrinsic Implementation
576 //===----------------------------------------------------------------------===//
577 
578 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
579   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
580 
581   std::vector<CodeGenIntrinsic> Result;
582 
583   // If we are in the context of a target .td file, get the target info so that
584   // we can decode the current intptr_t.
585   CodeGenTarget *CGT = 0;
586   if (Records.getClass("Target") &&
587       Records.getAllDerivedDefinitions("Target").size() == 1)
588     CGT = new CodeGenTarget();
589 
590   for (unsigned i = 0, e = I.size(); i != e; ++i)
591     Result.push_back(CodeGenIntrinsic(I[i], CGT));
592   delete CGT;
593   return Result;
594 }
595 
596 CodeGenIntrinsic::CodeGenIntrinsic(Record *R, CodeGenTarget *CGT) {
597   TheDef = R;
598   std::string DefName = R->getName();
599   ModRef = WriteMem;
600   isOverloaded = false;
601 
602   if (DefName.size() <= 4 ||
603       std::string(DefName.begin(), DefName.begin()+4) != "int_")
604     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
605   EnumName = std::string(DefName.begin()+4, DefName.end());
606   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
607     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
608   TargetPrefix   = R->getValueAsString("TargetPrefix");
609   Name = R->getValueAsString("LLVMName");
610   if (Name == "") {
611     // If an explicit name isn't specified, derive one from the DefName.
612     Name = "llvm.";
613     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
614       if (EnumName[i] == '_')
615         Name += '.';
616       else
617         Name += EnumName[i];
618   } else {
619     // Verify it starts with "llvm.".
620     if (Name.size() <= 5 ||
621         std::string(Name.begin(), Name.begin()+5) != "llvm.")
622       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
623   }
624 
625   // If TargetPrefix is specified, make sure that Name starts with
626   // "llvm.<targetprefix>.".
627   if (!TargetPrefix.empty()) {
628     if (Name.size() < 6+TargetPrefix.size() ||
629         std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size())
630         != (TargetPrefix+"."))
631       throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
632         TargetPrefix + ".'!";
633   }
634 
635   // Parse the list of argument types.
636   ListInit *TypeList = R->getValueAsListInit("Types");
637   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
638     Record *TyEl = TypeList->getElementAsRecord(i);
639     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
640     ArgTypes.push_back(TyEl->getValueAsString("TypeVal"));
641     MVT::ValueType VT = getValueType(TyEl->getValueAsDef("VT"));
642     isOverloaded |= VT == MVT::iAny;
643     ArgVTs.push_back(VT);
644     ArgTypeDefs.push_back(TyEl);
645   }
646   if (ArgTypes.size() == 0)
647     throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
648 
649 
650   // Parse the intrinsic properties.
651   ListInit *PropList = R->getValueAsListInit("Properties");
652   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
653     Record *Property = PropList->getElementAsRecord(i);
654     assert(Property->isSubClassOf("IntrinsicProperty") &&
655            "Expected a property!");
656 
657     if (Property->getName() == "IntrNoMem")
658       ModRef = NoMem;
659     else if (Property->getName() == "IntrReadArgMem")
660       ModRef = ReadArgMem;
661     else if (Property->getName() == "IntrReadMem")
662       ModRef = ReadMem;
663     else if (Property->getName() == "IntrWriteArgMem")
664       ModRef = WriteArgMem;
665     else if (Property->getName() == "IntrWriteMem")
666       ModRef = WriteMem;
667     else
668       assert(0 && "Unknown property!");
669   }
670 }
671