Inline asm multiple alternative constraints development phase 2 - improved basic...
[oota-llvm.git] / lib / VMCore / InlineAsm.cpp
1 //===-- InlineAsm.cpp - Implement the InlineAsm class ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the InlineAsm class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/InlineAsm.h"
15 #include "ConstantsContext.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/DerivedTypes.h"
18 #include <algorithm>
19 #include <cctype>
20 using namespace llvm;
21
22 // Implement the first virtual method in this class in this file so the
23 // InlineAsm vtable is emitted here.
24 InlineAsm::~InlineAsm() {
25 }
26
27
28 InlineAsm *InlineAsm::get(const FunctionType *Ty, StringRef AsmString,
29                           StringRef Constraints, bool hasSideEffects,
30                           bool isAlignStack) {
31   InlineAsmKeyType Key(AsmString, Constraints, hasSideEffects, isAlignStack);
32   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
33   return pImpl->InlineAsms.getOrCreate(PointerType::getUnqual(Ty), Key);
34 }
35
36 InlineAsm::InlineAsm(const PointerType *Ty, const std::string &asmString,
37                      const std::string &constraints, bool hasSideEffects,
38                      bool isAlignStack)
39   : Value(Ty, Value::InlineAsmVal),
40     AsmString(asmString), 
41     Constraints(constraints), HasSideEffects(hasSideEffects), 
42     IsAlignStack(isAlignStack) {
43
44   // Do various checks on the constraint string and type.
45   assert(Verify(getFunctionType(), constraints) &&
46          "Function type not legal for constraints!");
47 }
48
49 void InlineAsm::destroyConstant() {
50   delete this;
51 }
52
53 const FunctionType *InlineAsm::getFunctionType() const {
54   return cast<FunctionType>(getType()->getElementType());
55 }
56     
57 ///Default constructor.
58 InlineAsm::ConstraintInfo::ConstraintInfo() :
59   Type(isInput), isEarlyClobber(false),
60   MatchingInput(-1), isCommutative(false),
61   isIndirect(false), isMultipleAlternative(false),
62   currentAlternativeIndex(0) {
63 }
64
65 /// Copy constructor.
66 InlineAsm::ConstraintInfo::ConstraintInfo(const ConstraintInfo &other) :
67   Type(other.Type), isEarlyClobber(other.isEarlyClobber),
68   MatchingInput(other.MatchingInput), isCommutative(other.isCommutative),
69   isIndirect(other.isIndirect), Codes(other.Codes),
70   isMultipleAlternative(other.isMultipleAlternative),
71   multipleAlternatives(other.multipleAlternatives),
72   currentAlternativeIndex(other.currentAlternativeIndex) {
73 }
74
75 /// Parse - Analyze the specified string (e.g. "==&{eax}") and fill in the
76 /// fields in this structure.  If the constraint string is not understood,
77 /// return true, otherwise return false.
78 bool InlineAsm::ConstraintInfo::Parse(StringRef Str,
79                      InlineAsm::ConstraintInfoVector &ConstraintsSoFar) {
80   StringRef::iterator I = Str.begin(), E = Str.end();
81   unsigned multipleAlternativeCount = Str.count('|') + 1;
82   unsigned multipleAlternativeIndex = 0;
83   ConstraintCodeVector *pCodes = &Codes;
84   
85   // Initialize
86   isMultipleAlternative = (multipleAlternativeCount > 1 ? true : false);
87   if (isMultipleAlternative) {
88     multipleAlternatives.resize(multipleAlternativeCount);
89     pCodes = &multipleAlternatives[0].Codes;
90   }
91   Type = isInput;
92   isEarlyClobber = false;
93   MatchingInput = -1;
94   isCommutative = false;
95   isIndirect = false;
96   currentAlternativeIndex = 0;
97   
98   // Parse prefixes.
99   if (*I == '~') {
100     Type = isClobber;
101     ++I;
102   } else if (*I == '=') {
103     ++I;
104     Type = isOutput;
105   }
106   
107   if (*I == '*') {
108     isIndirect = true;
109     ++I;
110   }
111   
112   if (I == E) return true;  // Just a prefix, like "==" or "~".
113   
114   // Parse the modifiers.
115   bool DoneWithModifiers = false;
116   while (!DoneWithModifiers) {
117     switch (*I) {
118     default:
119       DoneWithModifiers = true;
120       break;
121     case '&':     // Early clobber.
122       if (Type != isOutput ||      // Cannot early clobber anything but output.
123           isEarlyClobber)          // Reject &&&&&&
124         return true;
125       isEarlyClobber = true;
126       break;
127     case '%':     // Commutative.
128       if (Type == isClobber ||     // Cannot commute clobbers.
129           isCommutative)           // Reject %%%%%
130         return true;
131       isCommutative = true;
132       break;
133     case '#':     // Comment.
134     case '*':     // Register preferencing.
135       return true;     // Not supported.
136     }
137     
138     if (!DoneWithModifiers) {
139       ++I;
140       if (I == E) return true;   // Just prefixes and modifiers!
141     }
142   }
143   
144   // Parse the various constraints.
145   while (I != E) {
146     if (*I == '{') {   // Physical register reference.
147       // Find the end of the register name.
148       StringRef::iterator ConstraintEnd = std::find(I+1, E, '}');
149       if (ConstraintEnd == E) return true;  // "{foo"
150       pCodes->push_back(std::string(I, ConstraintEnd+1));
151       I = ConstraintEnd+1;
152     } else if (isdigit(*I)) {     // Matching Constraint
153       // Maximal munch numbers.
154       StringRef::iterator NumStart = I;
155       while (I != E && isdigit(*I))
156         ++I;
157       pCodes->push_back(std::string(NumStart, I));
158       unsigned N = atoi(pCodes->back().c_str());
159       // Check that this is a valid matching constraint!
160       if (N >= ConstraintsSoFar.size() || ConstraintsSoFar[N].Type != isOutput||
161           Type != isInput)
162         return true;  // Invalid constraint number.
163       
164       // If Operand N already has a matching input, reject this.  An output
165       // can't be constrained to the same value as multiple inputs.
166       if (isMultipleAlternative) {
167         InlineAsm::SubConstraintInfo &scInfo =
168           ConstraintsSoFar[N].multipleAlternatives[multipleAlternativeIndex];
169         if (scInfo.MatchingInput != -1)
170           return true;
171         // Note that operand #n has a matching input.
172         scInfo.MatchingInput = ConstraintsSoFar.size();
173       } else {
174         if (ConstraintsSoFar[N].hasMatchingInput())
175           return true;
176         // Note that operand #n has a matching input.
177         ConstraintsSoFar[N].MatchingInput = ConstraintsSoFar.size();
178         }
179     } else if (*I == '|') {
180       multipleAlternativeIndex++;
181       pCodes = &multipleAlternatives[multipleAlternativeIndex].Codes;
182       ++I;
183     } else {
184       // Single letter constraint.
185       pCodes->push_back(std::string(I, I+1));
186       ++I;
187     }
188   }
189
190   return false;
191 }
192
193 /// selectAlternative - Point this constraint to the alternative constraint
194 /// indicated by the index.
195 void InlineAsm::ConstraintInfo::selectAlternative(unsigned index) {
196   if (index < multipleAlternatives.size()) {
197     currentAlternativeIndex = index;
198     InlineAsm::SubConstraintInfo &scInfo =
199       multipleAlternatives[currentAlternativeIndex];
200     MatchingInput = scInfo.MatchingInput;
201     Codes = scInfo.Codes;
202   }
203 }
204
205 InlineAsm::ConstraintInfoVector
206 InlineAsm::ParseConstraints(StringRef Constraints) {
207   ConstraintInfoVector Result;
208   
209   // Scan the constraints string.
210   for (StringRef::iterator I = Constraints.begin(),
211          E = Constraints.end(); I != E; ) {
212     ConstraintInfo Info;
213
214     // Find the end of this constraint.
215     StringRef::iterator ConstraintEnd = std::find(I, E, ',');
216
217     if (ConstraintEnd == I ||  // Empty constraint like ",,"
218         Info.Parse(StringRef(I, ConstraintEnd-I), Result)) {
219       Result.clear();          // Erroneous constraint?
220       break;
221     }
222
223     Result.push_back(Info);
224     
225     // ConstraintEnd may be either the next comma or the end of the string.  In
226     // the former case, we skip the comma.
227     I = ConstraintEnd;
228     if (I != E) {
229       ++I;
230       if (I == E) { Result.clear(); break; }    // don't allow "xyz,"
231     }
232   }
233   
234   return Result;
235 }
236
237 /// Verify - Verify that the specified constraint string is reasonable for the
238 /// specified function type, and otherwise validate the constraint string.
239 bool InlineAsm::Verify(const FunctionType *Ty, StringRef ConstStr) {
240   if (Ty->isVarArg()) return false;
241   
242   ConstraintInfoVector Constraints = ParseConstraints(ConstStr);
243   
244   // Error parsing constraints.
245   if (Constraints.empty() && !ConstStr.empty()) return false;
246   
247   unsigned NumOutputs = 0, NumInputs = 0, NumClobbers = 0;
248   unsigned NumIndirect = 0;
249   
250   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
251     switch (Constraints[i].Type) {
252     case InlineAsm::isOutput:
253       if ((NumInputs-NumIndirect) != 0 || NumClobbers != 0)
254         return false;  // outputs before inputs and clobbers.
255       if (!Constraints[i].isIndirect) {
256         ++NumOutputs;
257         break;
258       }
259       ++NumIndirect;
260       // FALLTHROUGH for Indirect Outputs.
261     case InlineAsm::isInput:
262       if (NumClobbers) return false;               // inputs before clobbers.
263       ++NumInputs;
264       break;
265     case InlineAsm::isClobber:
266       ++NumClobbers;
267       break;
268     }
269   }
270   
271   switch (NumOutputs) {
272   case 0:
273     if (!Ty->getReturnType()->isVoidTy()) return false;
274     break;
275   case 1:
276     if (Ty->getReturnType()->isStructTy()) return false;
277     break;
278   default:
279     const StructType *STy = dyn_cast<StructType>(Ty->getReturnType());
280     if (STy == 0 || STy->getNumElements() != NumOutputs)
281       return false;
282     break;
283   }      
284   
285   if (Ty->getNumParams() != NumInputs) return false;
286   return true;
287 }
288