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