Oops...I committed too much.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuild.cpp
1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
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 implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Module.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/DwarfWriter.h"
41 #include "llvm/Analysis/DebugInfo.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetFrameInfo.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetIntrinsicInfo.h"
47 #include "llvm/Target/TargetLowering.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include <algorithm>
56 using namespace llvm;
57
58 /// LimitFloatPrecision - Generate low-precision inline sequences for
59 /// some float libcalls (6, 8 or 12 bits).
60 static unsigned LimitFloatPrecision;
61
62 static cl::opt<unsigned, true>
63 LimitFPPrecision("limit-float-precision",
64                  cl::desc("Generate low-precision inline sequences "
65                           "for some float libcalls"),
66                  cl::location(LimitFloatPrecision),
67                  cl::init(0));
68
69 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
70 /// of insertvalue or extractvalue indices that identify a member, return
71 /// the linearized index of the start of the member.
72 ///
73 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
74                                    const unsigned *Indices,
75                                    const unsigned *IndicesEnd,
76                                    unsigned CurIndex = 0) {
77   // Base case: We're done.
78   if (Indices && Indices == IndicesEnd)
79     return CurIndex;
80
81   // Given a struct type, recursively traverse the elements.
82   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
83     for (StructType::element_iterator EB = STy->element_begin(),
84                                       EI = EB,
85                                       EE = STy->element_end();
86         EI != EE; ++EI) {
87       if (Indices && *Indices == unsigned(EI - EB))
88         return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
89       CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
90     }
91     return CurIndex;
92   }
93   // Given an array type, recursively traverse the elements.
94   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
95     const Type *EltTy = ATy->getElementType();
96     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
97       if (Indices && *Indices == i)
98         return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
99       CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
100     }
101     return CurIndex;
102   }
103   // We haven't found the type we're looking for, so keep searching.
104   return CurIndex + 1;
105 }
106
107 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
108 /// MVTs that represent all the individual underlying
109 /// non-aggregate types that comprise it.
110 ///
111 /// If Offsets is non-null, it points to a vector to be filled in
112 /// with the in-memory offsets of each of the individual values.
113 ///
114 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
115                             SmallVectorImpl<MVT> &ValueVTs,
116                             SmallVectorImpl<uint64_t> *Offsets = 0,
117                             uint64_t StartingOffset = 0) {
118   // Given a struct type, recursively traverse the elements.
119   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
120     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
121     for (StructType::element_iterator EB = STy->element_begin(),
122                                       EI = EB,
123                                       EE = STy->element_end();
124          EI != EE; ++EI)
125       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
126                       StartingOffset + SL->getElementOffset(EI - EB));
127     return;
128   }
129   // Given an array type, recursively traverse the elements.
130   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
131     const Type *EltTy = ATy->getElementType();
132     uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
133     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
134       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
135                       StartingOffset + i * EltSize);
136     return;
137   }
138   // Base case: we can get an MVT for this LLVM IR type.
139   ValueVTs.push_back(TLI.getValueType(Ty));
140   if (Offsets)
141     Offsets->push_back(StartingOffset);
142 }
143
144 namespace llvm {
145   /// RegsForValue - This struct represents the registers (physical or virtual)
146   /// that a particular set of values is assigned, and the type information about
147   /// the value. The most common situation is to represent one value at a time,
148   /// but struct or array values are handled element-wise as multiple values.
149   /// The splitting of aggregates is performed recursively, so that we never
150   /// have aggregate-typed registers. The values at this point do not necessarily
151   /// have legal types, so each value may require one or more registers of some
152   /// legal type.
153   ///
154   struct VISIBILITY_HIDDEN RegsForValue {
155     /// TLI - The TargetLowering object.
156     ///
157     const TargetLowering *TLI;
158
159     /// ValueVTs - The value types of the values, which may not be legal, and
160     /// may need be promoted or synthesized from one or more registers.
161     ///
162     SmallVector<MVT, 4> ValueVTs;
163
164     /// RegVTs - The value types of the registers. This is the same size as
165     /// ValueVTs and it records, for each value, what the type of the assigned
166     /// register or registers are. (Individual values are never synthesized
167     /// from more than one type of register.)
168     ///
169     /// With virtual registers, the contents of RegVTs is redundant with TLI's
170     /// getRegisterType member function, however when with physical registers
171     /// it is necessary to have a separate record of the types.
172     ///
173     SmallVector<MVT, 4> RegVTs;
174
175     /// Regs - This list holds the registers assigned to the values.
176     /// Each legal or promoted value requires one register, and each
177     /// expanded value requires multiple registers.
178     ///
179     SmallVector<unsigned, 4> Regs;
180
181     RegsForValue() : TLI(0) {}
182
183     RegsForValue(const TargetLowering &tli,
184                  const SmallVector<unsigned, 4> &regs,
185                  MVT regvt, MVT valuevt)
186       : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
187     RegsForValue(const TargetLowering &tli,
188                  const SmallVector<unsigned, 4> &regs,
189                  const SmallVector<MVT, 4> &regvts,
190                  const SmallVector<MVT, 4> &valuevts)
191       : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
192     RegsForValue(const TargetLowering &tli,
193                  unsigned Reg, const Type *Ty) : TLI(&tli) {
194       ComputeValueVTs(tli, Ty, ValueVTs);
195
196       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
197         MVT ValueVT = ValueVTs[Value];
198         unsigned NumRegs = TLI->getNumRegisters(ValueVT);
199         MVT RegisterVT = TLI->getRegisterType(ValueVT);
200         for (unsigned i = 0; i != NumRegs; ++i)
201           Regs.push_back(Reg + i);
202         RegVTs.push_back(RegisterVT);
203         Reg += NumRegs;
204       }
205     }
206
207     /// append - Add the specified values to this one.
208     void append(const RegsForValue &RHS) {
209       TLI = RHS.TLI;
210       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
211       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
212       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
213     }
214
215
216     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
217     /// this value and returns the result as a ValueVTs value.  This uses
218     /// Chain/Flag as the input and updates them for the output Chain/Flag.
219     /// If the Flag pointer is NULL, no flag is used.
220     SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
221                               SDValue &Chain, SDValue *Flag) const;
222
223     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
224     /// specified value into the registers specified by this object.  This uses
225     /// Chain/Flag as the input and updates them for the output Chain/Flag.
226     /// If the Flag pointer is NULL, no flag is used.
227     void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
228                        SDValue &Chain, SDValue *Flag) const;
229
230     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
231     /// operand list.  This adds the code marker and includes the number of
232     /// values added into it.
233     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
234                               std::vector<SDValue> &Ops) const;
235   };
236 }
237
238 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
239 /// PHI nodes or outside of the basic block that defines it, or used by a
240 /// switch or atomic instruction, which may expand to multiple basic blocks.
241 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
242   if (isa<PHINode>(I)) return true;
243   BasicBlock *BB = I->getParent();
244   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
245     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
246         // FIXME: Remove switchinst special case.
247         isa<SwitchInst>(*UI))
248       return true;
249   return false;
250 }
251
252 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
253 /// entry block, return true.  This includes arguments used by switches, since
254 /// the switch may expand into multiple basic blocks.
255 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
256   // With FastISel active, we may be splitting blocks, so force creation
257   // of virtual registers for all non-dead arguments.
258   // Don't force virtual registers for byval arguments though, because
259   // fast-isel can't handle those in all cases.
260   if (EnableFastISel && !A->hasByValAttr())
261     return A->use_empty();
262
263   BasicBlock *Entry = A->getParent()->begin();
264   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
265     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
266       return false;  // Use not in entry block.
267   return true;
268 }
269
270 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
271   : TLI(tli) {
272 }
273
274 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
275                                SelectionDAG &DAG,
276                                bool EnableFastISel) {
277   Fn = &fn;
278   MF = &mf;
279   RegInfo = &MF->getRegInfo();
280
281   // Create a vreg for each argument register that is not dead and is used
282   // outside of the entry block for the function.
283   for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
284        AI != E; ++AI)
285     if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
286       InitializeRegForValue(AI);
287
288   // Initialize the mapping of values to registers.  This is only set up for
289   // instruction values that are used outside of the block that defines
290   // them.
291   Function::iterator BB = Fn->begin(), EB = Fn->end();
292   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
293     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
294       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
295         const Type *Ty = AI->getAllocatedType();
296         uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
297         unsigned Align =
298           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
299                    AI->getAlignment());
300
301         TySize *= CUI->getZExtValue();   // Get total allocated size.
302         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
303         StaticAllocaMap[AI] =
304           MF->getFrameInfo()->CreateStackObject(TySize, Align);
305       }
306
307   for (; BB != EB; ++BB)
308     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
309       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
310         if (!isa<AllocaInst>(I) ||
311             !StaticAllocaMap.count(cast<AllocaInst>(I)))
312           InitializeRegForValue(I);
313
314   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
315   // also creates the initial PHI MachineInstrs, though none of the input
316   // operands are populated.
317   for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
318     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
319     MBBMap[BB] = MBB;
320     MF->push_back(MBB);
321
322     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
323     // appropriate.
324     PHINode *PN;
325     DebugLoc DL;
326     for (BasicBlock::iterator
327            I = BB->begin(), E = BB->end(); I != E; ++I) {
328       if (CallInst *CI = dyn_cast<CallInst>(I)) {
329         if (Function *F = CI->getCalledFunction()) {
330           switch (F->getIntrinsicID()) {
331           default: break;
332           case Intrinsic::dbg_stoppoint: {
333             DwarfWriter *DW = DAG.getDwarfWriter();
334             DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
335
336             if (DW && DW->ValidDebugInfo(SPI->getContext())) {
337               DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
338               std::string Dir, FN;
339               unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
340                                                          CU.getFilename(FN));
341               unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
342                                                        SPI->getLine(),
343                                                        SPI->getColumn());
344               DL = DebugLoc::get(idx);
345             }
346
347             break;
348           }
349           case Intrinsic::dbg_func_start: {
350             DwarfWriter *DW = DAG.getDwarfWriter();
351             if (DW) {
352               DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
353               Value *SP = FSI->getSubprogram();
354
355               if (DW->ValidDebugInfo(SP)) {
356                 DISubprogram Subprogram(cast<GlobalVariable>(SP));
357                 DICompileUnit CU(Subprogram.getCompileUnit());
358                 std::string Dir, FN;
359                 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
360                                                            CU.getFilename(FN));
361                 unsigned Line = Subprogram.getLineNumber();
362                 DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
363               }
364             }
365
366             break;
367           }
368           }
369         }
370       }
371
372       PN = dyn_cast<PHINode>(I);
373       if (!PN || PN->use_empty()) continue;
374
375       unsigned PHIReg = ValueMap[PN];
376       assert(PHIReg && "PHI node does not have an assigned virtual register!");
377
378       SmallVector<MVT, 4> ValueVTs;
379       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
380       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
381         MVT VT = ValueVTs[vti];
382         unsigned NumRegisters = TLI.getNumRegisters(VT);
383         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
384         for (unsigned i = 0; i != NumRegisters; ++i)
385           BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
386         PHIReg += NumRegisters;
387       }
388     }
389   }
390 }
391
392 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
393   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
394 }
395
396 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
397 /// the correctly promoted or expanded types.  Assign these registers
398 /// consecutive vreg numbers and return the first assigned number.
399 ///
400 /// In the case that the given value has struct or array type, this function
401 /// will assign registers for each member or element.
402 ///
403 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
404   SmallVector<MVT, 4> ValueVTs;
405   ComputeValueVTs(TLI, V->getType(), ValueVTs);
406
407   unsigned FirstReg = 0;
408   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
409     MVT ValueVT = ValueVTs[Value];
410     MVT RegisterVT = TLI.getRegisterType(ValueVT);
411
412     unsigned NumRegs = TLI.getNumRegisters(ValueVT);
413     for (unsigned i = 0; i != NumRegs; ++i) {
414       unsigned R = MakeReg(RegisterVT);
415       if (!FirstReg) FirstReg = R;
416     }
417   }
418   return FirstReg;
419 }
420
421 /// getCopyFromParts - Create a value that contains the specified legal parts
422 /// combined into the value they represent.  If the parts combine to a type
423 /// larger then ValueVT then AssertOp can be used to specify whether the extra
424 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
425 /// (ISD::AssertSext).
426 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
427                                 const SDValue *Parts,
428                                 unsigned NumParts, MVT PartVT, MVT ValueVT,
429                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
430   assert(NumParts > 0 && "No parts to assemble!");
431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
432   SDValue Val = Parts[0];
433
434   if (NumParts > 1) {
435     // Assemble the value from multiple parts.
436     if (!ValueVT.isVector()) {
437       unsigned PartBits = PartVT.getSizeInBits();
438       unsigned ValueBits = ValueVT.getSizeInBits();
439
440       // Assemble the power of 2 part.
441       unsigned RoundParts = NumParts & (NumParts - 1) ?
442         1 << Log2_32(NumParts) : NumParts;
443       unsigned RoundBits = PartBits * RoundParts;
444       MVT RoundVT = RoundBits == ValueBits ?
445         ValueVT : MVT::getIntegerVT(RoundBits);
446       SDValue Lo, Hi;
447
448       MVT HalfVT = ValueVT.isInteger() ?
449         MVT::getIntegerVT(RoundBits/2) :
450         MVT::getFloatingPointVT(RoundBits/2);
451
452       if (RoundParts > 2) {
453         Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
454         Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
455                               PartVT, HalfVT);
456       } else {
457         Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
458         Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
459       }
460       if (TLI.isBigEndian())
461         std::swap(Lo, Hi);
462       Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
463
464       if (RoundParts < NumParts) {
465         // Assemble the trailing non-power-of-2 part.
466         unsigned OddParts = NumParts - RoundParts;
467         MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
468         Hi = getCopyFromParts(DAG, dl,
469                               Parts+RoundParts, OddParts, PartVT, OddVT);
470
471         // Combine the round and odd parts.
472         Lo = Val;
473         if (TLI.isBigEndian())
474           std::swap(Lo, Hi);
475         MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
476         Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
477         Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
478                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
479                                          TLI.getPointerTy()));
480         Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
481         Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
482       }
483     } else {
484       // Handle a multi-element vector.
485       MVT IntermediateVT, RegisterVT;
486       unsigned NumIntermediates;
487       unsigned NumRegs =
488         TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
489                                    RegisterVT);
490       assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
491       NumParts = NumRegs; // Silence a compiler warning.
492       assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
493       assert(RegisterVT == Parts[0].getValueType() &&
494              "Part type doesn't match part!");
495
496       // Assemble the parts into intermediate operands.
497       SmallVector<SDValue, 8> Ops(NumIntermediates);
498       if (NumIntermediates == NumParts) {
499         // If the register was not expanded, truncate or copy the value,
500         // as appropriate.
501         for (unsigned i = 0; i != NumParts; ++i)
502           Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
503                                     PartVT, IntermediateVT);
504       } else if (NumParts > 0) {
505         // If the intermediate type was expanded, build the intermediate operands
506         // from the parts.
507         assert(NumParts % NumIntermediates == 0 &&
508                "Must expand into a divisible number of parts!");
509         unsigned Factor = NumParts / NumIntermediates;
510         for (unsigned i = 0; i != NumIntermediates; ++i)
511           Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
512                                     PartVT, IntermediateVT);
513       }
514
515       // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
516       // operands.
517       Val = DAG.getNode(IntermediateVT.isVector() ?
518                         ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
519                         ValueVT, &Ops[0], NumIntermediates);
520     }
521   }
522
523   // There is now one part, held in Val.  Correct it to match ValueVT.
524   PartVT = Val.getValueType();
525
526   if (PartVT == ValueVT)
527     return Val;
528
529   if (PartVT.isVector()) {
530     assert(ValueVT.isVector() && "Unknown vector conversion!");
531     return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
532   }
533
534   if (ValueVT.isVector()) {
535     assert(ValueVT.getVectorElementType() == PartVT &&
536            ValueVT.getVectorNumElements() == 1 &&
537            "Only trivial scalar-to-vector conversions should get here!");
538     return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
539   }
540
541   if (PartVT.isInteger() &&
542       ValueVT.isInteger()) {
543     if (ValueVT.bitsLT(PartVT)) {
544       // For a truncate, see if we have any information to
545       // indicate whether the truncated bits will always be
546       // zero or sign-extension.
547       if (AssertOp != ISD::DELETED_NODE)
548         Val = DAG.getNode(AssertOp, dl, PartVT, Val,
549                           DAG.getValueType(ValueVT));
550       return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
551     } else {
552       return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
553     }
554   }
555
556   if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
557     if (ValueVT.bitsLT(Val.getValueType()))
558       // FP_ROUND's are always exact here.
559       return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
560                          DAG.getIntPtrConstant(1));
561     return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
562   }
563
564   if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
565     return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
566
567   assert(0 && "Unknown mismatch!");
568   return SDValue();
569 }
570
571 /// getCopyToParts - Create a series of nodes that contain the specified value
572 /// split into legal parts.  If the parts contain more bits than Val, then, for
573 /// integers, ExtendKind can be used to specify how to generate the extra bits.
574 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
575                            SDValue *Parts, unsigned NumParts, MVT PartVT,
576                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
578   MVT PtrVT = TLI.getPointerTy();
579   MVT ValueVT = Val.getValueType();
580   unsigned PartBits = PartVT.getSizeInBits();
581   unsigned OrigNumParts = NumParts;
582   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
583
584   if (!NumParts)
585     return;
586
587   if (!ValueVT.isVector()) {
588     if (PartVT == ValueVT) {
589       assert(NumParts == 1 && "No-op copy with multiple parts!");
590       Parts[0] = Val;
591       return;
592     }
593
594     if (NumParts * PartBits > ValueVT.getSizeInBits()) {
595       // If the parts cover more bits than the value has, promote the value.
596       if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
597         assert(NumParts == 1 && "Do not know what to promote to!");
598         Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
599       } else if (PartVT.isInteger() && ValueVT.isInteger()) {
600         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
601         Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
602       } else {
603         assert(0 && "Unknown mismatch!");
604       }
605     } else if (PartBits == ValueVT.getSizeInBits()) {
606       // Different types of the same size.
607       assert(NumParts == 1 && PartVT != ValueVT);
608       Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
609     } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
610       // If the parts cover less bits than value has, truncate the value.
611       if (PartVT.isInteger() && ValueVT.isInteger()) {
612         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
613         Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
614       } else {
615         assert(0 && "Unknown mismatch!");
616       }
617     }
618
619     // The value may have changed - recompute ValueVT.
620     ValueVT = Val.getValueType();
621     assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
622            "Failed to tile the value with PartVT!");
623
624     if (NumParts == 1) {
625       assert(PartVT == ValueVT && "Type conversion failed!");
626       Parts[0] = Val;
627       return;
628     }
629
630     // Expand the value into multiple parts.
631     if (NumParts & (NumParts - 1)) {
632       // The number of parts is not a power of 2.  Split off and copy the tail.
633       assert(PartVT.isInteger() && ValueVT.isInteger() &&
634              "Do not know what to expand to!");
635       unsigned RoundParts = 1 << Log2_32(NumParts);
636       unsigned RoundBits = RoundParts * PartBits;
637       unsigned OddParts = NumParts - RoundParts;
638       SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
639                                    DAG.getConstant(RoundBits,
640                                                    TLI.getPointerTy()));
641       getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
642       if (TLI.isBigEndian())
643         // The odd parts were reversed by getCopyToParts - unreverse them.
644         std::reverse(Parts + RoundParts, Parts + NumParts);
645       NumParts = RoundParts;
646       ValueVT = MVT::getIntegerVT(NumParts * PartBits);
647       Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
648     }
649
650     // The number of parts is a power of 2.  Repeatedly bisect the value using
651     // EXTRACT_ELEMENT.
652     Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
653                            MVT::getIntegerVT(ValueVT.getSizeInBits()),
654                            Val);
655     for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
656       for (unsigned i = 0; i < NumParts; i += StepSize) {
657         unsigned ThisBits = StepSize * PartBits / 2;
658         MVT ThisVT = MVT::getIntegerVT (ThisBits);
659         SDValue &Part0 = Parts[i];
660         SDValue &Part1 = Parts[i+StepSize/2];
661
662         Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
663                             ThisVT, Part0,
664                             DAG.getConstant(1, PtrVT));
665         Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
666                             ThisVT, Part0,
667                             DAG.getConstant(0, PtrVT));
668
669         if (ThisBits == PartBits && ThisVT != PartVT) {
670           Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
671                                                 PartVT, Part0);
672           Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
673                                                 PartVT, Part1);
674         }
675       }
676     }
677
678     if (TLI.isBigEndian())
679       std::reverse(Parts, Parts + OrigNumParts);
680
681     return;
682   }
683
684   // Vector ValueVT.
685   if (NumParts == 1) {
686     if (PartVT != ValueVT) {
687       if (PartVT.isVector()) {
688         Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
689       } else {
690         assert(ValueVT.getVectorElementType() == PartVT &&
691                ValueVT.getVectorNumElements() == 1 &&
692                "Only trivial vector-to-scalar conversions should get here!");
693         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
694                           PartVT, Val,
695                           DAG.getConstant(0, PtrVT));
696       }
697     }
698
699     Parts[0] = Val;
700     return;
701   }
702
703   // Handle a multi-element vector.
704   MVT IntermediateVT, RegisterVT;
705   unsigned NumIntermediates;
706   unsigned NumRegs = TLI
707       .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
708                               RegisterVT);
709   unsigned NumElements = ValueVT.getVectorNumElements();
710
711   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
712   NumParts = NumRegs; // Silence a compiler warning.
713   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
714
715   // Split the vector into intermediate operands.
716   SmallVector<SDValue, 8> Ops(NumIntermediates);
717   for (unsigned i = 0; i != NumIntermediates; ++i)
718     if (IntermediateVT.isVector())
719       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
720                            IntermediateVT, Val,
721                            DAG.getConstant(i * (NumElements / NumIntermediates),
722                                            PtrVT));
723     else
724       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
725                            IntermediateVT, Val,
726                            DAG.getConstant(i, PtrVT));
727
728   // Split the intermediate operands into legal parts.
729   if (NumParts == NumIntermediates) {
730     // If the register was not expanded, promote or copy the value,
731     // as appropriate.
732     for (unsigned i = 0; i != NumParts; ++i)
733       getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
734   } else if (NumParts > 0) {
735     // If the intermediate type was expanded, split each the value into
736     // legal parts.
737     assert(NumParts % NumIntermediates == 0 &&
738            "Must expand into a divisible number of parts!");
739     unsigned Factor = NumParts / NumIntermediates;
740     for (unsigned i = 0; i != NumIntermediates; ++i)
741       getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
742   }
743 }
744
745
746 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
747   AA = &aa;
748   GFI = gfi;
749   TD = DAG.getTarget().getTargetData();
750 }
751
752 /// clear - Clear out the curret SelectionDAG and the associated
753 /// state and prepare this SelectionDAGLowering object to be used
754 /// for a new block. This doesn't clear out information about
755 /// additional blocks that are needed to complete switch lowering
756 /// or PHI node updating; that information is cleared out as it is
757 /// consumed.
758 void SelectionDAGLowering::clear() {
759   NodeMap.clear();
760   PendingLoads.clear();
761   PendingExports.clear();
762   DAG.clear();
763   CurDebugLoc = DebugLoc::getUnknownLoc();
764 }
765
766 /// getRoot - Return the current virtual root of the Selection DAG,
767 /// flushing any PendingLoad items. This must be done before emitting
768 /// a store or any other node that may need to be ordered after any
769 /// prior load instructions.
770 ///
771 SDValue SelectionDAGLowering::getRoot() {
772   if (PendingLoads.empty())
773     return DAG.getRoot();
774
775   if (PendingLoads.size() == 1) {
776     SDValue Root = PendingLoads[0];
777     DAG.setRoot(Root);
778     PendingLoads.clear();
779     return Root;
780   }
781
782   // Otherwise, we have to make a token factor node.
783   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
784                                &PendingLoads[0], PendingLoads.size());
785   PendingLoads.clear();
786   DAG.setRoot(Root);
787   return Root;
788 }
789
790 /// getControlRoot - Similar to getRoot, but instead of flushing all the
791 /// PendingLoad items, flush all the PendingExports items. It is necessary
792 /// to do this before emitting a terminator instruction.
793 ///
794 SDValue SelectionDAGLowering::getControlRoot() {
795   SDValue Root = DAG.getRoot();
796
797   if (PendingExports.empty())
798     return Root;
799
800   // Turn all of the CopyToReg chains into one factored node.
801   if (Root.getOpcode() != ISD::EntryToken) {
802     unsigned i = 0, e = PendingExports.size();
803     for (; i != e; ++i) {
804       assert(PendingExports[i].getNode()->getNumOperands() > 1);
805       if (PendingExports[i].getNode()->getOperand(0) == Root)
806         break;  // Don't add the root if we already indirectly depend on it.
807     }
808
809     if (i == e)
810       PendingExports.push_back(Root);
811   }
812
813   Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
814                      &PendingExports[0],
815                      PendingExports.size());
816   PendingExports.clear();
817   DAG.setRoot(Root);
818   return Root;
819 }
820
821 void SelectionDAGLowering::visit(Instruction &I) {
822   visit(I.getOpcode(), I);
823 }
824
825 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
826   // Note: this doesn't use InstVisitor, because it has to work with
827   // ConstantExpr's in addition to instructions.
828   switch (Opcode) {
829   default: assert(0 && "Unknown instruction type encountered!");
830            abort();
831     // Build the switch statement using the Instruction.def file.
832 #define HANDLE_INST(NUM, OPCODE, CLASS) \
833   case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
834 #include "llvm/Instruction.def"
835   }
836 }
837
838 void SelectionDAGLowering::visitAdd(User &I) {
839   if (I.getType()->isFPOrFPVector())
840     visitBinary(I, ISD::FADD);
841   else
842     visitBinary(I, ISD::ADD);
843 }
844
845 void SelectionDAGLowering::visitMul(User &I) {
846   if (I.getType()->isFPOrFPVector())
847     visitBinary(I, ISD::FMUL);
848   else
849     visitBinary(I, ISD::MUL);
850 }
851
852 SDValue SelectionDAGLowering::getValue(const Value *V) {
853   SDValue &N = NodeMap[V];
854   if (N.getNode()) return N;
855
856   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
857     MVT VT = TLI.getValueType(V->getType(), true);
858
859     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
860       return N = DAG.getConstant(*CI, VT);
861
862     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
863       return N = DAG.getGlobalAddress(GV, VT);
864
865     if (isa<ConstantPointerNull>(C))
866       return N = DAG.getConstant(0, TLI.getPointerTy());
867
868     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
869       return N = DAG.getConstantFP(*CFP, VT);
870
871     if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
872         !V->getType()->isAggregateType())
873       return N = DAG.getUNDEF(VT);
874
875     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
876       visit(CE->getOpcode(), *CE);
877       SDValue N1 = NodeMap[V];
878       assert(N1.getNode() && "visit didn't populate the ValueMap!");
879       return N1;
880     }
881
882     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
883       SmallVector<SDValue, 4> Constants;
884       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
885            OI != OE; ++OI) {
886         SDNode *Val = getValue(*OI).getNode();
887         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
888           Constants.push_back(SDValue(Val, i));
889       }
890       return DAG.getMergeValues(&Constants[0], Constants.size(),
891                                 getCurDebugLoc());
892     }
893
894     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
895       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
896              "Unknown struct or array constant!");
897
898       SmallVector<MVT, 4> ValueVTs;
899       ComputeValueVTs(TLI, C->getType(), ValueVTs);
900       unsigned NumElts = ValueVTs.size();
901       if (NumElts == 0)
902         return SDValue(); // empty struct
903       SmallVector<SDValue, 4> Constants(NumElts);
904       for (unsigned i = 0; i != NumElts; ++i) {
905         MVT EltVT = ValueVTs[i];
906         if (isa<UndefValue>(C))
907           Constants[i] = DAG.getUNDEF(EltVT);
908         else if (EltVT.isFloatingPoint())
909           Constants[i] = DAG.getConstantFP(0, EltVT);
910         else
911           Constants[i] = DAG.getConstant(0, EltVT);
912       }
913       return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
914     }
915
916     const VectorType *VecTy = cast<VectorType>(V->getType());
917     unsigned NumElements = VecTy->getNumElements();
918
919     // Now that we know the number and type of the elements, get that number of
920     // elements into the Ops array based on what kind of constant it is.
921     SmallVector<SDValue, 16> Ops;
922     if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
923       for (unsigned i = 0; i != NumElements; ++i)
924         Ops.push_back(getValue(CP->getOperand(i)));
925     } else {
926       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
927              "Unknown vector constant!");
928       MVT EltVT = TLI.getValueType(VecTy->getElementType());
929
930       SDValue Op;
931       if (isa<UndefValue>(C))
932         Op = DAG.getUNDEF(EltVT);
933       else if (EltVT.isFloatingPoint())
934         Op = DAG.getConstantFP(0, EltVT);
935       else
936         Op = DAG.getConstant(0, EltVT);
937       Ops.assign(NumElements, Op);
938     }
939
940     // Create a BUILD_VECTOR node.
941     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
942                                     VT, &Ops[0], Ops.size());
943   }
944
945   // If this is a static alloca, generate it as the frameindex instead of
946   // computation.
947   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
948     DenseMap<const AllocaInst*, int>::iterator SI =
949       FuncInfo.StaticAllocaMap.find(AI);
950     if (SI != FuncInfo.StaticAllocaMap.end())
951       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
952   }
953
954   unsigned InReg = FuncInfo.ValueMap[V];
955   assert(InReg && "Value not in map!");
956
957   RegsForValue RFV(TLI, InReg, V->getType());
958   SDValue Chain = DAG.getEntryNode();
959   return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
960 }
961
962
963 void SelectionDAGLowering::visitRet(ReturnInst &I) {
964   if (I.getNumOperands() == 0) {
965     DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
966                             MVT::Other, getControlRoot()));
967     return;
968   }
969
970   SmallVector<SDValue, 8> NewValues;
971   NewValues.push_back(getControlRoot());
972   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
973     SmallVector<MVT, 4> ValueVTs;
974     ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
975     unsigned NumValues = ValueVTs.size();
976     if (NumValues == 0) continue;
977
978     SDValue RetOp = getValue(I.getOperand(i));
979     for (unsigned j = 0, f = NumValues; j != f; ++j) {
980       MVT VT = ValueVTs[j];
981
982       // FIXME: C calling convention requires the return type to be promoted to
983       // at least 32-bit. But this is not necessary for non-C calling
984       // conventions.
985       if (VT.isInteger()) {
986         MVT MinVT = TLI.getRegisterType(MVT::i32);
987         if (VT.bitsLT(MinVT))
988           VT = MinVT;
989       }
990
991       unsigned NumParts = TLI.getNumRegisters(VT);
992       MVT PartVT = TLI.getRegisterType(VT);
993       SmallVector<SDValue, 4> Parts(NumParts);
994       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
995
996       const Function *F = I.getParent()->getParent();
997       if (F->paramHasAttr(0, Attribute::SExt))
998         ExtendKind = ISD::SIGN_EXTEND;
999       else if (F->paramHasAttr(0, Attribute::ZExt))
1000         ExtendKind = ISD::ZERO_EXTEND;
1001
1002       getCopyToParts(DAG, getCurDebugLoc(),
1003                      SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1004                      &Parts[0], NumParts, PartVT, ExtendKind);
1005
1006       // 'inreg' on function refers to return value
1007       ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1008       if (F->paramHasAttr(0, Attribute::InReg))
1009         Flags.setInReg();
1010       for (unsigned i = 0; i < NumParts; ++i) {
1011         NewValues.push_back(Parts[i]);
1012         NewValues.push_back(DAG.getArgFlags(Flags));
1013       }
1014     }
1015   }
1016   DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
1017                           &NewValues[0], NewValues.size()));
1018 }
1019
1020 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1021 /// the current basic block, add it to ValueMap now so that we'll get a
1022 /// CopyTo/FromReg.
1023 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1024   // No need to export constants.
1025   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1026
1027   // Already exported?
1028   if (FuncInfo.isExportedInst(V)) return;
1029
1030   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1031   CopyValueToVirtualRegister(V, Reg);
1032 }
1033
1034 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1035                                                     const BasicBlock *FromBB) {
1036   // The operands of the setcc have to be in this block.  We don't know
1037   // how to export them from some other block.
1038   if (Instruction *VI = dyn_cast<Instruction>(V)) {
1039     // Can export from current BB.
1040     if (VI->getParent() == FromBB)
1041       return true;
1042
1043     // Is already exported, noop.
1044     return FuncInfo.isExportedInst(V);
1045   }
1046
1047   // If this is an argument, we can export it if the BB is the entry block or
1048   // if it is already exported.
1049   if (isa<Argument>(V)) {
1050     if (FromBB == &FromBB->getParent()->getEntryBlock())
1051       return true;
1052
1053     // Otherwise, can only export this if it is already exported.
1054     return FuncInfo.isExportedInst(V);
1055   }
1056
1057   // Otherwise, constants can always be exported.
1058   return true;
1059 }
1060
1061 static bool InBlock(const Value *V, const BasicBlock *BB) {
1062   if (const Instruction *I = dyn_cast<Instruction>(V))
1063     return I->getParent() == BB;
1064   return true;
1065 }
1066
1067 /// getFCmpCondCode - Return the ISD condition code corresponding to
1068 /// the given LLVM IR floating-point condition code.  This includes
1069 /// consideration of global floating-point math flags.
1070 ///
1071 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1072   ISD::CondCode FPC, FOC;
1073   switch (Pred) {
1074   case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1075   case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1076   case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1077   case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1078   case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1079   case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1080   case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1081   case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1082   case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1083   case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1084   case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1085   case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1086   case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1087   case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1088   case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1089   case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1090   default:
1091     assert(0 && "Invalid FCmp predicate opcode!");
1092     FOC = FPC = ISD::SETFALSE;
1093     break;
1094   }
1095   if (FiniteOnlyFPMath())
1096     return FOC;
1097   else
1098     return FPC;
1099 }
1100
1101 /// getICmpCondCode - Return the ISD condition code corresponding to
1102 /// the given LLVM IR integer condition code.
1103 ///
1104 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1105   switch (Pred) {
1106   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
1107   case ICmpInst::ICMP_NE:  return ISD::SETNE;
1108   case ICmpInst::ICMP_SLE: return ISD::SETLE;
1109   case ICmpInst::ICMP_ULE: return ISD::SETULE;
1110   case ICmpInst::ICMP_SGE: return ISD::SETGE;
1111   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1112   case ICmpInst::ICMP_SLT: return ISD::SETLT;
1113   case ICmpInst::ICMP_ULT: return ISD::SETULT;
1114   case ICmpInst::ICMP_SGT: return ISD::SETGT;
1115   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1116   default:
1117     assert(0 && "Invalid ICmp predicate opcode!");
1118     return ISD::SETNE;
1119   }
1120 }
1121
1122 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1123 /// This function emits a branch and is used at the leaves of an OR or an
1124 /// AND operator tree.
1125 ///
1126 void
1127 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1128                                                    MachineBasicBlock *TBB,
1129                                                    MachineBasicBlock *FBB,
1130                                                    MachineBasicBlock *CurBB) {
1131   const BasicBlock *BB = CurBB->getBasicBlock();
1132
1133   // If the leaf of the tree is a comparison, merge the condition into
1134   // the caseblock.
1135   if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1136     // The operands of the cmp have to be in this block.  We don't know
1137     // how to export them from some other block.  If this is the first block
1138     // of the sequence, no exporting is needed.
1139     if (CurBB == CurMBB ||
1140         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1141          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1142       ISD::CondCode Condition;
1143       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1144         Condition = getICmpCondCode(IC->getPredicate());
1145       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1146         Condition = getFCmpCondCode(FC->getPredicate());
1147       } else {
1148         Condition = ISD::SETEQ; // silence warning.
1149         assert(0 && "Unknown compare instruction");
1150       }
1151
1152       CaseBlock CB(Condition, BOp->getOperand(0),
1153                    BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1154       SwitchCases.push_back(CB);
1155       return;
1156     }
1157   }
1158
1159   // Create a CaseBlock record representing this branch.
1160   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1161                NULL, TBB, FBB, CurBB);
1162   SwitchCases.push_back(CB);
1163 }
1164
1165 /// FindMergedConditions - If Cond is an expression like
1166 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1167                                                 MachineBasicBlock *TBB,
1168                                                 MachineBasicBlock *FBB,
1169                                                 MachineBasicBlock *CurBB,
1170                                                 unsigned Opc) {
1171   // If this node is not part of the or/and tree, emit it as a branch.
1172   Instruction *BOp = dyn_cast<Instruction>(Cond);
1173   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1174       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1175       BOp->getParent() != CurBB->getBasicBlock() ||
1176       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1177       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1178     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1179     return;
1180   }
1181
1182   //  Create TmpBB after CurBB.
1183   MachineFunction::iterator BBI = CurBB;
1184   MachineFunction &MF = DAG.getMachineFunction();
1185   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1186   CurBB->getParent()->insert(++BBI, TmpBB);
1187
1188   if (Opc == Instruction::Or) {
1189     // Codegen X | Y as:
1190     //   jmp_if_X TBB
1191     //   jmp TmpBB
1192     // TmpBB:
1193     //   jmp_if_Y TBB
1194     //   jmp FBB
1195     //
1196
1197     // Emit the LHS condition.
1198     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1199
1200     // Emit the RHS condition into TmpBB.
1201     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1202   } else {
1203     assert(Opc == Instruction::And && "Unknown merge op!");
1204     // Codegen X & Y as:
1205     //   jmp_if_X TmpBB
1206     //   jmp FBB
1207     // TmpBB:
1208     //   jmp_if_Y TBB
1209     //   jmp FBB
1210     //
1211     //  This requires creation of TmpBB after CurBB.
1212
1213     // Emit the LHS condition.
1214     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1215
1216     // Emit the RHS condition into TmpBB.
1217     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1218   }
1219 }
1220
1221 /// If the set of cases should be emitted as a series of branches, return true.
1222 /// If we should emit this as a bunch of and/or'd together conditions, return
1223 /// false.
1224 bool
1225 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1226   if (Cases.size() != 2) return true;
1227
1228   // If this is two comparisons of the same values or'd or and'd together, they
1229   // will get folded into a single comparison, so don't emit two blocks.
1230   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1231        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1232       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1233        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1234     return false;
1235   }
1236
1237   return true;
1238 }
1239
1240 void SelectionDAGLowering::visitBr(BranchInst &I) {
1241   // Update machine-CFG edges.
1242   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1243
1244   // Figure out which block is immediately after the current one.
1245   MachineBasicBlock *NextBlock = 0;
1246   MachineFunction::iterator BBI = CurMBB;
1247   if (++BBI != CurMBB->getParent()->end())
1248     NextBlock = BBI;
1249
1250   if (I.isUnconditional()) {
1251     // Update machine-CFG edges.
1252     CurMBB->addSuccessor(Succ0MBB);
1253
1254     // If this is not a fall-through branch, emit the branch.
1255     if (Succ0MBB != NextBlock)
1256       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1257                               MVT::Other, getControlRoot(),
1258                               DAG.getBasicBlock(Succ0MBB)));
1259     return;
1260   }
1261
1262   // If this condition is one of the special cases we handle, do special stuff
1263   // now.
1264   Value *CondVal = I.getCondition();
1265   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1266
1267   // If this is a series of conditions that are or'd or and'd together, emit
1268   // this as a sequence of branches instead of setcc's with and/or operations.
1269   // For example, instead of something like:
1270   //     cmp A, B
1271   //     C = seteq
1272   //     cmp D, E
1273   //     F = setle
1274   //     or C, F
1275   //     jnz foo
1276   // Emit:
1277   //     cmp A, B
1278   //     je foo
1279   //     cmp D, E
1280   //     jle foo
1281   //
1282   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1283     if (BOp->hasOneUse() &&
1284         (BOp->getOpcode() == Instruction::And ||
1285          BOp->getOpcode() == Instruction::Or)) {
1286       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1287       // If the compares in later blocks need to use values not currently
1288       // exported from this block, export them now.  This block should always
1289       // be the first entry.
1290       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1291
1292       // Allow some cases to be rejected.
1293       if (ShouldEmitAsBranches(SwitchCases)) {
1294         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1295           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1296           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1297         }
1298
1299         // Emit the branch for this block.
1300         visitSwitchCase(SwitchCases[0]);
1301         SwitchCases.erase(SwitchCases.begin());
1302         return;
1303       }
1304
1305       // Okay, we decided not to do this, remove any inserted MBB's and clear
1306       // SwitchCases.
1307       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1308         CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1309
1310       SwitchCases.clear();
1311     }
1312   }
1313
1314   // Create a CaseBlock record representing this branch.
1315   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1316                NULL, Succ0MBB, Succ1MBB, CurMBB);
1317   // Use visitSwitchCase to actually insert the fast branch sequence for this
1318   // cond branch.
1319   visitSwitchCase(CB);
1320 }
1321
1322 /// visitSwitchCase - Emits the necessary code to represent a single node in
1323 /// the binary search tree resulting from lowering a switch instruction.
1324 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1325   SDValue Cond;
1326   SDValue CondLHS = getValue(CB.CmpLHS);
1327   DebugLoc dl = getCurDebugLoc();
1328
1329   // Build the setcc now.
1330   if (CB.CmpMHS == NULL) {
1331     // Fold "(X == true)" to X and "(X == false)" to !X to
1332     // handle common cases produced by branch lowering.
1333     if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1334       Cond = CondLHS;
1335     else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1336       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1337       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1338     } else
1339       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1340   } else {
1341     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1342
1343     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1344     const APInt& High  = cast<ConstantInt>(CB.CmpRHS)->getValue();
1345
1346     SDValue CmpOp = getValue(CB.CmpMHS);
1347     MVT VT = CmpOp.getValueType();
1348
1349     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1350       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1351                           ISD::SETLE);
1352     } else {
1353       SDValue SUB = DAG.getNode(ISD::SUB, dl,
1354                                 VT, CmpOp, DAG.getConstant(Low, VT));
1355       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1356                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1357     }
1358   }
1359
1360   // Update successor info
1361   CurMBB->addSuccessor(CB.TrueBB);
1362   CurMBB->addSuccessor(CB.FalseBB);
1363
1364   // Set NextBlock to be the MBB immediately after the current one, if any.
1365   // This is used to avoid emitting unnecessary branches to the next block.
1366   MachineBasicBlock *NextBlock = 0;
1367   MachineFunction::iterator BBI = CurMBB;
1368   if (++BBI != CurMBB->getParent()->end())
1369     NextBlock = BBI;
1370
1371   // If the lhs block is the next block, invert the condition so that we can
1372   // fall through to the lhs instead of the rhs block.
1373   if (CB.TrueBB == NextBlock) {
1374     std::swap(CB.TrueBB, CB.FalseBB);
1375     SDValue True = DAG.getConstant(1, Cond.getValueType());
1376     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1377   }
1378   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1379                                MVT::Other, getControlRoot(), Cond,
1380                                DAG.getBasicBlock(CB.TrueBB));
1381
1382   // If the branch was constant folded, fix up the CFG.
1383   if (BrCond.getOpcode() == ISD::BR) {
1384     CurMBB->removeSuccessor(CB.FalseBB);
1385     DAG.setRoot(BrCond);
1386   } else {
1387     // Otherwise, go ahead and insert the false branch.
1388     if (BrCond == getControlRoot())
1389       CurMBB->removeSuccessor(CB.TrueBB);
1390
1391     if (CB.FalseBB == NextBlock)
1392       DAG.setRoot(BrCond);
1393     else
1394       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1395                               DAG.getBasicBlock(CB.FalseBB)));
1396   }
1397 }
1398
1399 /// visitJumpTable - Emit JumpTable node in the current MBB
1400 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1401   // Emit the code for the jump table
1402   assert(JT.Reg != -1U && "Should lower JT Header first!");
1403   MVT PTy = TLI.getPointerTy();
1404   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1405                                      JT.Reg, PTy);
1406   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1407   DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1408                           MVT::Other, Index.getValue(1),
1409                           Table, Index));
1410 }
1411
1412 /// visitJumpTableHeader - This function emits necessary code to produce index
1413 /// in the JumpTable from switch case.
1414 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1415                                                 JumpTableHeader &JTH) {
1416   // Subtract the lowest switch case value from the value being switched on and
1417   // conditional branch to default mbb if the result is greater than the
1418   // difference between smallest and largest cases.
1419   SDValue SwitchOp = getValue(JTH.SValue);
1420   MVT VT = SwitchOp.getValueType();
1421   SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1422                             DAG.getConstant(JTH.First, VT));
1423
1424   // The SDNode we just created, which holds the value being switched on minus
1425   // the the smallest case value, needs to be copied to a virtual register so it
1426   // can be used as an index into the jump table in a subsequent basic block.
1427   // This value may be smaller or larger than the target's pointer type, and
1428   // therefore require extension or truncating.
1429   if (VT.bitsGT(TLI.getPointerTy()))
1430     SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
1431                            TLI.getPointerTy(), SUB);
1432   else
1433     SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
1434                            TLI.getPointerTy(), SUB);
1435
1436   unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1437   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1438                                     JumpTableReg, SwitchOp);
1439   JT.Reg = JumpTableReg;
1440
1441   // Emit the range check for the jump table, and branch to the default block
1442   // for the switch statement if the value being switched on exceeds the largest
1443   // case in the switch.
1444   SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1445                              TLI.getSetCCResultType(SUB.getValueType()), SUB,
1446                              DAG.getConstant(JTH.Last-JTH.First,VT),
1447                              ISD::SETUGT);
1448
1449   // Set NextBlock to be the MBB immediately after the current one, if any.
1450   // This is used to avoid emitting unnecessary branches to the next block.
1451   MachineBasicBlock *NextBlock = 0;
1452   MachineFunction::iterator BBI = CurMBB;
1453   if (++BBI != CurMBB->getParent()->end())
1454     NextBlock = BBI;
1455
1456   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1457                                MVT::Other, CopyTo, CMP,
1458                                DAG.getBasicBlock(JT.Default));
1459
1460   if (JT.MBB == NextBlock)
1461     DAG.setRoot(BrCond);
1462   else
1463     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1464                             DAG.getBasicBlock(JT.MBB)));
1465 }
1466
1467 /// visitBitTestHeader - This function emits necessary code to produce value
1468 /// suitable for "bit tests"
1469 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1470   // Subtract the minimum value
1471   SDValue SwitchOp = getValue(B.SValue);
1472   MVT VT = SwitchOp.getValueType();
1473   SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1474                             DAG.getConstant(B.First, VT));
1475
1476   // Check range
1477   SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1478                                   TLI.getSetCCResultType(SUB.getValueType()),
1479                                   SUB, DAG.getConstant(B.Range, VT),
1480                                   ISD::SETUGT);
1481
1482   SDValue ShiftOp;
1483   if (VT.bitsGT(TLI.getPointerTy()))
1484     ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
1485                           TLI.getPointerTy(), SUB);
1486   else
1487     ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
1488                           TLI.getPointerTy(), SUB);
1489
1490   B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1491   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1492                                     B.Reg, ShiftOp);
1493
1494   // Set NextBlock to be the MBB immediately after the current one, if any.
1495   // This is used to avoid emitting unnecessary branches to the next block.
1496   MachineBasicBlock *NextBlock = 0;
1497   MachineFunction::iterator BBI = CurMBB;
1498   if (++BBI != CurMBB->getParent()->end())
1499     NextBlock = BBI;
1500
1501   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1502
1503   CurMBB->addSuccessor(B.Default);
1504   CurMBB->addSuccessor(MBB);
1505
1506   SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1507                                 MVT::Other, CopyTo, RangeCmp,
1508                                 DAG.getBasicBlock(B.Default));
1509
1510   if (MBB == NextBlock)
1511     DAG.setRoot(BrRange);
1512   else
1513     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1514                             DAG.getBasicBlock(MBB)));
1515 }
1516
1517 /// visitBitTestCase - this function produces one "bit test"
1518 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1519                                             unsigned Reg,
1520                                             BitTestCase &B) {
1521   // Make desired shift
1522   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1523                                        TLI.getPointerTy());
1524   SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1525                                   TLI.getPointerTy(),
1526                                   DAG.getConstant(1, TLI.getPointerTy()),
1527                                   ShiftOp);
1528
1529   // Emit bit tests and jumps
1530   SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1531                               TLI.getPointerTy(), SwitchVal,
1532                               DAG.getConstant(B.Mask, TLI.getPointerTy()));
1533   SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1534                                 TLI.getSetCCResultType(AndOp.getValueType()),
1535                                 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1536                                 ISD::SETNE);
1537
1538   CurMBB->addSuccessor(B.TargetBB);
1539   CurMBB->addSuccessor(NextMBB);
1540
1541   SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1542                               MVT::Other, getControlRoot(),
1543                               AndCmp, DAG.getBasicBlock(B.TargetBB));
1544
1545   // Set NextBlock to be the MBB immediately after the current one, if any.
1546   // This is used to avoid emitting unnecessary branches to the next block.
1547   MachineBasicBlock *NextBlock = 0;
1548   MachineFunction::iterator BBI = CurMBB;
1549   if (++BBI != CurMBB->getParent()->end())
1550     NextBlock = BBI;
1551
1552   if (NextMBB == NextBlock)
1553     DAG.setRoot(BrAnd);
1554   else
1555     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1556                             DAG.getBasicBlock(NextMBB)));
1557 }
1558
1559 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1560   // Retrieve successors.
1561   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1562   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1563
1564   const Value *Callee(I.getCalledValue());
1565   if (isa<InlineAsm>(Callee))
1566     visitInlineAsm(&I);
1567   else
1568     LowerCallTo(&I, getValue(Callee), false, LandingPad);
1569
1570   // If the value of the invoke is used outside of its defining block, make it
1571   // available as a virtual register.
1572   if (!I.use_empty()) {
1573     DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1574     if (VMI != FuncInfo.ValueMap.end())
1575       CopyValueToVirtualRegister(&I, VMI->second);
1576   }
1577
1578   // Update successor info
1579   CurMBB->addSuccessor(Return);
1580   CurMBB->addSuccessor(LandingPad);
1581
1582   // Drop into normal successor.
1583   DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1584                           MVT::Other, getControlRoot(),
1585                           DAG.getBasicBlock(Return)));
1586 }
1587
1588 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1589 }
1590
1591 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1592 /// small case ranges).
1593 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1594                                                   CaseRecVector& WorkList,
1595                                                   Value* SV,
1596                                                   MachineBasicBlock* Default) {
1597   Case& BackCase  = *(CR.Range.second-1);
1598
1599   // Size is the number of Cases represented by this range.
1600   size_t Size = CR.Range.second - CR.Range.first;
1601   if (Size > 3)
1602     return false;
1603
1604   // Get the MachineFunction which holds the current MBB.  This is used when
1605   // inserting any additional MBBs necessary to represent the switch.
1606   MachineFunction *CurMF = CurMBB->getParent();
1607
1608   // Figure out which block is immediately after the current one.
1609   MachineBasicBlock *NextBlock = 0;
1610   MachineFunction::iterator BBI = CR.CaseBB;
1611
1612   if (++BBI != CurMBB->getParent()->end())
1613     NextBlock = BBI;
1614
1615   // TODO: If any two of the cases has the same destination, and if one value
1616   // is the same as the other, but has one bit unset that the other has set,
1617   // use bit manipulation to do two compares at once.  For example:
1618   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1619
1620   // Rearrange the case blocks so that the last one falls through if possible.
1621   if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1622     // The last case block won't fall through into 'NextBlock' if we emit the
1623     // branches in this order.  See if rearranging a case value would help.
1624     for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1625       if (I->BB == NextBlock) {
1626         std::swap(*I, BackCase);
1627         break;
1628       }
1629     }
1630   }
1631
1632   // Create a CaseBlock record representing a conditional branch to
1633   // the Case's target mbb if the value being switched on SV is equal
1634   // to C.
1635   MachineBasicBlock *CurBlock = CR.CaseBB;
1636   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1637     MachineBasicBlock *FallThrough;
1638     if (I != E-1) {
1639       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1640       CurMF->insert(BBI, FallThrough);
1641     } else {
1642       // If the last case doesn't match, go to the default block.
1643       FallThrough = Default;
1644     }
1645
1646     Value *RHS, *LHS, *MHS;
1647     ISD::CondCode CC;
1648     if (I->High == I->Low) {
1649       // This is just small small case range :) containing exactly 1 case
1650       CC = ISD::SETEQ;
1651       LHS = SV; RHS = I->High; MHS = NULL;
1652     } else {
1653       CC = ISD::SETLE;
1654       LHS = I->Low; MHS = SV; RHS = I->High;
1655     }
1656     CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1657
1658     // If emitting the first comparison, just call visitSwitchCase to emit the
1659     // code into the current block.  Otherwise, push the CaseBlock onto the
1660     // vector to be later processed by SDISel, and insert the node's MBB
1661     // before the next MBB.
1662     if (CurBlock == CurMBB)
1663       visitSwitchCase(CB);
1664     else
1665       SwitchCases.push_back(CB);
1666
1667     CurBlock = FallThrough;
1668   }
1669
1670   return true;
1671 }
1672
1673 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1674   return !DisableJumpTables &&
1675           (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1676            TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1677 }
1678
1679 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1680   APInt LastExt(Last), FirstExt(First);
1681   uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1682   LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1683   return (LastExt - FirstExt + 1ULL);
1684 }
1685
1686 /// handleJTSwitchCase - Emit jumptable for current switch case range
1687 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1688                                               CaseRecVector& WorkList,
1689                                               Value* SV,
1690                                               MachineBasicBlock* Default) {
1691   Case& FrontCase = *CR.Range.first;
1692   Case& BackCase  = *(CR.Range.second-1);
1693
1694   const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1695   const APInt& Last  = cast<ConstantInt>(BackCase.High)->getValue();
1696
1697   size_t TSize = 0;
1698   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1699        I!=E; ++I)
1700     TSize += I->size();
1701
1702   if (!areJTsAllowed(TLI) || TSize <= 3)
1703     return false;
1704
1705   APInt Range = ComputeRange(First, Last);
1706   double Density = (double)TSize / Range.roundToDouble();
1707   if (Density < 0.4)
1708     return false;
1709
1710   DEBUG(errs() << "Lowering jump table\n"
1711                << "First entry: " << First << ". Last entry: " << Last << '\n'
1712                << "Range: " << Range
1713                << "Size: " << TSize << ". Density: " << Density << "\n\n");
1714
1715   // Get the MachineFunction which holds the current MBB.  This is used when
1716   // inserting any additional MBBs necessary to represent the switch.
1717   MachineFunction *CurMF = CurMBB->getParent();
1718
1719   // Figure out which block is immediately after the current one.
1720   MachineBasicBlock *NextBlock = 0;
1721   MachineFunction::iterator BBI = CR.CaseBB;
1722
1723   if (++BBI != CurMBB->getParent()->end())
1724     NextBlock = BBI;
1725
1726   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1727
1728   // Create a new basic block to hold the code for loading the address
1729   // of the jump table, and jumping to it.  Update successor information;
1730   // we will either branch to the default case for the switch, or the jump
1731   // table.
1732   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1733   CurMF->insert(BBI, JumpTableBB);
1734   CR.CaseBB->addSuccessor(Default);
1735   CR.CaseBB->addSuccessor(JumpTableBB);
1736
1737   // Build a vector of destination BBs, corresponding to each target
1738   // of the jump table. If the value of the jump table slot corresponds to
1739   // a case statement, push the case's BB onto the vector, otherwise, push
1740   // the default BB.
1741   std::vector<MachineBasicBlock*> DestBBs;
1742   APInt TEI = First;
1743   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1744     const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1745     const APInt& High = cast<ConstantInt>(I->High)->getValue();
1746
1747     if (Low.sle(TEI) && TEI.sle(High)) {
1748       DestBBs.push_back(I->BB);
1749       if (TEI==High)
1750         ++I;
1751     } else {
1752       DestBBs.push_back(Default);
1753     }
1754   }
1755
1756   // Update successor info. Add one edge to each unique successor.
1757   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1758   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1759          E = DestBBs.end(); I != E; ++I) {
1760     if (!SuccsHandled[(*I)->getNumber()]) {
1761       SuccsHandled[(*I)->getNumber()] = true;
1762       JumpTableBB->addSuccessor(*I);
1763     }
1764   }
1765
1766   // Create a jump table index for this jump table, or return an existing
1767   // one.
1768   unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1769
1770   // Set the jump table information so that we can codegen it as a second
1771   // MachineBasicBlock
1772   JumpTable JT(-1U, JTI, JumpTableBB, Default);
1773   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1774   if (CR.CaseBB == CurMBB)
1775     visitJumpTableHeader(JT, JTH);
1776
1777   JTCases.push_back(JumpTableBlock(JTH, JT));
1778
1779   return true;
1780 }
1781
1782 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1783 /// 2 subtrees.
1784 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1785                                                    CaseRecVector& WorkList,
1786                                                    Value* SV,
1787                                                    MachineBasicBlock* Default) {
1788   // Get the MachineFunction which holds the current MBB.  This is used when
1789   // inserting any additional MBBs necessary to represent the switch.
1790   MachineFunction *CurMF = CurMBB->getParent();
1791
1792   // Figure out which block is immediately after the current one.
1793   MachineBasicBlock *NextBlock = 0;
1794   MachineFunction::iterator BBI = CR.CaseBB;
1795
1796   if (++BBI != CurMBB->getParent()->end())
1797     NextBlock = BBI;
1798
1799   Case& FrontCase = *CR.Range.first;
1800   Case& BackCase  = *(CR.Range.second-1);
1801   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1802
1803   // Size is the number of Cases represented by this range.
1804   unsigned Size = CR.Range.second - CR.Range.first;
1805
1806   const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1807   const APInt& Last  = cast<ConstantInt>(BackCase.High)->getValue();
1808   double FMetric = 0;
1809   CaseItr Pivot = CR.Range.first + Size/2;
1810
1811   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1812   // (heuristically) allow us to emit JumpTable's later.
1813   size_t TSize = 0;
1814   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1815        I!=E; ++I)
1816     TSize += I->size();
1817
1818   size_t LSize = FrontCase.size();
1819   size_t RSize = TSize-LSize;
1820   DEBUG(errs() << "Selecting best pivot: \n"
1821                << "First: " << First << ", Last: " << Last <<'\n'
1822                << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1823   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1824        J!=E; ++I, ++J) {
1825     const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1826     const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
1827     APInt Range = ComputeRange(LEnd, RBegin);
1828     assert((Range - 2ULL).isNonNegative() &&
1829            "Invalid case distance");
1830     double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1831     double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
1832     double Metric = Range.logBase2()*(LDensity+RDensity);
1833     // Should always split in some non-trivial place
1834     DEBUG(errs() <<"=>Step\n"
1835                  << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1836                  << "LDensity: " << LDensity
1837                  << ", RDensity: " << RDensity << '\n'
1838                  << "Metric: " << Metric << '\n');
1839     if (FMetric < Metric) {
1840       Pivot = J;
1841       FMetric = Metric;
1842       DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1843     }
1844
1845     LSize += J->size();
1846     RSize -= J->size();
1847   }
1848   if (areJTsAllowed(TLI)) {
1849     // If our case is dense we *really* should handle it earlier!
1850     assert((FMetric > 0) && "Should handle dense range earlier!");
1851   } else {
1852     Pivot = CR.Range.first + Size/2;
1853   }
1854
1855   CaseRange LHSR(CR.Range.first, Pivot);
1856   CaseRange RHSR(Pivot, CR.Range.second);
1857   Constant *C = Pivot->Low;
1858   MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1859
1860   // We know that we branch to the LHS if the Value being switched on is
1861   // less than the Pivot value, C.  We use this to optimize our binary
1862   // tree a bit, by recognizing that if SV is greater than or equal to the
1863   // LHS's Case Value, and that Case Value is exactly one less than the
1864   // Pivot's Value, then we can branch directly to the LHS's Target,
1865   // rather than creating a leaf node for it.
1866   if ((LHSR.second - LHSR.first) == 1 &&
1867       LHSR.first->High == CR.GE &&
1868       cast<ConstantInt>(C)->getValue() ==
1869       (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1870     TrueBB = LHSR.first->BB;
1871   } else {
1872     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1873     CurMF->insert(BBI, TrueBB);
1874     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1875   }
1876
1877   // Similar to the optimization above, if the Value being switched on is
1878   // known to be less than the Constant CR.LT, and the current Case Value
1879   // is CR.LT - 1, then we can branch directly to the target block for
1880   // the current Case Value, rather than emitting a RHS leaf node for it.
1881   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1882       cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1883       (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1884     FalseBB = RHSR.first->BB;
1885   } else {
1886     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1887     CurMF->insert(BBI, FalseBB);
1888     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1889   }
1890
1891   // Create a CaseBlock record representing a conditional branch to
1892   // the LHS node if the value being switched on SV is less than C.
1893   // Otherwise, branch to LHS.
1894   CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1895
1896   if (CR.CaseBB == CurMBB)
1897     visitSwitchCase(CB);
1898   else
1899     SwitchCases.push_back(CB);
1900
1901   return true;
1902 }
1903
1904 /// handleBitTestsSwitchCase - if current case range has few destination and
1905 /// range span less, than machine word bitwidth, encode case range into series
1906 /// of masks and emit bit tests with these masks.
1907 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1908                                                     CaseRecVector& WorkList,
1909                                                     Value* SV,
1910                                                     MachineBasicBlock* Default){
1911   unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1912
1913   Case& FrontCase = *CR.Range.first;
1914   Case& BackCase  = *(CR.Range.second-1);
1915
1916   // Get the MachineFunction which holds the current MBB.  This is used when
1917   // inserting any additional MBBs necessary to represent the switch.
1918   MachineFunction *CurMF = CurMBB->getParent();
1919
1920   size_t numCmps = 0;
1921   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1922        I!=E; ++I) {
1923     // Single case counts one, case range - two.
1924     numCmps += (I->Low == I->High ? 1 : 2);
1925   }
1926
1927   // Count unique destinations
1928   SmallSet<MachineBasicBlock*, 4> Dests;
1929   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1930     Dests.insert(I->BB);
1931     if (Dests.size() > 3)
1932       // Don't bother the code below, if there are too much unique destinations
1933       return false;
1934   }
1935   DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1936                << "Total number of comparisons: " << numCmps << '\n');
1937
1938   // Compute span of values.
1939   const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1940   const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1941   APInt cmpRange = maxValue - minValue;
1942
1943   DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1944                << "Low bound: " << minValue << '\n'
1945                << "High bound: " << maxValue << '\n');
1946
1947   if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1948       (!(Dests.size() == 1 && numCmps >= 3) &&
1949        !(Dests.size() == 2 && numCmps >= 5) &&
1950        !(Dests.size() >= 3 && numCmps >= 6)))
1951     return false;
1952
1953   DEBUG(errs() << "Emitting bit tests\n");
1954   APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1955
1956   // Optimize the case where all the case values fit in a
1957   // word without having to subtract minValue. In this case,
1958   // we can optimize away the subtraction.
1959   if (minValue.isNonNegative() &&
1960       maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1961     cmpRange = maxValue;
1962   } else {
1963     lowBound = minValue;
1964   }
1965
1966   CaseBitsVector CasesBits;
1967   unsigned i, count = 0;
1968
1969   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1970     MachineBasicBlock* Dest = I->BB;
1971     for (i = 0; i < count; ++i)
1972       if (Dest == CasesBits[i].BB)
1973         break;
1974
1975     if (i == count) {
1976       assert((count < 3) && "Too much destinations to test!");
1977       CasesBits.push_back(CaseBits(0, Dest, 0));
1978       count++;
1979     }
1980
1981     const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1982     const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1983
1984     uint64_t lo = (lowValue - lowBound).getZExtValue();
1985     uint64_t hi = (highValue - lowBound).getZExtValue();
1986
1987     for (uint64_t j = lo; j <= hi; j++) {
1988       CasesBits[i].Mask |=  1ULL << j;
1989       CasesBits[i].Bits++;
1990     }
1991
1992   }
1993   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1994
1995   BitTestInfo BTC;
1996
1997   // Figure out which block is immediately after the current one.
1998   MachineFunction::iterator BBI = CR.CaseBB;
1999   ++BBI;
2000
2001   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2002
2003   DEBUG(errs() << "Cases:\n");
2004   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2005     DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2006                  << ", Bits: " << CasesBits[i].Bits
2007                  << ", BB: " << CasesBits[i].BB << '\n');
2008
2009     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2010     CurMF->insert(BBI, CaseBB);
2011     BTC.push_back(BitTestCase(CasesBits[i].Mask,
2012                               CaseBB,
2013                               CasesBits[i].BB));
2014   }
2015
2016   BitTestBlock BTB(lowBound, cmpRange, SV,
2017                    -1U, (CR.CaseBB == CurMBB),
2018                    CR.CaseBB, Default, BTC);
2019
2020   if (CR.CaseBB == CurMBB)
2021     visitBitTestHeader(BTB);
2022
2023   BitTestCases.push_back(BTB);
2024
2025   return true;
2026 }
2027
2028
2029 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2030 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
2031                                           const SwitchInst& SI) {
2032   size_t numCmps = 0;
2033
2034   // Start with "simple" cases
2035   for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2036     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2037     Cases.push_back(Case(SI.getSuccessorValue(i),
2038                          SI.getSuccessorValue(i),
2039                          SMBB));
2040   }
2041   std::sort(Cases.begin(), Cases.end(), CaseCmp());
2042
2043   // Merge case into clusters
2044   if (Cases.size() >= 2)
2045     // Must recompute end() each iteration because it may be
2046     // invalidated by erase if we hold on to it
2047     for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2048       const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2049       const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2050       MachineBasicBlock* nextBB = J->BB;
2051       MachineBasicBlock* currentBB = I->BB;
2052
2053       // If the two neighboring cases go to the same destination, merge them
2054       // into a single case.
2055       if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2056         I->High = J->High;
2057         J = Cases.erase(J);
2058       } else {
2059         I = J++;
2060       }
2061     }
2062
2063   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2064     if (I->Low != I->High)
2065       // A range counts double, since it requires two compares.
2066       ++numCmps;
2067   }
2068
2069   return numCmps;
2070 }
2071
2072 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2073   // Figure out which block is immediately after the current one.
2074   MachineBasicBlock *NextBlock = 0;
2075   MachineFunction::iterator BBI = CurMBB;
2076
2077   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2078
2079   // If there is only the default destination, branch to it if it is not the
2080   // next basic block.  Otherwise, just fall through.
2081   if (SI.getNumOperands() == 2) {
2082     // Update machine-CFG edges.
2083
2084     // If this is not a fall-through branch, emit the branch.
2085     CurMBB->addSuccessor(Default);
2086     if (Default != NextBlock)
2087       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2088                               MVT::Other, getControlRoot(),
2089                               DAG.getBasicBlock(Default)));
2090     return;
2091   }
2092
2093   // If there are any non-default case statements, create a vector of Cases
2094   // representing each one, and sort the vector so that we can efficiently
2095   // create a binary search tree from them.
2096   CaseVector Cases;
2097   size_t numCmps = Clusterify(Cases, SI);
2098   DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2099                << ". Total compares: " << numCmps << '\n');
2100   numCmps = 0;
2101
2102   // Get the Value to be switched on and default basic blocks, which will be
2103   // inserted into CaseBlock records, representing basic blocks in the binary
2104   // search tree.
2105   Value *SV = SI.getOperand(0);
2106
2107   // Push the initial CaseRec onto the worklist
2108   CaseRecVector WorkList;
2109   WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2110
2111   while (!WorkList.empty()) {
2112     // Grab a record representing a case range to process off the worklist
2113     CaseRec CR = WorkList.back();
2114     WorkList.pop_back();
2115
2116     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2117       continue;
2118
2119     // If the range has few cases (two or less) emit a series of specific
2120     // tests.
2121     if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2122       continue;
2123
2124     // If the switch has more than 5 blocks, and at least 40% dense, and the
2125     // target supports indirect branches, then emit a jump table rather than
2126     // lowering the switch to a binary tree of conditional branches.
2127     if (handleJTSwitchCase(CR, WorkList, SV, Default))
2128       continue;
2129
2130     // Emit binary tree. We need to pick a pivot, and push left and right ranges
2131     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2132     handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2133   }
2134 }
2135
2136
2137 void SelectionDAGLowering::visitSub(User &I) {
2138   // -0.0 - X --> fneg
2139   const Type *Ty = I.getType();
2140   if (isa<VectorType>(Ty)) {
2141     if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2142       const VectorType *DestTy = cast<VectorType>(I.getType());
2143       const Type *ElTy = DestTy->getElementType();
2144       if (ElTy->isFloatingPoint()) {
2145         unsigned VL = DestTy->getNumElements();
2146         std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2147         Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2148         if (CV == CNZ) {
2149           SDValue Op2 = getValue(I.getOperand(1));
2150           setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2151                                    Op2.getValueType(), Op2));
2152           return;
2153         }
2154       }
2155     }
2156   }
2157   if (Ty->isFloatingPoint()) {
2158     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2159       if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2160         SDValue Op2 = getValue(I.getOperand(1));
2161         setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2162                                  Op2.getValueType(), Op2));
2163         return;
2164       }
2165   }
2166
2167   visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2168 }
2169
2170 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2171   SDValue Op1 = getValue(I.getOperand(0));
2172   SDValue Op2 = getValue(I.getOperand(1));
2173
2174   setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2175                            Op1.getValueType(), Op1, Op2));
2176 }
2177
2178 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2179   SDValue Op1 = getValue(I.getOperand(0));
2180   SDValue Op2 = getValue(I.getOperand(1));
2181   if (!isa<VectorType>(I.getType())) {
2182     if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
2183       Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2184                         TLI.getPointerTy(), Op2);
2185     else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
2186       Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2187                         TLI.getPointerTy(), Op2);
2188   }
2189
2190   setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2191                            Op1.getValueType(), Op1, Op2));
2192 }
2193
2194 void SelectionDAGLowering::visitICmp(User &I) {
2195   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2196   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2197     predicate = IC->getPredicate();
2198   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2199     predicate = ICmpInst::Predicate(IC->getPredicate());
2200   SDValue Op1 = getValue(I.getOperand(0));
2201   SDValue Op2 = getValue(I.getOperand(1));
2202   ISD::CondCode Opcode = getICmpCondCode(predicate);
2203   setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
2204 }
2205
2206 void SelectionDAGLowering::visitFCmp(User &I) {
2207   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2208   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2209     predicate = FC->getPredicate();
2210   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2211     predicate = FCmpInst::Predicate(FC->getPredicate());
2212   SDValue Op1 = getValue(I.getOperand(0));
2213   SDValue Op2 = getValue(I.getOperand(1));
2214   ISD::CondCode Condition = getFCmpCondCode(predicate);
2215   setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
2216 }
2217
2218 void SelectionDAGLowering::visitVICmp(User &I) {
2219   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2220   if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2221     predicate = IC->getPredicate();
2222   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2223     predicate = ICmpInst::Predicate(IC->getPredicate());
2224   SDValue Op1 = getValue(I.getOperand(0));
2225   SDValue Op2 = getValue(I.getOperand(1));
2226   ISD::CondCode Opcode = getICmpCondCode(predicate);
2227   setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
2228                              Op1, Op2, Opcode));
2229 }
2230
2231 void SelectionDAGLowering::visitVFCmp(User &I) {
2232   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2233   if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2234     predicate = FC->getPredicate();
2235   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2236     predicate = FCmpInst::Predicate(FC->getPredicate());
2237   SDValue Op1 = getValue(I.getOperand(0));
2238   SDValue Op2 = getValue(I.getOperand(1));
2239   ISD::CondCode Condition = getFCmpCondCode(predicate);
2240   MVT DestVT = TLI.getValueType(I.getType());
2241
2242   setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2243 }
2244
2245 void SelectionDAGLowering::visitSelect(User &I) {
2246   SmallVector<MVT, 4> ValueVTs;
2247   ComputeValueVTs(TLI, I.getType(), ValueVTs);
2248   unsigned NumValues = ValueVTs.size();
2249   if (NumValues != 0) {
2250     SmallVector<SDValue, 4> Values(NumValues);
2251     SDValue Cond     = getValue(I.getOperand(0));
2252     SDValue TrueVal  = getValue(I.getOperand(1));
2253     SDValue FalseVal = getValue(I.getOperand(2));
2254
2255     for (unsigned i = 0; i != NumValues; ++i)
2256       Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2257                               TrueVal.getValueType(), Cond,
2258                               SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2259                               SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2260
2261     setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2262                              DAG.getVTList(&ValueVTs[0], NumValues),
2263                              &Values[0], NumValues));
2264   }
2265 }
2266
2267
2268 void SelectionDAGLowering::visitTrunc(User &I) {
2269   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2270   SDValue N = getValue(I.getOperand(0));
2271   MVT DestVT = TLI.getValueType(I.getType());
2272   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2273 }
2274
2275 void SelectionDAGLowering::visitZExt(User &I) {
2276   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2277   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2278   SDValue N = getValue(I.getOperand(0));
2279   MVT DestVT = TLI.getValueType(I.getType());
2280   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2281 }
2282
2283 void SelectionDAGLowering::visitSExt(User &I) {
2284   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2285   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2286   SDValue N = getValue(I.getOperand(0));
2287   MVT DestVT = TLI.getValueType(I.getType());
2288   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2289 }
2290
2291 void SelectionDAGLowering::visitFPTrunc(User &I) {
2292   // FPTrunc is never a no-op cast, no need to check
2293   SDValue N = getValue(I.getOperand(0));
2294   MVT DestVT = TLI.getValueType(I.getType());
2295   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2296                            DestVT, N, DAG.getIntPtrConstant(0)));
2297 }
2298
2299 void SelectionDAGLowering::visitFPExt(User &I){
2300   // FPTrunc is never a no-op cast, no need to check
2301   SDValue N = getValue(I.getOperand(0));
2302   MVT DestVT = TLI.getValueType(I.getType());
2303   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2304 }
2305
2306 void SelectionDAGLowering::visitFPToUI(User &I) {
2307   // FPToUI is never a no-op cast, no need to check
2308   SDValue N = getValue(I.getOperand(0));
2309   MVT DestVT = TLI.getValueType(I.getType());
2310   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2311 }
2312
2313 void SelectionDAGLowering::visitFPToSI(User &I) {
2314   // FPToSI is never a no-op cast, no need to check
2315   SDValue N = getValue(I.getOperand(0));
2316   MVT DestVT = TLI.getValueType(I.getType());
2317   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2318 }
2319
2320 void SelectionDAGLowering::visitUIToFP(User &I) {
2321   // UIToFP is never a no-op cast, no need to check
2322   SDValue N = getValue(I.getOperand(0));
2323   MVT DestVT = TLI.getValueType(I.getType());
2324   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2325 }
2326
2327 void SelectionDAGLowering::visitSIToFP(User &I){
2328   // SIToFP is never a no-op cast, no need to check
2329   SDValue N = getValue(I.getOperand(0));
2330   MVT DestVT = TLI.getValueType(I.getType());
2331   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2332 }
2333
2334 void SelectionDAGLowering::visitPtrToInt(User &I) {
2335   // What to do depends on the size of the integer and the size of the pointer.
2336   // We can either truncate, zero extend, or no-op, accordingly.
2337   SDValue N = getValue(I.getOperand(0));
2338   MVT SrcVT = N.getValueType();
2339   MVT DestVT = TLI.getValueType(I.getType());
2340   SDValue Result;
2341   if (DestVT.bitsLT(SrcVT))
2342     Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2343   else
2344     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2345     Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2346   setValue(&I, Result);
2347 }
2348
2349 void SelectionDAGLowering::visitIntToPtr(User &I) {
2350   // What to do depends on the size of the integer and the size of the pointer.
2351   // We can either truncate, zero extend, or no-op, accordingly.
2352   SDValue N = getValue(I.getOperand(0));
2353   MVT SrcVT = N.getValueType();
2354   MVT DestVT = TLI.getValueType(I.getType());
2355   if (DestVT.bitsLT(SrcVT))
2356     setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2357   else
2358     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2359     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2360                              DestVT, N));
2361 }
2362
2363 void SelectionDAGLowering::visitBitCast(User &I) {
2364   SDValue N = getValue(I.getOperand(0));
2365   MVT DestVT = TLI.getValueType(I.getType());
2366
2367   // BitCast assures us that source and destination are the same size so this
2368   // is either a BIT_CONVERT or a no-op.
2369   if (DestVT != N.getValueType())
2370     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2371                              DestVT, N)); // convert types
2372   else
2373     setValue(&I, N); // noop cast.
2374 }
2375
2376 void SelectionDAGLowering::visitInsertElement(User &I) {
2377   SDValue InVec = getValue(I.getOperand(0));
2378   SDValue InVal = getValue(I.getOperand(1));
2379   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2380                                 TLI.getPointerTy(),
2381                                 getValue(I.getOperand(2)));
2382
2383   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2384                            TLI.getValueType(I.getType()),
2385                            InVec, InVal, InIdx));
2386 }
2387
2388 void SelectionDAGLowering::visitExtractElement(User &I) {
2389   SDValue InVec = getValue(I.getOperand(0));
2390   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2391                                 TLI.getPointerTy(),
2392                                 getValue(I.getOperand(1)));
2393   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2394                            TLI.getValueType(I.getType()), InVec, InIdx));
2395 }
2396
2397
2398 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2399 // from SIndx and increasing to the element length (undefs are allowed).
2400 static bool SequentialMask(SDValue Mask, unsigned SIndx) {
2401   unsigned MaskNumElts = Mask.getNumOperands();
2402   for (unsigned i = 0; i != MaskNumElts; ++i) {
2403     if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2404       unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2405       if (Idx != i + SIndx)
2406         return false;
2407     }
2408   }
2409   return true;
2410 }
2411
2412 void SelectionDAGLowering::visitShuffleVector(User &I) {
2413   SDValue Src1 = getValue(I.getOperand(0));
2414   SDValue Src2 = getValue(I.getOperand(1));
2415   SDValue Mask = getValue(I.getOperand(2));
2416
2417   MVT VT = TLI.getValueType(I.getType());
2418   MVT SrcVT = Src1.getValueType();
2419   int MaskNumElts = Mask.getNumOperands();
2420   int SrcNumElts = SrcVT.getVectorNumElements();
2421
2422   if (SrcNumElts == MaskNumElts) {
2423     setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2424                              VT, Src1, Src2, Mask));
2425     return;
2426   }
2427
2428   // Normalize the shuffle vector since mask and vector length don't match.
2429   MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2430
2431   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2432     // Mask is longer than the source vectors and is a multiple of the source
2433     // vectors.  We can use concatenate vector to make the mask and vectors
2434     // lengths match.
2435     if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2436       // The shuffle is concatenating two vectors together.
2437       setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2438                                VT, Src1, Src2));
2439       return;
2440     }
2441
2442     // Pad both vectors with undefs to make them the same length as the mask.
2443     unsigned NumConcat = MaskNumElts / SrcNumElts;
2444     SDValue UndefVal = DAG.getUNDEF(SrcVT);
2445
2446     SDValue* MOps1 = new SDValue[NumConcat];
2447     SDValue* MOps2 = new SDValue[NumConcat];
2448     MOps1[0] = Src1;
2449     MOps2[0] = Src2;
2450     for (unsigned i = 1; i != NumConcat; ++i) {
2451       MOps1[i] = UndefVal;
2452       MOps2[i] = UndefVal;
2453     }
2454     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2455                        VT, MOps1, NumConcat);
2456     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2457                        VT, MOps2, NumConcat);
2458
2459     delete [] MOps1;
2460     delete [] MOps2;
2461
2462     // Readjust mask for new input vector length.
2463     SmallVector<SDValue, 8> MappedOps;
2464     for (int i = 0; i != MaskNumElts; ++i) {
2465       if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2466         MappedOps.push_back(Mask.getOperand(i));
2467       } else {
2468         int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2469         if (Idx < SrcNumElts)
2470           MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2471         else
2472           MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2473                                               MaskEltVT));
2474       }
2475     }
2476     Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2477                        Mask.getValueType(),
2478                        &MappedOps[0], MappedOps.size());
2479
2480     setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2481                              VT, Src1, Src2, Mask));
2482     return;
2483   }
2484
2485   if (SrcNumElts > MaskNumElts) {
2486     // Resulting vector is shorter than the incoming vector.
2487     if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
2488       // Shuffle extracts 1st vector.
2489       setValue(&I, Src1);
2490       return;
2491     }
2492
2493     if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
2494       // Shuffle extracts 2nd vector.
2495       setValue(&I, Src2);
2496       return;
2497     }
2498
2499     // Analyze the access pattern of the vector to see if we can extract
2500     // two subvectors and do the shuffle. The analysis is done by calculating
2501     // the range of elements the mask access on both vectors.
2502     int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2503     int MaxRange[2] = {-1, -1};
2504
2505     for (int i = 0; i != MaskNumElts; ++i) {
2506       SDValue Arg = Mask.getOperand(i);
2507       if (Arg.getOpcode() != ISD::UNDEF) {
2508         assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2509         int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2510         int Input = 0;
2511         if (Idx >= SrcNumElts) {
2512           Input = 1;
2513           Idx -= SrcNumElts;
2514         }
2515         if (Idx > MaxRange[Input])
2516           MaxRange[Input] = Idx;
2517         if (Idx < MinRange[Input])
2518           MinRange[Input] = Idx;
2519       }
2520     }
2521
2522     // Check if the access is smaller than the vector size and can we find
2523     // a reasonable extract index.
2524     int RangeUse[2] = { 2, 2 };  // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2525     int StartIdx[2];  // StartIdx to extract from
2526     for (int Input=0; Input < 2; ++Input) {
2527       if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2528         RangeUse[Input] = 0; // Unused
2529         StartIdx[Input] = 0;
2530       } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2531         // Fits within range but we should see if we can find a good
2532         // start index that is a multiple of the mask length.
2533         if (MaxRange[Input] < MaskNumElts) {
2534           RangeUse[Input] = 1; // Extract from beginning of the vector
2535           StartIdx[Input] = 0;
2536         } else {
2537           StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2538           if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2539               StartIdx[Input] + MaskNumElts < SrcNumElts)
2540             RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2541         }
2542       }
2543     }
2544
2545     if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2546       setValue(&I, DAG.getUNDEF(VT));  // Vectors are not used.
2547       return;
2548     }
2549     else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2550       // Extract appropriate subvector and generate a vector shuffle
2551       for (int Input=0; Input < 2; ++Input) {
2552         SDValue& Src = Input == 0 ? Src1 : Src2;
2553         if (RangeUse[Input] == 0) {
2554           Src = DAG.getUNDEF(VT);
2555         } else {
2556           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2557                             Src, DAG.getIntPtrConstant(StartIdx[Input]));
2558         }
2559       }
2560       // Calculate new mask.
2561       SmallVector<SDValue, 8> MappedOps;
2562       for (int i = 0; i != MaskNumElts; ++i) {
2563         SDValue Arg = Mask.getOperand(i);
2564         if (Arg.getOpcode() == ISD::UNDEF) {
2565           MappedOps.push_back(Arg);
2566         } else {
2567           int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2568           if (Idx < SrcNumElts)
2569             MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2570           else {
2571             Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2572             MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2573           }
2574         }
2575       }
2576       Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2577                          Mask.getValueType(),
2578                          &MappedOps[0], MappedOps.size());
2579       setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2580                                VT, Src1, Src2, Mask));
2581       return;
2582     }
2583   }
2584
2585   // We can't use either concat vectors or extract subvectors so fall back to
2586   // replacing the shuffle with extract and build vector.
2587   // to insert and build vector.
2588   MVT EltVT = VT.getVectorElementType();
2589   MVT PtrVT = TLI.getPointerTy();
2590   SmallVector<SDValue,8> Ops;
2591   for (int i = 0; i != MaskNumElts; ++i) {
2592     SDValue Arg = Mask.getOperand(i);
2593     if (Arg.getOpcode() == ISD::UNDEF) {
2594       Ops.push_back(DAG.getUNDEF(EltVT));
2595     } else {
2596       assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2597       int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2598       if (Idx < SrcNumElts)
2599         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2600                                   EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
2601       else
2602         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2603                                   EltVT, Src2,
2604                                   DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2605     }
2606   }
2607   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2608                            VT, &Ops[0], Ops.size()));
2609 }
2610
2611 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2612   const Value *Op0 = I.getOperand(0);
2613   const Value *Op1 = I.getOperand(1);
2614   const Type *AggTy = I.getType();
2615   const Type *ValTy = Op1->getType();
2616   bool IntoUndef = isa<UndefValue>(Op0);
2617   bool FromUndef = isa<UndefValue>(Op1);
2618
2619   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2620                                             I.idx_begin(), I.idx_end());
2621
2622   SmallVector<MVT, 4> AggValueVTs;
2623   ComputeValueVTs(TLI, AggTy, AggValueVTs);
2624   SmallVector<MVT, 4> ValValueVTs;
2625   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2626
2627   unsigned NumAggValues = AggValueVTs.size();
2628   unsigned NumValValues = ValValueVTs.size();
2629   SmallVector<SDValue, 4> Values(NumAggValues);
2630
2631   SDValue Agg = getValue(Op0);
2632   SDValue Val = getValue(Op1);
2633   unsigned i = 0;
2634   // Copy the beginning value(s) from the original aggregate.
2635   for (; i != LinearIndex; ++i)
2636     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2637                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2638   // Copy values from the inserted value(s).
2639   for (; i != LinearIndex + NumValValues; ++i)
2640     Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2641                 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2642   // Copy remaining value(s) from the original aggregate.
2643   for (; i != NumAggValues; ++i)
2644     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2645                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2646
2647   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2648                            DAG.getVTList(&AggValueVTs[0], NumAggValues),
2649                            &Values[0], NumAggValues));
2650 }
2651
2652 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2653   const Value *Op0 = I.getOperand(0);
2654   const Type *AggTy = Op0->getType();
2655   const Type *ValTy = I.getType();
2656   bool OutOfUndef = isa<UndefValue>(Op0);
2657
2658   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2659                                             I.idx_begin(), I.idx_end());
2660
2661   SmallVector<MVT, 4> ValValueVTs;
2662   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2663
2664   unsigned NumValValues = ValValueVTs.size();
2665   SmallVector<SDValue, 4> Values(NumValValues);
2666
2667   SDValue Agg = getValue(Op0);
2668   // Copy out the selected value(s).
2669   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2670     Values[i - LinearIndex] =
2671       OutOfUndef ?
2672         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2673         SDValue(Agg.getNode(), Agg.getResNo() + i);
2674
2675   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2676                            DAG.getVTList(&ValValueVTs[0], NumValValues),
2677                            &Values[0], NumValValues));
2678 }
2679
2680
2681 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2682   SDValue N = getValue(I.getOperand(0));
2683   const Type *Ty = I.getOperand(0)->getType();
2684
2685   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2686        OI != E; ++OI) {
2687     Value *Idx = *OI;
2688     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2689       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2690       if (Field) {
2691         // N = N + Offset
2692         uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2693         N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2694                         DAG.getIntPtrConstant(Offset));
2695       }
2696       Ty = StTy->getElementType(Field);
2697     } else {
2698       Ty = cast<SequentialType>(Ty)->getElementType();
2699
2700       // If this is a constant subscript, handle it quickly.
2701       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2702         if (CI->getZExtValue() == 0) continue;
2703         uint64_t Offs =
2704             TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2705         SDValue OffsVal;
2706         unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
2707         if (PtrBits < 64) {
2708           OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2709                                 TLI.getPointerTy(),
2710                                 DAG.getConstant(Offs, MVT::i64));
2711         } else
2712           OffsVal = DAG.getIntPtrConstant(Offs);
2713         N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2714                         OffsVal);
2715         continue;
2716       }
2717
2718       // N = N + Idx * ElementSize;
2719       uint64_t ElementSize = TD->getTypePaddedSize(Ty);
2720       SDValue IdxN = getValue(Idx);
2721
2722       // If the index is smaller or larger than intptr_t, truncate or extend
2723       // it.
2724       if (IdxN.getValueType().bitsLT(N.getValueType()))
2725         IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
2726                            N.getValueType(), IdxN);
2727       else if (IdxN.getValueType().bitsGT(N.getValueType()))
2728         IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2729                            N.getValueType(), IdxN);
2730
2731       // If this is a multiply by a power of two, turn it into a shl
2732       // immediately.  This is a very common case.
2733       if (ElementSize != 1) {
2734         if (isPowerOf2_64(ElementSize)) {
2735           unsigned Amt = Log2_64(ElementSize);
2736           IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2737                              N.getValueType(), IdxN,
2738                              DAG.getConstant(Amt, TLI.getPointerTy()));
2739         } else {
2740           SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2741           IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2742                              N.getValueType(), IdxN, Scale);
2743         }
2744       }
2745
2746       N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2747                       N.getValueType(), N, IdxN);
2748     }
2749   }
2750   setValue(&I, N);
2751 }
2752
2753 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2754   // If this is a fixed sized alloca in the entry block of the function,
2755   // allocate it statically on the stack.
2756   if (FuncInfo.StaticAllocaMap.count(&I))
2757     return;   // getValue will auto-populate this.
2758
2759   const Type *Ty = I.getAllocatedType();
2760   uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
2761   unsigned Align =
2762     std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2763              I.getAlignment());
2764
2765   SDValue AllocSize = getValue(I.getArraySize());
2766   MVT IntPtr = TLI.getPointerTy();
2767   if (IntPtr.bitsLT(AllocSize.getValueType()))
2768     AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2769                             IntPtr, AllocSize);
2770   else if (IntPtr.bitsGT(AllocSize.getValueType()))
2771     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2772                             IntPtr, AllocSize);
2773
2774   AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr, AllocSize,
2775                           DAG.getIntPtrConstant(TySize));
2776
2777   // Handle alignment.  If the requested alignment is less than or equal to
2778   // the stack alignment, ignore it.  If the size is greater than or equal to
2779   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2780   unsigned StackAlign =
2781     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2782   if (Align <= StackAlign)
2783     Align = 0;
2784
2785   // Round the size of the allocation up to the stack alignment size
2786   // by add SA-1 to the size.
2787   AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2788                           AllocSize.getValueType(), AllocSize,
2789                           DAG.getIntPtrConstant(StackAlign-1));
2790   // Mask out the low bits for alignment purposes.
2791   AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2792                           AllocSize.getValueType(), AllocSize,
2793                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2794
2795   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2796   const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2797                                                     MVT::Other);
2798   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2799                             VTs, 2, Ops, 3);
2800   setValue(&I, DSA);
2801   DAG.setRoot(DSA.getValue(1));
2802
2803   // Inform the Frame Information that we have just allocated a variable-sized
2804   // object.
2805   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2806 }
2807
2808 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2809   const Value *SV = I.getOperand(0);
2810   SDValue Ptr = getValue(SV);
2811
2812   const Type *Ty = I.getType();
2813   bool isVolatile = I.isVolatile();
2814   unsigned Alignment = I.getAlignment();
2815
2816   SmallVector<MVT, 4> ValueVTs;
2817   SmallVector<uint64_t, 4> Offsets;
2818   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2819   unsigned NumValues = ValueVTs.size();
2820   if (NumValues == 0)
2821     return;
2822
2823   SDValue Root;
2824   bool ConstantMemory = false;
2825   if (I.isVolatile())
2826     // Serialize volatile loads with other side effects.
2827     Root = getRoot();
2828   else if (AA->pointsToConstantMemory(SV)) {
2829     // Do not serialize (non-volatile) loads of constant memory with anything.
2830     Root = DAG.getEntryNode();
2831     ConstantMemory = true;
2832   } else {
2833     // Do not serialize non-volatile loads against each other.
2834     Root = DAG.getRoot();
2835   }
2836
2837   SmallVector<SDValue, 4> Values(NumValues);
2838   SmallVector<SDValue, 4> Chains(NumValues);
2839   MVT PtrVT = Ptr.getValueType();
2840   for (unsigned i = 0; i != NumValues; ++i) {
2841     SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2842                               DAG.getNode(ISD::ADD, getCurDebugLoc(),
2843                                           PtrVT, Ptr,
2844                                           DAG.getConstant(Offsets[i], PtrVT)),
2845                               SV, Offsets[i],
2846                               isVolatile, Alignment);
2847     Values[i] = L;
2848     Chains[i] = L.getValue(1);
2849   }
2850
2851   if (!ConstantMemory) {
2852     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2853                                   MVT::Other,
2854                                   &Chains[0], NumValues);
2855     if (isVolatile)
2856       DAG.setRoot(Chain);
2857     else
2858       PendingLoads.push_back(Chain);
2859   }
2860
2861   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2862                            DAG.getVTList(&ValueVTs[0], NumValues),
2863                            &Values[0], NumValues));
2864 }
2865
2866
2867 void SelectionDAGLowering::visitStore(StoreInst &I) {
2868   Value *SrcV = I.getOperand(0);
2869   Value *PtrV = I.getOperand(1);
2870
2871   SmallVector<MVT, 4> ValueVTs;
2872   SmallVector<uint64_t, 4> Offsets;
2873   ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2874   unsigned NumValues = ValueVTs.size();
2875   if (NumValues == 0)
2876     return;
2877
2878   // Get the lowered operands. Note that we do this after
2879   // checking if NumResults is zero, because with zero results
2880   // the operands won't have values in the map.
2881   SDValue Src = getValue(SrcV);
2882   SDValue Ptr = getValue(PtrV);
2883
2884   SDValue Root = getRoot();
2885   SmallVector<SDValue, 4> Chains(NumValues);
2886   MVT PtrVT = Ptr.getValueType();
2887   bool isVolatile = I.isVolatile();
2888   unsigned Alignment = I.getAlignment();
2889   for (unsigned i = 0; i != NumValues; ++i)
2890     Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2891                              SDValue(Src.getNode(), Src.getResNo() + i),
2892                              DAG.getNode(ISD::ADD, getCurDebugLoc(),
2893                                          PtrVT, Ptr,
2894                                          DAG.getConstant(Offsets[i], PtrVT)),
2895                              PtrV, Offsets[i],
2896                              isVolatile, Alignment);
2897
2898   DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2899                           MVT::Other, &Chains[0], NumValues));
2900 }
2901
2902 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2903 /// node.
2904 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2905                                                 unsigned Intrinsic) {
2906   bool HasChain = !I.doesNotAccessMemory();
2907   bool OnlyLoad = HasChain && I.onlyReadsMemory();
2908
2909   // Build the operand list.
2910   SmallVector<SDValue, 8> Ops;
2911   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
2912     if (OnlyLoad) {
2913       // We don't need to serialize loads against other loads.
2914       Ops.push_back(DAG.getRoot());
2915     } else {
2916       Ops.push_back(getRoot());
2917     }
2918   }
2919
2920   // Info is set by getTgtMemInstrinsic
2921   TargetLowering::IntrinsicInfo Info;
2922   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2923
2924   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2925   if (!IsTgtIntrinsic)
2926     Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2927
2928   // Add all operands of the call to the operand list.
2929   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2930     SDValue Op = getValue(I.getOperand(i));
2931     assert(TLI.isTypeLegal(Op.getValueType()) &&
2932            "Intrinsic uses a non-legal type?");
2933     Ops.push_back(Op);
2934   }
2935
2936   std::vector<MVT> VTs;
2937   if (I.getType() != Type::VoidTy) {
2938     MVT VT = TLI.getValueType(I.getType());
2939     if (VT.isVector()) {
2940       const VectorType *DestTy = cast<VectorType>(I.getType());
2941       MVT EltVT = TLI.getValueType(DestTy->getElementType());
2942
2943       VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2944       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2945     }
2946
2947     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2948     VTs.push_back(VT);
2949   }
2950   if (HasChain)
2951     VTs.push_back(MVT::Other);
2952
2953   const MVT *VTList = DAG.getNodeValueTypes(VTs);
2954
2955   // Create the node.
2956   SDValue Result;
2957   if (IsTgtIntrinsic) {
2958     // This is target intrinsic that touches memory
2959     Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2960                                      VTList, VTs.size(),
2961                                      &Ops[0], Ops.size(),
2962                                      Info.memVT, Info.ptrVal, Info.offset,
2963                                      Info.align, Info.vol,
2964                                      Info.readMem, Info.writeMem);
2965   }
2966   else if (!HasChain)
2967     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2968                          VTList, VTs.size(),
2969                          &Ops[0], Ops.size());
2970   else if (I.getType() != Type::VoidTy)
2971     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2972                          VTList, VTs.size(),
2973                          &Ops[0], Ops.size());
2974   else
2975     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2976                          VTList, VTs.size(),
2977                          &Ops[0], Ops.size());
2978
2979   if (HasChain) {
2980     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2981     if (OnlyLoad)
2982       PendingLoads.push_back(Chain);
2983     else
2984       DAG.setRoot(Chain);
2985   }
2986   if (I.getType() != Type::VoidTy) {
2987     if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2988       MVT VT = TLI.getValueType(PTy);
2989       Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2990     }
2991     setValue(&I, Result);
2992   }
2993 }
2994
2995 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2996 static GlobalVariable *ExtractTypeInfo(Value *V) {
2997   V = V->stripPointerCasts();
2998   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2999   assert ((GV || isa<ConstantPointerNull>(V)) &&
3000           "TypeInfo must be a global variable or NULL");
3001   return GV;
3002 }
3003
3004 namespace llvm {
3005
3006 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
3007 /// call, and add them to the specified machine basic block.
3008 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3009                   MachineBasicBlock *MBB) {
3010   // Inform the MachineModuleInfo of the personality for this landing pad.
3011   ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3012   assert(CE->getOpcode() == Instruction::BitCast &&
3013          isa<Function>(CE->getOperand(0)) &&
3014          "Personality should be a function");
3015   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3016
3017   // Gather all the type infos for this landing pad and pass them along to
3018   // MachineModuleInfo.
3019   std::vector<GlobalVariable *> TyInfo;
3020   unsigned N = I.getNumOperands();
3021
3022   for (unsigned i = N - 1; i > 2; --i) {
3023     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3024       unsigned FilterLength = CI->getZExtValue();
3025       unsigned FirstCatch = i + FilterLength + !FilterLength;
3026       assert (FirstCatch <= N && "Invalid filter length");
3027
3028       if (FirstCatch < N) {
3029         TyInfo.reserve(N - FirstCatch);
3030         for (unsigned j = FirstCatch; j < N; ++j)
3031           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3032         MMI->addCatchTypeInfo(MBB, TyInfo);
3033         TyInfo.clear();
3034       }
3035
3036       if (!FilterLength) {
3037         // Cleanup.
3038         MMI->addCleanup(MBB);
3039       } else {
3040         // Filter.
3041         TyInfo.reserve(FilterLength - 1);
3042         for (unsigned j = i + 1; j < FirstCatch; ++j)
3043           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3044         MMI->addFilterTypeInfo(MBB, TyInfo);
3045         TyInfo.clear();
3046       }
3047
3048       N = i;
3049     }
3050   }
3051
3052   if (N > 3) {
3053     TyInfo.reserve(N - 3);
3054     for (unsigned j = 3; j < N; ++j)
3055       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3056     MMI->addCatchTypeInfo(MBB, TyInfo);
3057   }
3058 }
3059
3060 }
3061
3062 /// GetSignificand - Get the significand and build it into a floating-point
3063 /// number with exponent of 1:
3064 ///
3065 ///   Op = (Op & 0x007fffff) | 0x3f800000;
3066 ///
3067 /// where Op is the hexidecimal representation of floating point value.
3068 static SDValue
3069 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3070   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3071                            DAG.getConstant(0x007fffff, MVT::i32));
3072   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3073                            DAG.getConstant(0x3f800000, MVT::i32));
3074   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3075 }
3076
3077 /// GetExponent - Get the exponent:
3078 ///
3079 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3080 ///
3081 /// where Op is the hexidecimal representation of floating point value.
3082 static SDValue
3083 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3084             DebugLoc dl) {
3085   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3086                            DAG.getConstant(0x7f800000, MVT::i32));
3087   SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3088                            DAG.getConstant(23, TLI.getPointerTy()));
3089   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3090                            DAG.getConstant(127, MVT::i32));
3091   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3092 }
3093
3094 /// getF32Constant - Get 32-bit floating point constant.
3095 static SDValue
3096 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3097   return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3098 }
3099
3100 /// Inlined utility function to implement binary input atomic intrinsics for
3101 /// visitIntrinsicCall: I is a call instruction
3102 ///                     Op is the associated NodeType for I
3103 const char *
3104 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3105   SDValue Root = getRoot();
3106   SDValue L =
3107     DAG.getAtomic(Op, getCurDebugLoc(),
3108                   getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3109                   Root,
3110                   getValue(I.getOperand(1)),
3111                   getValue(I.getOperand(2)),
3112                   I.getOperand(1));
3113   setValue(&I, L);
3114   DAG.setRoot(L.getValue(1));
3115   return 0;
3116 }
3117
3118 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3119 const char *
3120 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3121   SDValue Op1 = getValue(I.getOperand(1));
3122   SDValue Op2 = getValue(I.getOperand(2));
3123
3124   MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
3125   SDValue Ops[] = { Op1, Op2 };
3126
3127   SDValue Result = DAG.getNode(Op, getCurDebugLoc(),
3128                                DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
3129
3130   setValue(&I, Result);
3131   return 0;
3132 }
3133
3134 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3135 /// limited-precision mode.
3136 void
3137 SelectionDAGLowering::visitExp(CallInst &I) {
3138   SDValue result;
3139   DebugLoc dl = getCurDebugLoc();
3140
3141   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3142       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3143     SDValue Op = getValue(I.getOperand(1));
3144
3145     // Put the exponent in the right bit position for later addition to the
3146     // final result:
3147     //
3148     //   #define LOG2OFe 1.4426950f
3149     //   IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3150     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3151                              getF32Constant(DAG, 0x3fb8aa3b));
3152     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3153
3154     //   FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3155     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3156     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3157
3158     //   IntegerPartOfX <<= 23;
3159     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3160                                  DAG.getConstant(23, TLI.getPointerTy()));
3161
3162     if (LimitFloatPrecision <= 6) {
3163       // For floating-point precision of 6:
3164       //
3165       //   TwoToFractionalPartOfX =
3166       //     0.997535578f +
3167       //       (0.735607626f + 0.252464424f * x) * x;
3168       //
3169       // error 0.0144103317, which is 6 bits
3170       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3171                                getF32Constant(DAG, 0x3e814304));
3172       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3173                                getF32Constant(DAG, 0x3f3c50c8));
3174       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3175       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3176                                getF32Constant(DAG, 0x3f7f5e7e));
3177       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3178
3179       // Add the exponent into the result in integer domain.
3180       SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3181                                TwoToFracPartOfX, IntegerPartOfX);
3182
3183       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3184     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3185       // For floating-point precision of 12:
3186       //
3187       //   TwoToFractionalPartOfX =
3188       //     0.999892986f +
3189       //       (0.696457318f +
3190       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3191       //
3192       // 0.000107046256 error, which is 13 to 14 bits
3193       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3194                                getF32Constant(DAG, 0x3da235e3));
3195       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3196                                getF32Constant(DAG, 0x3e65b8f3));
3197       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3198       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3199                                getF32Constant(DAG, 0x3f324b07));
3200       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3201       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3202                                getF32Constant(DAG, 0x3f7ff8fd));
3203       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3204
3205       // Add the exponent into the result in integer domain.
3206       SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3207                                TwoToFracPartOfX, IntegerPartOfX);
3208
3209       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3210     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3211       // For floating-point precision of 18:
3212       //
3213       //   TwoToFractionalPartOfX =
3214       //     0.999999982f +
3215       //       (0.693148872f +
3216       //         (0.240227044f +
3217       //           (0.554906021e-1f +
3218       //             (0.961591928e-2f +
3219       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3220       //
3221       // error 2.47208000*10^(-7), which is better than 18 bits
3222       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3223                                getF32Constant(DAG, 0x3924b03e));
3224       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3225                                getF32Constant(DAG, 0x3ab24b87));
3226       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3227       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3228                                getF32Constant(DAG, 0x3c1d8c17));
3229       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3230       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3231                                getF32Constant(DAG, 0x3d634a1d));
3232       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3233       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3234                                getF32Constant(DAG, 0x3e75fe14));
3235       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3236       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3237                                 getF32Constant(DAG, 0x3f317234));
3238       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3239       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3240                                 getF32Constant(DAG, 0x3f800000));
3241       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3242                                              MVT::i32, t13);
3243
3244       // Add the exponent into the result in integer domain.
3245       SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3246                                 TwoToFracPartOfX, IntegerPartOfX);
3247
3248       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3249     }
3250   } else {
3251     // No special expansion.
3252     result = DAG.getNode(ISD::FEXP, dl,
3253                          getValue(I.getOperand(1)).getValueType(),
3254                          getValue(I.getOperand(1)));
3255   }
3256
3257   setValue(&I, result);
3258 }
3259
3260 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3261 /// limited-precision mode.
3262 void
3263 SelectionDAGLowering::visitLog(CallInst &I) {
3264   SDValue result;
3265   DebugLoc dl = getCurDebugLoc();
3266
3267   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3268       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3269     SDValue Op = getValue(I.getOperand(1));
3270     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3271
3272     // Scale the exponent by log(2) [0.69314718f].
3273     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3274     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3275                                         getF32Constant(DAG, 0x3f317218));
3276
3277     // Get the significand and build it into a floating-point number with
3278     // exponent of 1.
3279     SDValue X = GetSignificand(DAG, Op1, dl);
3280
3281     if (LimitFloatPrecision <= 6) {
3282       // For floating-point precision of 6:
3283       //
3284       //   LogofMantissa =
3285       //     -1.1609546f +
3286       //       (1.4034025f - 0.23903021f * x) * x;
3287       //
3288       // error 0.0034276066, which is better than 8 bits
3289       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3290                                getF32Constant(DAG, 0xbe74c456));
3291       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3292                                getF32Constant(DAG, 0x3fb3a2b1));
3293       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3294       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3295                                           getF32Constant(DAG, 0x3f949a29));
3296
3297       result = DAG.getNode(ISD::FADD, dl,
3298                            MVT::f32, LogOfExponent, LogOfMantissa);
3299     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3300       // For floating-point precision of 12:
3301       //
3302       //   LogOfMantissa =
3303       //     -1.7417939f +
3304       //       (2.8212026f +
3305       //         (-1.4699568f +
3306       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3307       //
3308       // error 0.000061011436, which is 14 bits
3309       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3310                                getF32Constant(DAG, 0xbd67b6d6));
3311       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3312                                getF32Constant(DAG, 0x3ee4f4b8));
3313       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3314       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3315                                getF32Constant(DAG, 0x3fbc278b));
3316       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3317       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3318                                getF32Constant(DAG, 0x40348e95));
3319       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3320       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3321                                           getF32Constant(DAG, 0x3fdef31a));
3322
3323       result = DAG.getNode(ISD::FADD, dl,
3324                            MVT::f32, LogOfExponent, LogOfMantissa);
3325     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3326       // For floating-point precision of 18:
3327       //
3328       //   LogOfMantissa =
3329       //     -2.1072184f +
3330       //       (4.2372794f +
3331       //         (-3.7029485f +
3332       //           (2.2781945f +
3333       //             (-0.87823314f +
3334       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3335       //
3336       // error 0.0000023660568, which is better than 18 bits
3337       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3338                                getF32Constant(DAG, 0xbc91e5ac));
3339       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3340                                getF32Constant(DAG, 0x3e4350aa));
3341       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3342       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3343                                getF32Constant(DAG, 0x3f60d3e3));
3344       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3345       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3346                                getF32Constant(DAG, 0x4011cdf0));
3347       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3348       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3349                                getF32Constant(DAG, 0x406cfd1c));
3350       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3351       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3352                                getF32Constant(DAG, 0x408797cb));
3353       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3354       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3355                                           getF32Constant(DAG, 0x4006dcab));
3356
3357       result = DAG.getNode(ISD::FADD, dl,
3358                            MVT::f32, LogOfExponent, LogOfMantissa);
3359     }
3360   } else {
3361     // No special expansion.
3362     result = DAG.getNode(ISD::FLOG, dl,
3363                          getValue(I.getOperand(1)).getValueType(),
3364                          getValue(I.getOperand(1)));
3365   }
3366
3367   setValue(&I, result);
3368 }
3369
3370 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3371 /// limited-precision mode.
3372 void
3373 SelectionDAGLowering::visitLog2(CallInst &I) {
3374   SDValue result;
3375   DebugLoc dl = getCurDebugLoc();
3376
3377   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3378       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3379     SDValue Op = getValue(I.getOperand(1));
3380     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3381
3382     // Get the exponent.
3383     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3384
3385     // Get the significand and build it into a floating-point number with
3386     // exponent of 1.
3387     SDValue X = GetSignificand(DAG, Op1, dl);
3388
3389     // Different possible minimax approximations of significand in
3390     // floating-point for various degrees of accuracy over [1,2].
3391     if (LimitFloatPrecision <= 6) {
3392       // For floating-point precision of 6:
3393       //
3394       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3395       //
3396       // error 0.0049451742, which is more than 7 bits
3397       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3398                                getF32Constant(DAG, 0xbeb08fe0));
3399       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3400                                getF32Constant(DAG, 0x40019463));
3401       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3402       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3403                                            getF32Constant(DAG, 0x3fd6633d));
3404
3405       result = DAG.getNode(ISD::FADD, dl,
3406                            MVT::f32, LogOfExponent, Log2ofMantissa);
3407     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3408       // For floating-point precision of 12:
3409       //
3410       //   Log2ofMantissa =
3411       //     -2.51285454f +
3412       //       (4.07009056f +
3413       //         (-2.12067489f +
3414       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3415       //
3416       // error 0.0000876136000, which is better than 13 bits
3417       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3418                                getF32Constant(DAG, 0xbda7262e));
3419       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3420                                getF32Constant(DAG, 0x3f25280b));
3421       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3422       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3423                                getF32Constant(DAG, 0x4007b923));
3424       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3425       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3426                                getF32Constant(DAG, 0x40823e2f));
3427       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3428       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3429                                            getF32Constant(DAG, 0x4020d29c));
3430
3431       result = DAG.getNode(ISD::FADD, dl,
3432                            MVT::f32, LogOfExponent, Log2ofMantissa);
3433     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3434       // For floating-point precision of 18:
3435       //
3436       //   Log2ofMantissa =
3437       //     -3.0400495f +
3438       //       (6.1129976f +
3439       //         (-5.3420409f +
3440       //           (3.2865683f +
3441       //             (-1.2669343f +
3442       //               (0.27515199f -
3443       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3444       //
3445       // error 0.0000018516, which is better than 18 bits
3446       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3447                                getF32Constant(DAG, 0xbcd2769e));
3448       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3449                                getF32Constant(DAG, 0x3e8ce0b9));
3450       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3451       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3452                                getF32Constant(DAG, 0x3fa22ae7));
3453       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3454       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3455                                getF32Constant(DAG, 0x40525723));
3456       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3457       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3458                                getF32Constant(DAG, 0x40aaf200));
3459       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3460       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3461                                getF32Constant(DAG, 0x40c39dad));
3462       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3463       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3464                                            getF32Constant(DAG, 0x4042902c));
3465
3466       result = DAG.getNode(ISD::FADD, dl,
3467                            MVT::f32, LogOfExponent, Log2ofMantissa);
3468     }
3469   } else {
3470     // No special expansion.
3471     result = DAG.getNode(ISD::FLOG2, dl,
3472                          getValue(I.getOperand(1)).getValueType(),
3473                          getValue(I.getOperand(1)));
3474   }
3475
3476   setValue(&I, result);
3477 }
3478
3479 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3480 /// limited-precision mode.
3481 void
3482 SelectionDAGLowering::visitLog10(CallInst &I) {
3483   SDValue result;
3484   DebugLoc dl = getCurDebugLoc();
3485
3486   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3487       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3488     SDValue Op = getValue(I.getOperand(1));
3489     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3490
3491     // Scale the exponent by log10(2) [0.30102999f].
3492     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3493     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3494                                         getF32Constant(DAG, 0x3e9a209a));
3495
3496     // Get the significand and build it into a floating-point number with
3497     // exponent of 1.
3498     SDValue X = GetSignificand(DAG, Op1, dl);
3499
3500     if (LimitFloatPrecision <= 6) {
3501       // For floating-point precision of 6:
3502       //
3503       //   Log10ofMantissa =
3504       //     -0.50419619f +
3505       //       (0.60948995f - 0.10380950f * x) * x;
3506       //
3507       // error 0.0014886165, which is 6 bits
3508       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3509                                getF32Constant(DAG, 0xbdd49a13));
3510       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3511                                getF32Constant(DAG, 0x3f1c0789));
3512       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3513       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3514                                             getF32Constant(DAG, 0x3f011300));
3515
3516       result = DAG.getNode(ISD::FADD, dl,
3517                            MVT::f32, LogOfExponent, Log10ofMantissa);
3518     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3519       // For floating-point precision of 12:
3520       //
3521       //   Log10ofMantissa =
3522       //     -0.64831180f +
3523       //       (0.91751397f +
3524       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3525       //
3526       // error 0.00019228036, which is better than 12 bits
3527       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3528                                getF32Constant(DAG, 0x3d431f31));
3529       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3530                                getF32Constant(DAG, 0x3ea21fb2));
3531       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3532       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3533                                getF32Constant(DAG, 0x3f6ae232));
3534       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3535       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3536                                             getF32Constant(DAG, 0x3f25f7c3));
3537
3538       result = DAG.getNode(ISD::FADD, dl,
3539                            MVT::f32, LogOfExponent, Log10ofMantissa);
3540     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3541       // For floating-point precision of 18:
3542       //
3543       //   Log10ofMantissa =
3544       //     -0.84299375f +
3545       //       (1.5327582f +
3546       //         (-1.0688956f +
3547       //           (0.49102474f +
3548       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3549       //
3550       // error 0.0000037995730, which is better than 18 bits
3551       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3552                                getF32Constant(DAG, 0x3c5d51ce));
3553       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3554                                getF32Constant(DAG, 0x3e00685a));
3555       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3556       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3557                                getF32Constant(DAG, 0x3efb6798));
3558       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3559       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3560                                getF32Constant(DAG, 0x3f88d192));
3561       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3562       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3563                                getF32Constant(DAG, 0x3fc4316c));
3564       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3565       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3566                                             getF32Constant(DAG, 0x3f57ce70));
3567
3568       result = DAG.getNode(ISD::FADD, dl,
3569                            MVT::f32, LogOfExponent, Log10ofMantissa);
3570     }
3571   } else {
3572     // No special expansion.
3573     result = DAG.getNode(ISD::FLOG10, dl,
3574                          getValue(I.getOperand(1)).getValueType(),
3575                          getValue(I.getOperand(1)));
3576   }
3577
3578   setValue(&I, result);
3579 }
3580
3581 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3582 /// limited-precision mode.
3583 void
3584 SelectionDAGLowering::visitExp2(CallInst &I) {
3585   SDValue result;
3586   DebugLoc dl = getCurDebugLoc();
3587
3588   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3589       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3590     SDValue Op = getValue(I.getOperand(1));
3591
3592     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3593
3594     //   FractionalPartOfX = x - (float)IntegerPartOfX;
3595     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3596     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3597
3598     //   IntegerPartOfX <<= 23;
3599     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3600                                  DAG.getConstant(23, TLI.getPointerTy()));
3601
3602     if (LimitFloatPrecision <= 6) {
3603       // For floating-point precision of 6:
3604       //
3605       //   TwoToFractionalPartOfX =
3606       //     0.997535578f +
3607       //       (0.735607626f + 0.252464424f * x) * x;
3608       //
3609       // error 0.0144103317, which is 6 bits
3610       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3611                                getF32Constant(DAG, 0x3e814304));
3612       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3613                                getF32Constant(DAG, 0x3f3c50c8));
3614       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3615       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3616                                getF32Constant(DAG, 0x3f7f5e7e));
3617       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3618       SDValue TwoToFractionalPartOfX =
3619         DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3620
3621       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3622                            MVT::f32, TwoToFractionalPartOfX);
3623     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3624       // For floating-point precision of 12:
3625       //
3626       //   TwoToFractionalPartOfX =
3627       //     0.999892986f +
3628       //       (0.696457318f +
3629       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3630       //
3631       // error 0.000107046256, which is 13 to 14 bits
3632       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3633                                getF32Constant(DAG, 0x3da235e3));
3634       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3635                                getF32Constant(DAG, 0x3e65b8f3));
3636       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3637       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3638                                getF32Constant(DAG, 0x3f324b07));
3639       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3640       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3641                                getF32Constant(DAG, 0x3f7ff8fd));
3642       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3643       SDValue TwoToFractionalPartOfX =
3644         DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3645
3646       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3647                            MVT::f32, TwoToFractionalPartOfX);
3648     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3649       // For floating-point precision of 18:
3650       //
3651       //   TwoToFractionalPartOfX =
3652       //     0.999999982f +
3653       //       (0.693148872f +
3654       //         (0.240227044f +
3655       //           (0.554906021e-1f +
3656       //             (0.961591928e-2f +
3657       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3658       // error 2.47208000*10^(-7), which is better than 18 bits
3659       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3660                                getF32Constant(DAG, 0x3924b03e));
3661       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3662                                getF32Constant(DAG, 0x3ab24b87));
3663       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3664       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3665                                getF32Constant(DAG, 0x3c1d8c17));
3666       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3667       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3668                                getF32Constant(DAG, 0x3d634a1d));
3669       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3670       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3671                                getF32Constant(DAG, 0x3e75fe14));
3672       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3673       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3674                                 getF32Constant(DAG, 0x3f317234));
3675       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3676       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3677                                 getF32Constant(DAG, 0x3f800000));
3678       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3679       SDValue TwoToFractionalPartOfX =
3680         DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3681
3682       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3683                            MVT::f32, TwoToFractionalPartOfX);
3684     }
3685   } else {
3686     // No special expansion.
3687     result = DAG.getNode(ISD::FEXP2, dl,
3688                          getValue(I.getOperand(1)).getValueType(),
3689                          getValue(I.getOperand(1)));
3690   }
3691
3692   setValue(&I, result);
3693 }
3694
3695 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3696 /// limited-precision mode with x == 10.0f.
3697 void
3698 SelectionDAGLowering::visitPow(CallInst &I) {
3699   SDValue result;
3700   Value *Val = I.getOperand(1);
3701   DebugLoc dl = getCurDebugLoc();
3702   bool IsExp10 = false;
3703
3704   if (getValue(Val).getValueType() == MVT::f32 &&
3705       getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3706       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3707     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3708       if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3709         APFloat Ten(10.0f);
3710         IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3711       }
3712     }
3713   }
3714
3715   if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3716     SDValue Op = getValue(I.getOperand(2));
3717
3718     // Put the exponent in the right bit position for later addition to the
3719     // final result:
3720     //
3721     //   #define LOG2OF10 3.3219281f
3722     //   IntegerPartOfX = (int32_t)(x * LOG2OF10);
3723     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3724                              getF32Constant(DAG, 0x40549a78));
3725     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3726
3727     //   FractionalPartOfX = x - (float)IntegerPartOfX;
3728     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3729     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3730
3731     //   IntegerPartOfX <<= 23;
3732     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3733                                  DAG.getConstant(23, TLI.getPointerTy()));
3734
3735     if (LimitFloatPrecision <= 6) {
3736       // For floating-point precision of 6:
3737       //
3738       //   twoToFractionalPartOfX =
3739       //     0.997535578f +
3740       //       (0.735607626f + 0.252464424f * x) * x;
3741       //
3742       // error 0.0144103317, which is 6 bits
3743       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3744                                getF32Constant(DAG, 0x3e814304));
3745       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3746                                getF32Constant(DAG, 0x3f3c50c8));
3747       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3748       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3749                                getF32Constant(DAG, 0x3f7f5e7e));
3750       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3751       SDValue TwoToFractionalPartOfX =
3752         DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3753
3754       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3755                            MVT::f32, TwoToFractionalPartOfX);
3756     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3757       // For floating-point precision of 12:
3758       //
3759       //   TwoToFractionalPartOfX =
3760       //     0.999892986f +
3761       //       (0.696457318f +
3762       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3763       //
3764       // error 0.000107046256, which is 13 to 14 bits
3765       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3766                                getF32Constant(DAG, 0x3da235e3));
3767       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3768                                getF32Constant(DAG, 0x3e65b8f3));
3769       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3770       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3771                                getF32Constant(DAG, 0x3f324b07));
3772       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3773       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3774                                getF32Constant(DAG, 0x3f7ff8fd));
3775       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3776       SDValue TwoToFractionalPartOfX =
3777         DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3778
3779       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3780                            MVT::f32, TwoToFractionalPartOfX);
3781     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3782       // For floating-point precision of 18:
3783       //
3784       //   TwoToFractionalPartOfX =
3785       //     0.999999982f +
3786       //       (0.693148872f +
3787       //         (0.240227044f +
3788       //           (0.554906021e-1f +
3789       //             (0.961591928e-2f +
3790       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3791       // error 2.47208000*10^(-7), which is better than 18 bits
3792       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3793                                getF32Constant(DAG, 0x3924b03e));
3794       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3795                                getF32Constant(DAG, 0x3ab24b87));
3796       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3797       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3798                                getF32Constant(DAG, 0x3c1d8c17));
3799       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3800       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3801                                getF32Constant(DAG, 0x3d634a1d));
3802       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3803       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3804                                getF32Constant(DAG, 0x3e75fe14));
3805       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3806       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3807                                 getF32Constant(DAG, 0x3f317234));
3808       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3809       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3810                                 getF32Constant(DAG, 0x3f800000));
3811       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3812       SDValue TwoToFractionalPartOfX =
3813         DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3814
3815       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3816                            MVT::f32, TwoToFractionalPartOfX);
3817     }
3818   } else {
3819     // No special expansion.
3820     result = DAG.getNode(ISD::FPOW, dl,
3821                          getValue(I.getOperand(1)).getValueType(),
3822                          getValue(I.getOperand(1)),
3823                          getValue(I.getOperand(2)));
3824   }
3825
3826   setValue(&I, result);
3827 }
3828
3829 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
3830 /// we want to emit this as a call to a named external function, return the name
3831 /// otherwise lower it and return null.
3832 const char *
3833 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3834   DebugLoc dl = getCurDebugLoc();
3835   switch (Intrinsic) {
3836   default:
3837     // By default, turn this into a target intrinsic node.
3838     visitTargetIntrinsic(I, Intrinsic);
3839     return 0;
3840   case Intrinsic::vastart:  visitVAStart(I); return 0;
3841   case Intrinsic::vaend:    visitVAEnd(I); return 0;
3842   case Intrinsic::vacopy:   visitVACopy(I); return 0;
3843   case Intrinsic::returnaddress:
3844     setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3845                              getValue(I.getOperand(1))));
3846     return 0;
3847   case Intrinsic::frameaddress:
3848     setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3849                              getValue(I.getOperand(1))));
3850     return 0;
3851   case Intrinsic::setjmp:
3852     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3853     break;
3854   case Intrinsic::longjmp:
3855     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3856     break;
3857   case Intrinsic::memcpy: {
3858     SDValue Op1 = getValue(I.getOperand(1));
3859     SDValue Op2 = getValue(I.getOperand(2));
3860     SDValue Op3 = getValue(I.getOperand(3));
3861     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3862     DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3863                               I.getOperand(1), 0, I.getOperand(2), 0));
3864     return 0;
3865   }
3866   case Intrinsic::memset: {
3867     SDValue Op1 = getValue(I.getOperand(1));
3868     SDValue Op2 = getValue(I.getOperand(2));
3869     SDValue Op3 = getValue(I.getOperand(3));
3870     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3871     DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3872                               I.getOperand(1), 0));
3873     return 0;
3874   }
3875   case Intrinsic::memmove: {
3876     SDValue Op1 = getValue(I.getOperand(1));
3877     SDValue Op2 = getValue(I.getOperand(2));
3878     SDValue Op3 = getValue(I.getOperand(3));
3879     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3880
3881     // If the source and destination are known to not be aliases, we can
3882     // lower memmove as memcpy.
3883     uint64_t Size = -1ULL;
3884     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3885       Size = C->getZExtValue();
3886     if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3887         AliasAnalysis::NoAlias) {
3888       DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3889                                 I.getOperand(1), 0, I.getOperand(2), 0));
3890       return 0;
3891     }
3892
3893     DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3894                                I.getOperand(1), 0, I.getOperand(2), 0));
3895     return 0;
3896   }
3897   case Intrinsic::dbg_stoppoint: {
3898     DwarfWriter *DW = DAG.getDwarfWriter();
3899     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3900     if (DW && DW->ValidDebugInfo(SPI.getContext())) {
3901       MachineFunction &MF = DAG.getMachineFunction();
3902       DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3903                                       SPI.getLine(),
3904                                       SPI.getColumn(),
3905                                       SPI.getContext()));
3906       DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
3907       std::string Dir, FN;
3908       unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
3909                                                  CU.getFilename(FN));
3910       unsigned idx = MF.getOrCreateDebugLocID(SrcFile,
3911                                               SPI.getLine(), SPI.getColumn());
3912       setCurDebugLoc(DebugLoc::get(idx));
3913     }
3914     return 0;
3915   }
3916   case Intrinsic::dbg_region_start: {
3917     DwarfWriter *DW = DAG.getDwarfWriter();
3918     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3919     if (DW && DW->ValidDebugInfo(RSI.getContext())) {
3920       unsigned LabelID =
3921         DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
3922       if (Fast)
3923         DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3924                                  getRoot(), LabelID));
3925     }
3926
3927     return 0;
3928   }
3929   case Intrinsic::dbg_region_end: {
3930     DwarfWriter *DW = DAG.getDwarfWriter();
3931     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3932     if (DW && DW->ValidDebugInfo(REI.getContext())) {
3933       unsigned LabelID =
3934         DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3935       if (Fast)
3936         DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3937                                  getRoot(), LabelID));
3938     }
3939
3940     return 0;
3941   }
3942   case Intrinsic::dbg_func_start: {
3943     DwarfWriter *DW = DAG.getDwarfWriter();
3944     if (!DW) return 0;
3945     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3946     Value *SP = FSI.getSubprogram();
3947     if (SP && DW->ValidDebugInfo(SP)) {
3948       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3949       // what (most?) gdb expects.
3950       MachineFunction &MF = DAG.getMachineFunction();
3951       DISubprogram Subprogram(cast<GlobalVariable>(SP));
3952       DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3953       std::string Dir, FN;
3954       unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
3955                                                  CompileUnit.getFilename(FN));
3956
3957       // Record the source line but does not create a label for the normal
3958       // function start. It will be emitted at asm emission time. However,
3959       // create a label if this is a beginning of inlined function.
3960       unsigned Line = Subprogram.getLineNumber();
3961
3962       if (Fast) {
3963         unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
3964         if (DW->getRecordSourceLineCount() != 1)
3965           DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3966                                    getRoot(), LabelID));
3967       }
3968
3969       setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
3970     }
3971
3972     return 0;
3973   }
3974   case Intrinsic::dbg_declare: {
3975     if (Fast) {
3976       DwarfWriter *DW = DAG.getDwarfWriter();
3977       DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3978       Value *Variable = DI.getVariable();
3979       if (DW && DW->ValidDebugInfo(Variable))
3980         DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
3981                                 getValue(DI.getAddress()), getValue(Variable)));
3982     } else {
3983       // FIXME: Do something sensible here when we support debug declare.
3984     }
3985     return 0;
3986   }
3987   case Intrinsic::eh_exception: {
3988     if (!CurMBB->isLandingPad()) {
3989       // FIXME: Mark exception register as live in.  Hack for PR1508.
3990       unsigned Reg = TLI.getExceptionAddressRegister();
3991       if (Reg) CurMBB->addLiveIn(Reg);
3992     }
3993     // Insert the EXCEPTIONADDR instruction.
3994     SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3995     SDValue Ops[1];
3996     Ops[0] = DAG.getRoot();
3997     SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3998     setValue(&I, Op);
3999     DAG.setRoot(Op.getValue(1));
4000     return 0;
4001   }
4002
4003   case Intrinsic::eh_selector_i32:
4004   case Intrinsic::eh_selector_i64: {
4005     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4006     MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4007                          MVT::i32 : MVT::i64);
4008
4009     if (MMI) {
4010       if (CurMBB->isLandingPad())
4011         AddCatchInfo(I, MMI, CurMBB);
4012       else {
4013 #ifndef NDEBUG
4014         FuncInfo.CatchInfoLost.insert(&I);
4015 #endif
4016         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
4017         unsigned Reg = TLI.getExceptionSelectorRegister();
4018         if (Reg) CurMBB->addLiveIn(Reg);
4019       }
4020
4021       // Insert the EHSELECTION instruction.
4022       SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4023       SDValue Ops[2];
4024       Ops[0] = getValue(I.getOperand(1));
4025       Ops[1] = getRoot();
4026       SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4027       setValue(&I, Op);
4028       DAG.setRoot(Op.getValue(1));
4029     } else {
4030       setValue(&I, DAG.getConstant(0, VT));
4031     }
4032
4033     return 0;
4034   }
4035
4036   case Intrinsic::eh_typeid_for_i32:
4037   case Intrinsic::eh_typeid_for_i64: {
4038     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4039     MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4040                          MVT::i32 : MVT::i64);
4041
4042     if (MMI) {
4043       // Find the type id for the given typeinfo.
4044       GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4045
4046       unsigned TypeID = MMI->getTypeIDFor(GV);
4047       setValue(&I, DAG.getConstant(TypeID, VT));
4048     } else {
4049       // Return something different to eh_selector.
4050       setValue(&I, DAG.getConstant(1, VT));
4051     }
4052
4053     return 0;
4054   }
4055
4056   case Intrinsic::eh_return_i32:
4057   case Intrinsic::eh_return_i64:
4058     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4059       MMI->setCallsEHReturn(true);
4060       DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4061                               MVT::Other,
4062                               getControlRoot(),
4063                               getValue(I.getOperand(1)),
4064                               getValue(I.getOperand(2))));
4065     } else {
4066       setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4067     }
4068
4069     return 0;
4070   case Intrinsic::eh_unwind_init:
4071     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4072       MMI->setCallsUnwindInit(true);
4073     }
4074
4075     return 0;
4076
4077   case Intrinsic::eh_dwarf_cfa: {
4078     MVT VT = getValue(I.getOperand(1)).getValueType();
4079     SDValue CfaArg;
4080     if (VT.bitsGT(TLI.getPointerTy()))
4081       CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
4082                            TLI.getPointerTy(), getValue(I.getOperand(1)));
4083     else
4084       CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
4085                            TLI.getPointerTy(), getValue(I.getOperand(1)));
4086
4087     SDValue Offset = DAG.getNode(ISD::ADD, dl,
4088                                  TLI.getPointerTy(),
4089                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4090                                              TLI.getPointerTy()),
4091                                  CfaArg);
4092     setValue(&I, DAG.getNode(ISD::ADD, dl,
4093                              TLI.getPointerTy(),
4094                              DAG.getNode(ISD::FRAMEADDR, dl,
4095                                          TLI.getPointerTy(),
4096                                          DAG.getConstant(0,
4097                                                          TLI.getPointerTy())),
4098                              Offset));
4099     return 0;
4100   }
4101
4102   case Intrinsic::convertff:
4103   case Intrinsic::convertfsi:
4104   case Intrinsic::convertfui:
4105   case Intrinsic::convertsif:
4106   case Intrinsic::convertuif:
4107   case Intrinsic::convertss:
4108   case Intrinsic::convertsu:
4109   case Intrinsic::convertus:
4110   case Intrinsic::convertuu: {
4111     ISD::CvtCode Code = ISD::CVT_INVALID;
4112     switch (Intrinsic) {
4113     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
4114     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4115     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4116     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4117     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4118     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
4119     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
4120     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
4121     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
4122     }
4123     MVT DestVT = TLI.getValueType(I.getType());
4124     Value* Op1 = I.getOperand(1);
4125     setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4126                                 DAG.getValueType(DestVT),
4127                                 DAG.getValueType(getValue(Op1).getValueType()),
4128                                 getValue(I.getOperand(2)),
4129                                 getValue(I.getOperand(3)),
4130                                 Code));
4131     return 0;
4132   }
4133
4134   case Intrinsic::sqrt:
4135     setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4136                              getValue(I.getOperand(1)).getValueType(),
4137                              getValue(I.getOperand(1))));
4138     return 0;
4139   case Intrinsic::powi:
4140     setValue(&I, DAG.getNode(ISD::FPOWI, dl,
4141                              getValue(I.getOperand(1)).getValueType(),
4142                              getValue(I.getOperand(1)),
4143                              getValue(I.getOperand(2))));
4144     return 0;
4145   case Intrinsic::sin:
4146     setValue(&I, DAG.getNode(ISD::FSIN, dl,
4147                              getValue(I.getOperand(1)).getValueType(),
4148                              getValue(I.getOperand(1))));
4149     return 0;
4150   case Intrinsic::cos:
4151     setValue(&I, DAG.getNode(ISD::FCOS, dl,
4152                              getValue(I.getOperand(1)).getValueType(),
4153                              getValue(I.getOperand(1))));
4154     return 0;
4155   case Intrinsic::log:
4156     visitLog(I);
4157     return 0;
4158   case Intrinsic::log2:
4159     visitLog2(I);
4160     return 0;
4161   case Intrinsic::log10:
4162     visitLog10(I);
4163     return 0;
4164   case Intrinsic::exp:
4165     visitExp(I);
4166     return 0;
4167   case Intrinsic::exp2:
4168     visitExp2(I);
4169     return 0;
4170   case Intrinsic::pow:
4171     visitPow(I);
4172     return 0;
4173   case Intrinsic::pcmarker: {
4174     SDValue Tmp = getValue(I.getOperand(1));
4175     DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4176     return 0;
4177   }
4178   case Intrinsic::readcyclecounter: {
4179     SDValue Op = getRoot();
4180     SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4181                                 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4182                                 &Op, 1);
4183     setValue(&I, Tmp);
4184     DAG.setRoot(Tmp.getValue(1));
4185     return 0;
4186   }
4187   case Intrinsic::part_select: {
4188     // Currently not implemented: just abort
4189     assert(0 && "part_select intrinsic not implemented");
4190     abort();
4191   }
4192   case Intrinsic::part_set: {
4193     // Currently not implemented: just abort
4194     assert(0 && "part_set intrinsic not implemented");
4195     abort();
4196   }
4197   case Intrinsic::bswap:
4198     setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4199                              getValue(I.getOperand(1)).getValueType(),
4200                              getValue(I.getOperand(1))));
4201     return 0;
4202   case Intrinsic::cttz: {
4203     SDValue Arg = getValue(I.getOperand(1));
4204     MVT Ty = Arg.getValueType();
4205     SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4206     setValue(&I, result);
4207     return 0;
4208   }
4209   case Intrinsic::ctlz: {
4210     SDValue Arg = getValue(I.getOperand(1));
4211     MVT Ty = Arg.getValueType();
4212     SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4213     setValue(&I, result);
4214     return 0;
4215   }
4216   case Intrinsic::ctpop: {
4217     SDValue Arg = getValue(I.getOperand(1));
4218     MVT Ty = Arg.getValueType();
4219     SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4220     setValue(&I, result);
4221     return 0;
4222   }
4223   case Intrinsic::stacksave: {
4224     SDValue Op = getRoot();
4225     SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
4226               DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4227     setValue(&I, Tmp);
4228     DAG.setRoot(Tmp.getValue(1));
4229     return 0;
4230   }
4231   case Intrinsic::stackrestore: {
4232     SDValue Tmp = getValue(I.getOperand(1));
4233     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
4234     return 0;
4235   }
4236   case Intrinsic::stackprotector: {
4237     // Emit code into the DAG to store the stack guard onto the stack.
4238     MachineFunction &MF = DAG.getMachineFunction();
4239     MachineFrameInfo *MFI = MF.getFrameInfo();
4240     MVT PtrTy = TLI.getPointerTy();
4241
4242     SDValue Src = getValue(I.getOperand(1));   // The guard's value.
4243     AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4244
4245     int FI = FuncInfo.StaticAllocaMap[Slot];
4246     MFI->setStackProtectorIndex(FI);
4247
4248     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4249
4250     // Store the stack protector onto the stack.
4251     SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4252                                   PseudoSourceValue::getFixedStack(FI),
4253                                   0, true);
4254     setValue(&I, Result);
4255     DAG.setRoot(Result);
4256     return 0;
4257   }
4258   case Intrinsic::var_annotation:
4259     // Discard annotate attributes
4260     return 0;
4261
4262   case Intrinsic::init_trampoline: {
4263     const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4264
4265     SDValue Ops[6];
4266     Ops[0] = getRoot();
4267     Ops[1] = getValue(I.getOperand(1));
4268     Ops[2] = getValue(I.getOperand(2));
4269     Ops[3] = getValue(I.getOperand(3));
4270     Ops[4] = DAG.getSrcValue(I.getOperand(1));
4271     Ops[5] = DAG.getSrcValue(F);
4272
4273     SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
4274                                 DAG.getNodeValueTypes(TLI.getPointerTy(),
4275                                                       MVT::Other), 2,
4276                                 Ops, 6);
4277
4278     setValue(&I, Tmp);
4279     DAG.setRoot(Tmp.getValue(1));
4280     return 0;
4281   }
4282
4283   case Intrinsic::gcroot:
4284     if (GFI) {
4285       Value *Alloca = I.getOperand(1);
4286       Constant *TypeMap = cast<Constant>(I.getOperand(2));
4287
4288       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4289       GFI->addStackRoot(FI->getIndex(), TypeMap);
4290     }
4291     return 0;
4292
4293   case Intrinsic::gcread:
4294   case Intrinsic::gcwrite:
4295     assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4296     return 0;
4297
4298   case Intrinsic::flt_rounds: {
4299     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4300     return 0;
4301   }
4302
4303   case Intrinsic::trap: {
4304     DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4305     return 0;
4306   }
4307
4308   case Intrinsic::uadd_with_overflow:
4309     return implVisitAluOverflow(I, ISD::UADDO);
4310   case Intrinsic::sadd_with_overflow:
4311     return implVisitAluOverflow(I, ISD::SADDO);
4312   case Intrinsic::usub_with_overflow:
4313     return implVisitAluOverflow(I, ISD::USUBO);
4314   case Intrinsic::ssub_with_overflow:
4315     return implVisitAluOverflow(I, ISD::SSUBO);
4316   case Intrinsic::umul_with_overflow:
4317     return implVisitAluOverflow(I, ISD::UMULO);
4318   case Intrinsic::smul_with_overflow:
4319     return implVisitAluOverflow(I, ISD::SMULO);
4320
4321   case Intrinsic::prefetch: {
4322     SDValue Ops[4];
4323     Ops[0] = getRoot();
4324     Ops[1] = getValue(I.getOperand(1));
4325     Ops[2] = getValue(I.getOperand(2));
4326     Ops[3] = getValue(I.getOperand(3));
4327     DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4328     return 0;
4329   }
4330
4331   case Intrinsic::memory_barrier: {
4332     SDValue Ops[6];
4333     Ops[0] = getRoot();
4334     for (int x = 1; x < 6; ++x)
4335       Ops[x] = getValue(I.getOperand(x));
4336
4337     DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4338     return 0;
4339   }
4340   case Intrinsic::atomic_cmp_swap: {
4341     SDValue Root = getRoot();
4342     SDValue L =
4343       DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4344                     getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4345                     Root,
4346                     getValue(I.getOperand(1)),
4347                     getValue(I.getOperand(2)),
4348                     getValue(I.getOperand(3)),
4349                     I.getOperand(1));
4350     setValue(&I, L);
4351     DAG.setRoot(L.getValue(1));
4352     return 0;
4353   }
4354   case Intrinsic::atomic_load_add:
4355     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4356   case Intrinsic::atomic_load_sub:
4357     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4358   case Intrinsic::atomic_load_or:
4359     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4360   case Intrinsic::atomic_load_xor:
4361     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4362   case Intrinsic::atomic_load_and:
4363     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4364   case Intrinsic::atomic_load_nand:
4365     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4366   case Intrinsic::atomic_load_max:
4367     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4368   case Intrinsic::atomic_load_min:
4369     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4370   case Intrinsic::atomic_load_umin:
4371     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4372   case Intrinsic::atomic_load_umax:
4373     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4374   case Intrinsic::atomic_swap:
4375     return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4376   }
4377 }
4378
4379
4380 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4381                                        bool IsTailCall,
4382                                        MachineBasicBlock *LandingPad) {
4383   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4384   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4385   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4386   unsigned BeginLabel = 0, EndLabel = 0;
4387
4388   TargetLowering::ArgListTy Args;
4389   TargetLowering::ArgListEntry Entry;
4390   Args.reserve(CS.arg_size());
4391   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4392        i != e; ++i) {
4393     SDValue ArgNode = getValue(*i);
4394     Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4395
4396     unsigned attrInd = i - CS.arg_begin() + 1;
4397     Entry.isSExt  = CS.paramHasAttr(attrInd, Attribute::SExt);
4398     Entry.isZExt  = CS.paramHasAttr(attrInd, Attribute::ZExt);
4399     Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4400     Entry.isSRet  = CS.paramHasAttr(attrInd, Attribute::StructRet);
4401     Entry.isNest  = CS.paramHasAttr(attrInd, Attribute::Nest);
4402     Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4403     Entry.Alignment = CS.getParamAlignment(attrInd);
4404     Args.push_back(Entry);
4405   }
4406
4407   if (LandingPad && MMI) {
4408     // Insert a label before the invoke call to mark the try range.  This can be
4409     // used to detect deletion of the invoke via the MachineModuleInfo.
4410     BeginLabel = MMI->NextLabelID();
4411     // Both PendingLoads and PendingExports must be flushed here;
4412     // this call might not return.
4413     (void)getRoot();
4414     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4415                              getControlRoot(), BeginLabel));
4416   }
4417
4418   std::pair<SDValue,SDValue> Result =
4419     TLI.LowerCallTo(getRoot(), CS.getType(),
4420                     CS.paramHasAttr(0, Attribute::SExt),
4421                     CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4422                     CS.paramHasAttr(0, Attribute::InReg),
4423                     CS.getCallingConv(),
4424                     IsTailCall && PerformTailCallOpt,
4425                     Callee, Args, DAG, getCurDebugLoc());
4426   if (CS.getType() != Type::VoidTy)
4427     setValue(CS.getInstruction(), Result.first);
4428   DAG.setRoot(Result.second);
4429
4430   if (LandingPad && MMI) {
4431     // Insert a label at the end of the invoke call to mark the try range.  This
4432     // can be used to detect deletion of the invoke via the MachineModuleInfo.
4433     EndLabel = MMI->NextLabelID();
4434     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4435                              getRoot(), EndLabel));
4436
4437     // Inform MachineModuleInfo of range.
4438     MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4439   }
4440 }
4441
4442
4443 void SelectionDAGLowering::visitCall(CallInst &I) {
4444   const char *RenameFn = 0;
4445   if (Function *F = I.getCalledFunction()) {
4446     if (F->isDeclaration()) {
4447       const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4448       if (II) {
4449         if (unsigned IID = II->getIntrinsicID(F)) {
4450           RenameFn = visitIntrinsicCall(I, IID);
4451           if (!RenameFn)
4452             return;
4453         }
4454       }
4455       if (unsigned IID = F->getIntrinsicID()) {
4456         RenameFn = visitIntrinsicCall(I, IID);
4457         if (!RenameFn)
4458           return;
4459       }
4460     }
4461
4462     // Check for well-known libc/libm calls.  If the function is internal, it
4463     // can't be a library call.
4464     unsigned NameLen = F->getNameLen();
4465     if (!F->hasLocalLinkage() && NameLen) {
4466       const char *NameStr = F->getNameStart();
4467       if (NameStr[0] == 'c' &&
4468           ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4469            (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4470         if (I.getNumOperands() == 3 &&   // Basic sanity checks.
4471             I.getOperand(1)->getType()->isFloatingPoint() &&
4472             I.getType() == I.getOperand(1)->getType() &&
4473             I.getType() == I.getOperand(2)->getType()) {
4474           SDValue LHS = getValue(I.getOperand(1));
4475           SDValue RHS = getValue(I.getOperand(2));
4476           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4477                                    LHS.getValueType(), LHS, RHS));
4478           return;
4479         }
4480       } else if (NameStr[0] == 'f' &&
4481                  ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4482                   (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4483                   (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4484         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4485             I.getOperand(1)->getType()->isFloatingPoint() &&
4486             I.getType() == I.getOperand(1)->getType()) {
4487           SDValue Tmp = getValue(I.getOperand(1));
4488           setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4489                                    Tmp.getValueType(), Tmp));
4490           return;
4491         }
4492       } else if (NameStr[0] == 's' &&
4493                  ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4494                   (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4495                   (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4496         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4497             I.getOperand(1)->getType()->isFloatingPoint() &&
4498             I.getType() == I.getOperand(1)->getType()) {
4499           SDValue Tmp = getValue(I.getOperand(1));
4500           setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4501                                    Tmp.getValueType(), Tmp));
4502           return;
4503         }
4504       } else if (NameStr[0] == 'c' &&
4505                  ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4506                   (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4507                   (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4508         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4509             I.getOperand(1)->getType()->isFloatingPoint() &&
4510             I.getType() == I.getOperand(1)->getType()) {
4511           SDValue Tmp = getValue(I.getOperand(1));
4512           setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4513                                    Tmp.getValueType(), Tmp));
4514           return;
4515         }
4516       }
4517     }
4518   } else if (isa<InlineAsm>(I.getOperand(0))) {
4519     visitInlineAsm(&I);
4520     return;
4521   }
4522
4523   SDValue Callee;
4524   if (!RenameFn)
4525     Callee = getValue(I.getOperand(0));
4526   else
4527     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4528
4529   LowerCallTo(&I, Callee, I.isTailCall());
4530 }
4531
4532
4533 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4534 /// this value and returns the result as a ValueVT value.  This uses
4535 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4536 /// If the Flag pointer is NULL, no flag is used.
4537 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4538                                       SDValue &Chain,
4539                                       SDValue *Flag) const {
4540   // Assemble the legal parts into the final values.
4541   SmallVector<SDValue, 4> Values(ValueVTs.size());
4542   SmallVector<SDValue, 8> Parts;
4543   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4544     // Copy the legal parts from the registers.
4545     MVT ValueVT = ValueVTs[Value];
4546     unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4547     MVT RegisterVT = RegVTs[Value];
4548
4549     Parts.resize(NumRegs);
4550     for (unsigned i = 0; i != NumRegs; ++i) {
4551       SDValue P;
4552       if (Flag == 0)
4553         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4554       else {
4555         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4556         *Flag = P.getValue(2);
4557       }
4558       Chain = P.getValue(1);
4559
4560       // If the source register was virtual and if we know something about it,
4561       // add an assert node.
4562       if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4563           RegisterVT.isInteger() && !RegisterVT.isVector()) {
4564         unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4565         FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4566         if (FLI.LiveOutRegInfo.size() > SlotNo) {
4567           FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4568
4569           unsigned RegSize = RegisterVT.getSizeInBits();
4570           unsigned NumSignBits = LOI.NumSignBits;
4571           unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4572
4573           // FIXME: We capture more information than the dag can represent.  For
4574           // now, just use the tightest assertzext/assertsext possible.
4575           bool isSExt = true;
4576           MVT FromVT(MVT::Other);
4577           if (NumSignBits == RegSize)
4578             isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
4579           else if (NumZeroBits >= RegSize-1)
4580             isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
4581           else if (NumSignBits > RegSize-8)
4582             isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
4583           else if (NumZeroBits >= RegSize-9)
4584             isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
4585           else if (NumSignBits > RegSize-16)
4586             isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
4587           else if (NumZeroBits >= RegSize-17)
4588             isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4589           else if (NumSignBits > RegSize-32)
4590             isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
4591           else if (NumZeroBits >= RegSize-33)
4592             isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4593
4594           if (FromVT != MVT::Other) {
4595             P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4596                             RegisterVT, P, DAG.getValueType(FromVT));
4597
4598           }
4599         }
4600       }
4601
4602       Parts[i] = P;
4603     }
4604
4605     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4606                                      NumRegs, RegisterVT, ValueVT);
4607     Part += NumRegs;
4608     Parts.clear();
4609   }
4610
4611   return DAG.getNode(ISD::MERGE_VALUES, dl,
4612                      DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4613                      &Values[0], ValueVTs.size());
4614 }
4615
4616 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4617 /// specified value into the registers specified by this object.  This uses
4618 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4619 /// If the Flag pointer is NULL, no flag is used.
4620 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4621                                  SDValue &Chain, SDValue *Flag) const {
4622   // Get the list of the values's legal parts.
4623   unsigned NumRegs = Regs.size();
4624   SmallVector<SDValue, 8> Parts(NumRegs);
4625   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4626     MVT ValueVT = ValueVTs[Value];
4627     unsigned NumParts = TLI->getNumRegisters(ValueVT);
4628     MVT RegisterVT = RegVTs[Value];
4629
4630     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
4631                    &Parts[Part], NumParts, RegisterVT);
4632     Part += NumParts;
4633   }
4634
4635   // Copy the parts into the registers.
4636   SmallVector<SDValue, 8> Chains(NumRegs);
4637   for (unsigned i = 0; i != NumRegs; ++i) {
4638     SDValue Part;
4639     if (Flag == 0)
4640       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4641     else {
4642       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4643       *Flag = Part.getValue(1);
4644     }
4645     Chains[i] = Part.getValue(0);
4646   }
4647
4648   if (NumRegs == 1 || Flag)
4649     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4650     // flagged to it. That is the CopyToReg nodes and the user are considered
4651     // a single scheduling unit. If we create a TokenFactor and return it as
4652     // chain, then the TokenFactor is both a predecessor (operand) of the
4653     // user as well as a successor (the TF operands are flagged to the user).
4654     // c1, f1 = CopyToReg
4655     // c2, f2 = CopyToReg
4656     // c3     = TokenFactor c1, c2
4657     // ...
4658     //        = op c3, ..., f2
4659     Chain = Chains[NumRegs-1];
4660   else
4661     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4662 }
4663
4664 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4665 /// operand list.  This adds the code marker and includes the number of
4666 /// values added into it.
4667 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4668                                         std::vector<SDValue> &Ops) const {
4669   MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4670   Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4671   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4672     unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4673     MVT RegisterVT = RegVTs[Value];
4674     for (unsigned i = 0; i != NumRegs; ++i) {
4675       assert(Reg < Regs.size() && "Mismatch in # registers expected");
4676       Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4677     }
4678   }
4679 }
4680
4681 /// isAllocatableRegister - If the specified register is safe to allocate,
4682 /// i.e. it isn't a stack pointer or some other special register, return the
4683 /// register class for the register.  Otherwise, return null.
4684 static const TargetRegisterClass *
4685 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4686                       const TargetLowering &TLI,
4687                       const TargetRegisterInfo *TRI) {
4688   MVT FoundVT = MVT::Other;
4689   const TargetRegisterClass *FoundRC = 0;
4690   for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4691        E = TRI->regclass_end(); RCI != E; ++RCI) {
4692     MVT ThisVT = MVT::Other;
4693
4694     const TargetRegisterClass *RC = *RCI;
4695     // If none of the the value types for this register class are valid, we
4696     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4697     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4698          I != E; ++I) {
4699       if (TLI.isTypeLegal(*I)) {
4700         // If we have already found this register in a different register class,
4701         // choose the one with the largest VT specified.  For example, on
4702         // PowerPC, we favor f64 register classes over f32.
4703         if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4704           ThisVT = *I;
4705           break;
4706         }
4707       }
4708     }
4709
4710     if (ThisVT == MVT::Other) continue;
4711
4712     // NOTE: This isn't ideal.  In particular, this might allocate the
4713     // frame pointer in functions that need it (due to them not being taken
4714     // out of allocation, because a variable sized allocation hasn't been seen
4715     // yet).  This is a slight code pessimization, but should still work.
4716     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4717          E = RC->allocation_order_end(MF); I != E; ++I)
4718       if (*I == Reg) {
4719         // We found a matching register class.  Keep looking at others in case
4720         // we find one with larger registers that this physreg is also in.
4721         FoundRC = RC;
4722         FoundVT = ThisVT;
4723         break;
4724       }
4725   }
4726   return FoundRC;
4727 }
4728
4729
4730 namespace llvm {
4731 /// AsmOperandInfo - This contains information for each constraint that we are
4732 /// lowering.
4733 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4734     public TargetLowering::AsmOperandInfo {
4735 public:
4736   /// CallOperand - If this is the result output operand or a clobber
4737   /// this is null, otherwise it is the incoming operand to the CallInst.
4738   /// This gets modified as the asm is processed.
4739   SDValue CallOperand;
4740
4741   /// AssignedRegs - If this is a register or register class operand, this
4742   /// contains the set of register corresponding to the operand.
4743   RegsForValue AssignedRegs;
4744
4745   explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4746     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4747   }
4748
4749   /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4750   /// busy in OutputRegs/InputRegs.
4751   void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4752                          std::set<unsigned> &OutputRegs,
4753                          std::set<unsigned> &InputRegs,
4754                          const TargetRegisterInfo &TRI) const {
4755     if (isOutReg) {
4756       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4757         MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4758     }
4759     if (isInReg) {
4760       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4761         MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4762     }
4763   }
4764
4765   /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4766   /// corresponds to.  If there is no Value* for this operand, it returns
4767   /// MVT::Other.
4768   MVT getCallOperandValMVT(const TargetLowering &TLI,
4769                            const TargetData *TD) const {
4770     if (CallOperandVal == 0) return MVT::Other;
4771
4772     if (isa<BasicBlock>(CallOperandVal))
4773       return TLI.getPointerTy();
4774
4775     const llvm::Type *OpTy = CallOperandVal->getType();
4776
4777     // If this is an indirect operand, the operand is a pointer to the
4778     // accessed type.
4779     if (isIndirect)
4780       OpTy = cast<PointerType>(OpTy)->getElementType();
4781
4782     // If OpTy is not a single value, it may be a struct/union that we
4783     // can tile with integers.
4784     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4785       unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4786       switch (BitSize) {
4787       default: break;
4788       case 1:
4789       case 8:
4790       case 16:
4791       case 32:
4792       case 64:
4793       case 128:
4794         OpTy = IntegerType::get(BitSize);
4795         break;
4796       }
4797     }
4798
4799     return TLI.getValueType(OpTy, true);
4800   }
4801
4802 private:
4803   /// MarkRegAndAliases - Mark the specified register and all aliases in the
4804   /// specified set.
4805   static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4806                                 const TargetRegisterInfo &TRI) {
4807     assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4808     Regs.insert(Reg);
4809     if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4810       for (; *Aliases; ++Aliases)
4811         Regs.insert(*Aliases);
4812   }
4813 };
4814 } // end llvm namespace.
4815
4816
4817 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4818 /// specified operand.  We prefer to assign virtual registers, to allow the
4819 /// register allocator handle the assignment process.  However, if the asm uses
4820 /// features that we can't model on machineinstrs, we have SDISel do the
4821 /// allocation.  This produces generally horrible, but correct, code.
4822 ///
4823 ///   OpInfo describes the operand.
4824 ///   Input and OutputRegs are the set of already allocated physical registers.
4825 ///
4826 void SelectionDAGLowering::
4827 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4828                      std::set<unsigned> &OutputRegs,
4829                      std::set<unsigned> &InputRegs) {
4830   // Compute whether this value requires an input register, an output register,
4831   // or both.
4832   bool isOutReg = false;
4833   bool isInReg = false;
4834   switch (OpInfo.Type) {
4835   case InlineAsm::isOutput:
4836     isOutReg = true;
4837
4838     // If there is an input constraint that matches this, we need to reserve
4839     // the input register so no other inputs allocate to it.
4840     isInReg = OpInfo.hasMatchingInput();
4841     break;
4842   case InlineAsm::isInput:
4843     isInReg = true;
4844     isOutReg = false;
4845     break;
4846   case InlineAsm::isClobber:
4847     isOutReg = true;
4848     isInReg = true;
4849     break;
4850   }
4851
4852
4853   MachineFunction &MF = DAG.getMachineFunction();
4854   SmallVector<unsigned, 4> Regs;
4855
4856   // If this is a constraint for a single physreg, or a constraint for a
4857   // register class, find it.
4858   std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4859     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4860                                      OpInfo.ConstraintVT);
4861
4862   unsigned NumRegs = 1;
4863   if (OpInfo.ConstraintVT != MVT::Other) {
4864     // If this is a FP input in an integer register (or visa versa) insert a bit
4865     // cast of the input value.  More generally, handle any case where the input
4866     // value disagrees with the register class we plan to stick this in.
4867     if (OpInfo.Type == InlineAsm::isInput &&
4868         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4869       // Try to convert to the first MVT that the reg class contains.  If the
4870       // types are identical size, use a bitcast to convert (e.g. two differing
4871       // vector types).
4872       MVT RegVT = *PhysReg.second->vt_begin();
4873       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4874         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4875                                          RegVT, OpInfo.CallOperand);
4876         OpInfo.ConstraintVT = RegVT;
4877       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4878         // If the input is a FP value and we want it in FP registers, do a
4879         // bitcast to the corresponding integer type.  This turns an f64 value
4880         // into i64, which can be passed with two i32 values on a 32-bit
4881         // machine.
4882         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4883         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4884                                          RegVT, OpInfo.CallOperand);
4885         OpInfo.ConstraintVT = RegVT;
4886       }
4887     }
4888
4889     NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4890   }
4891
4892   MVT RegVT;
4893   MVT ValueVT = OpInfo.ConstraintVT;
4894
4895   // If this is a constraint for a specific physical register, like {r17},
4896   // assign it now.
4897   if (PhysReg.first) {
4898     if (OpInfo.ConstraintVT == MVT::Other)
4899       ValueVT = *PhysReg.second->vt_begin();
4900
4901     // Get the actual register value type.  This is important, because the user
4902     // may have asked for (e.g.) the AX register in i32 type.  We need to
4903     // remember that AX is actually i16 to get the right extension.
4904     RegVT = *PhysReg.second->vt_begin();
4905
4906     // This is a explicit reference to a physical register.
4907     Regs.push_back(PhysReg.first);
4908
4909     // If this is an expanded reference, add the rest of the regs to Regs.
4910     if (NumRegs != 1) {
4911       TargetRegisterClass::iterator I = PhysReg.second->begin();
4912       for (; *I != PhysReg.first; ++I)
4913         assert(I != PhysReg.second->end() && "Didn't find reg!");
4914
4915       // Already added the first reg.
4916       --NumRegs; ++I;
4917       for (; NumRegs; --NumRegs, ++I) {
4918         assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4919         Regs.push_back(*I);
4920       }
4921     }
4922     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4923     const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4924     OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4925     return;
4926   }
4927
4928   // Otherwise, if this was a reference to an LLVM register class, create vregs
4929   // for this reference.
4930   std::vector<unsigned> RegClassRegs;
4931   const TargetRegisterClass *RC = PhysReg.second;
4932   if (RC) {
4933     // If this is a tied register, our regalloc doesn't know how to maintain
4934     // the constraint, so we have to pick a register to pin the input/output to.
4935     // If it isn't a matched constraint, go ahead and create vreg and let the
4936     // regalloc do its thing.
4937     if (!OpInfo.hasMatchingInput()) {
4938       RegVT = *PhysReg.second->vt_begin();
4939       if (OpInfo.ConstraintVT == MVT::Other)
4940         ValueVT = RegVT;
4941
4942       // Create the appropriate number of virtual registers.
4943       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4944       for (; NumRegs; --NumRegs)
4945         Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4946
4947       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4948       return;
4949     }
4950
4951     // Otherwise, we can't allocate it.  Let the code below figure out how to
4952     // maintain these constraints.
4953     RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4954
4955   } else {
4956     // This is a reference to a register class that doesn't directly correspond
4957     // to an LLVM register class.  Allocate NumRegs consecutive, available,
4958     // registers from the class.
4959     RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4960                                                          OpInfo.ConstraintVT);
4961   }
4962
4963   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4964   unsigned NumAllocated = 0;
4965   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4966     unsigned Reg = RegClassRegs[i];
4967     // See if this register is available.
4968     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
4969         (isInReg  && InputRegs.count(Reg))) {    // Already used.
4970       // Make sure we find consecutive registers.
4971       NumAllocated = 0;
4972       continue;
4973     }
4974
4975     // Check to see if this register is allocatable (i.e. don't give out the
4976     // stack pointer).
4977     if (RC == 0) {
4978       RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4979       if (!RC) {        // Couldn't allocate this register.
4980         // Reset NumAllocated to make sure we return consecutive registers.
4981         NumAllocated = 0;
4982         continue;
4983       }
4984     }
4985
4986     // Okay, this register is good, we can use it.
4987     ++NumAllocated;
4988
4989     // If we allocated enough consecutive registers, succeed.
4990     if (NumAllocated == NumRegs) {
4991       unsigned RegStart = (i-NumAllocated)+1;
4992       unsigned RegEnd   = i+1;
4993       // Mark all of the allocated registers used.
4994       for (unsigned i = RegStart; i != RegEnd; ++i)
4995         Regs.push_back(RegClassRegs[i]);
4996
4997       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4998                                          OpInfo.ConstraintVT);
4999       OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5000       return;
5001     }
5002   }
5003
5004   // Otherwise, we couldn't allocate enough registers for this.
5005 }
5006
5007 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5008 /// processed uses a memory 'm' constraint.
5009 static bool
5010 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5011                           const TargetLowering &TLI) {
5012   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5013     InlineAsm::ConstraintInfo &CI = CInfos[i];
5014     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5015       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5016       if (CType == TargetLowering::C_Memory)
5017         return true;
5018     }
5019   }
5020
5021   return false;
5022 }
5023
5024 /// visitInlineAsm - Handle a call to an InlineAsm object.
5025 ///
5026 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5027   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5028
5029   /// ConstraintOperands - Information about all of the constraints.
5030   std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5031
5032   SDValue Chain = getRoot();
5033   SDValue Flag;
5034
5035   std::set<unsigned> OutputRegs, InputRegs;
5036
5037   // Do a prepass over the constraints, canonicalizing them, and building up the
5038   // ConstraintOperands list.
5039   std::vector<InlineAsm::ConstraintInfo>
5040     ConstraintInfos = IA->ParseConstraints();
5041
5042   bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5043
5044   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
5045   unsigned ResNo = 0;   // ResNo - The result number of the next output.
5046   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5047     ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5048     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5049
5050     MVT OpVT = MVT::Other;
5051
5052     // Compute the value type for each operand.
5053     switch (OpInfo.Type) {
5054     case InlineAsm::isOutput:
5055       // Indirect outputs just consume an argument.
5056       if (OpInfo.isIndirect) {
5057         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5058         break;
5059       }
5060
5061       // The return value of the call is this value.  As such, there is no
5062       // corresponding argument.
5063       assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5064       if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5065         OpVT = TLI.getValueType(STy->getElementType(ResNo));
5066       } else {
5067         assert(ResNo == 0 && "Asm only has one result!");
5068         OpVT = TLI.getValueType(CS.getType());
5069       }
5070       ++ResNo;
5071       break;
5072     case InlineAsm::isInput:
5073       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5074       break;
5075     case InlineAsm::isClobber:
5076       // Nothing to do.
5077       break;
5078     }
5079
5080     // If this is an input or an indirect output, process the call argument.
5081     // BasicBlocks are labels, currently appearing only in asm's.
5082     if (OpInfo.CallOperandVal) {
5083       if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5084         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5085       } else {
5086         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5087       }
5088
5089       OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
5090     }
5091
5092     OpInfo.ConstraintVT = OpVT;
5093   }
5094
5095   // Second pass over the constraints: compute which constraint option to use
5096   // and assign registers to constraints that want a specific physreg.
5097   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5098     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5099
5100     // If this is an output operand with a matching input operand, look up the
5101     // matching input. If their types mismatch, e.g. one is an integer, the
5102     // other is floating point, or their sizes are different, flag it as an
5103     // error.
5104     if (OpInfo.hasMatchingInput()) {
5105       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5106       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5107         if ((OpInfo.ConstraintVT.isInteger() !=
5108              Input.ConstraintVT.isInteger()) ||
5109             (OpInfo.ConstraintVT.getSizeInBits() !=
5110              Input.ConstraintVT.getSizeInBits())) {
5111           cerr << "Unsupported asm: input constraint with a matching output "
5112                << "constraint of incompatible type!\n";
5113           exit(1);
5114         }
5115         Input.ConstraintVT = OpInfo.ConstraintVT;
5116       }
5117     }
5118
5119     // Compute the constraint code and ConstraintType to use.
5120     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5121
5122     // If this is a memory input, and if the operand is not indirect, do what we
5123     // need to to provide an address for the memory input.
5124     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5125         !OpInfo.isIndirect) {
5126       assert(OpInfo.Type == InlineAsm::isInput &&
5127              "Can only indirectify direct input operands!");
5128
5129       // Memory operands really want the address of the value.  If we don't have
5130       // an indirect input, put it in the constpool if we can, otherwise spill
5131       // it to a stack slot.
5132
5133       // If the operand is a float, integer, or vector constant, spill to a
5134       // constant pool entry to get its address.
5135       Value *OpVal = OpInfo.CallOperandVal;
5136       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5137           isa<ConstantVector>(OpVal)) {
5138         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5139                                                  TLI.getPointerTy());
5140       } else {
5141         // Otherwise, create a stack slot and emit a store to it before the
5142         // asm.
5143         const Type *Ty = OpVal->getType();
5144         uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
5145         unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5146         MachineFunction &MF = DAG.getMachineFunction();
5147         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5148         SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5149         Chain = DAG.getStore(Chain, getCurDebugLoc(),
5150                              OpInfo.CallOperand, StackSlot, NULL, 0);
5151         OpInfo.CallOperand = StackSlot;
5152       }
5153
5154       // There is no longer a Value* corresponding to this operand.
5155       OpInfo.CallOperandVal = 0;
5156       // It is now an indirect operand.
5157       OpInfo.isIndirect = true;
5158     }
5159
5160     // If this constraint is for a specific register, allocate it before
5161     // anything else.
5162     if (OpInfo.ConstraintType == TargetLowering::C_Register)
5163       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5164   }
5165   ConstraintInfos.clear();
5166
5167
5168   // Second pass - Loop over all of the operands, assigning virtual or physregs
5169   // to register class operands.
5170   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5171     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5172
5173     // C_Register operands have already been allocated, Other/Memory don't need
5174     // to be.
5175     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5176       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5177   }
5178
5179   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5180   std::vector<SDValue> AsmNodeOperands;
5181   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
5182   AsmNodeOperands.push_back(
5183           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5184
5185
5186   // Loop over all of the inputs, copying the operand values into the
5187   // appropriate registers and processing the output regs.
5188   RegsForValue RetValRegs;
5189
5190   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5191   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5192
5193   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5194     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5195
5196     switch (OpInfo.Type) {
5197     case InlineAsm::isOutput: {
5198       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5199           OpInfo.ConstraintType != TargetLowering::C_Register) {
5200         // Memory output, or 'other' output (e.g. 'X' constraint).
5201         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5202
5203         // Add information to the INLINEASM node to know about this output.
5204         unsigned ResOpType = 4/*MEM*/ | (1<<3);
5205         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5206                                                         TLI.getPointerTy()));
5207         AsmNodeOperands.push_back(OpInfo.CallOperand);
5208         break;
5209       }
5210
5211       // Otherwise, this is a register or register class output.
5212
5213       // Copy the output from the appropriate register.  Find a register that
5214       // we can use.
5215       if (OpInfo.AssignedRegs.Regs.empty()) {
5216         cerr << "Couldn't allocate output reg for constraint '"
5217              << OpInfo.ConstraintCode << "'!\n";
5218         exit(1);
5219       }
5220
5221       // If this is an indirect operand, store through the pointer after the
5222       // asm.
5223       if (OpInfo.isIndirect) {
5224         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5225                                                       OpInfo.CallOperandVal));
5226       } else {
5227         // This is the result value of the call.
5228         assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5229         // Concatenate this output onto the outputs list.
5230         RetValRegs.append(OpInfo.AssignedRegs);
5231       }
5232
5233       // Add information to the INLINEASM node to know that this register is
5234       // set.
5235       OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5236                                                6 /* EARLYCLOBBER REGDEF */ :
5237                                                2 /* REGDEF */ ,
5238                                                DAG, AsmNodeOperands);
5239       break;
5240     }
5241     case InlineAsm::isInput: {
5242       SDValue InOperandVal = OpInfo.CallOperand;
5243
5244       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
5245         // If this is required to match an output register we have already set,
5246         // just use its register.
5247         unsigned OperandNo = OpInfo.getMatchedOperand();
5248
5249         // Scan until we find the definition we already emitted of this operand.
5250         // When we find it, create a RegsForValue operand.
5251         unsigned CurOp = 2;  // The first operand.
5252         for (; OperandNo; --OperandNo) {
5253           // Advance to the next operand.
5254           unsigned NumOps =
5255             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5256           assert(((NumOps & 7) == 2 /*REGDEF*/ ||
5257                   (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5258                   (NumOps & 7) == 4 /*MEM*/) &&
5259                  "Skipped past definitions?");
5260           CurOp += (NumOps>>3)+1;
5261         }
5262
5263         unsigned NumOps =
5264           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5265         if ((NumOps & 7) == 2 /*REGDEF*/
5266             || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5267           // Add NumOps>>3 registers to MatchedRegs.
5268           RegsForValue MatchedRegs;
5269           MatchedRegs.TLI = &TLI;
5270           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5271           MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5272           for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5273             unsigned Reg =
5274               cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5275             MatchedRegs.Regs.push_back(Reg);
5276           }
5277
5278           // Use the produced MatchedRegs object to
5279           MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5280                                     Chain, &Flag);
5281           MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
5282           break;
5283         } else {
5284           assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
5285           assert((NumOps >> 3) == 1 && "Unexpected number of operands");
5286           // Add information to the INLINEASM node to know about this input.
5287           AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
5288                                                           TLI.getPointerTy()));
5289           AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5290           break;
5291         }
5292       }
5293
5294       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5295         assert(!OpInfo.isIndirect &&
5296                "Don't know how to handle indirect other inputs yet!");
5297
5298         std::vector<SDValue> Ops;
5299         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5300                                          hasMemory, Ops, DAG);
5301         if (Ops.empty()) {
5302           cerr << "Invalid operand for inline asm constraint '"
5303                << OpInfo.ConstraintCode << "'!\n";
5304           exit(1);
5305         }
5306
5307         // Add information to the INLINEASM node to know about this input.
5308         unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5309         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5310                                                         TLI.getPointerTy()));
5311         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5312         break;
5313       } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5314         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5315         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5316                "Memory operands expect pointer values");
5317
5318         // Add information to the INLINEASM node to know about this input.
5319         unsigned ResOpType = 4/*MEM*/ | (1<<3);
5320         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5321                                                         TLI.getPointerTy()));
5322         AsmNodeOperands.push_back(InOperandVal);
5323         break;
5324       }
5325
5326       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5327               OpInfo.ConstraintType == TargetLowering::C_Register) &&
5328              "Unknown constraint type!");
5329       assert(!OpInfo.isIndirect &&
5330              "Don't know how to handle indirect register inputs yet!");
5331
5332       // Copy the input into the appropriate registers.
5333       if (OpInfo.AssignedRegs.Regs.empty()) {
5334         cerr << "Couldn't allocate output reg for constraint '"
5335              << OpInfo.ConstraintCode << "'!\n";
5336         exit(1);
5337       }
5338
5339       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5340                                         Chain, &Flag);
5341
5342       OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5343                                                DAG, AsmNodeOperands);
5344       break;
5345     }
5346     case InlineAsm::isClobber: {
5347       // Add the clobbered value to the operand list, so that the register
5348       // allocator is aware that the physreg got clobbered.
5349       if (!OpInfo.AssignedRegs.Regs.empty())
5350         OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5351                                                  DAG, AsmNodeOperands);
5352       break;
5353     }
5354     }
5355   }
5356
5357   // Finish up input operands.
5358   AsmNodeOperands[0] = Chain;
5359   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5360
5361   Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5362                       DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5363                       &AsmNodeOperands[0], AsmNodeOperands.size());
5364   Flag = Chain.getValue(1);
5365
5366   // If this asm returns a register value, copy the result from that register
5367   // and set it as the value of the call.
5368   if (!RetValRegs.Regs.empty()) {
5369     SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5370                                              Chain, &Flag);
5371
5372     // FIXME: Why don't we do this for inline asms with MRVs?
5373     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5374       MVT ResultType = TLI.getValueType(CS.getType());
5375
5376       // If any of the results of the inline asm is a vector, it may have the
5377       // wrong width/num elts.  This can happen for register classes that can
5378       // contain multiple different value types.  The preg or vreg allocated may
5379       // not have the same VT as was expected.  Convert it to the right type
5380       // with bit_convert.
5381       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5382         Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5383                           ResultType, Val);
5384
5385       } else if (ResultType != Val.getValueType() &&
5386                  ResultType.isInteger() && Val.getValueType().isInteger()) {
5387         // If a result value was tied to an input value, the computed result may
5388         // have a wider width than the expected result.  Extract the relevant
5389         // portion.
5390         Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5391       }
5392
5393       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5394     }
5395
5396     setValue(CS.getInstruction(), Val);
5397   }
5398
5399   std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5400
5401   // Process indirect outputs, first output all of the flagged copies out of
5402   // physregs.
5403   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5404     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5405     Value *Ptr = IndirectStoresToEmit[i].second;
5406     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5407                                              Chain, &Flag);
5408     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5409   }
5410
5411   // Emit the non-flagged stores from the physregs.
5412   SmallVector<SDValue, 8> OutChains;
5413   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5414     OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
5415                                     StoresToEmit[i].first,
5416                                     getValue(StoresToEmit[i].second),
5417                                     StoresToEmit[i].second, 0));
5418   if (!OutChains.empty())
5419     Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5420                         &OutChains[0], OutChains.size());
5421   DAG.setRoot(Chain);
5422 }
5423
5424
5425 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5426   SDValue Src = getValue(I.getOperand(0));
5427
5428   MVT IntPtr = TLI.getPointerTy();
5429
5430   if (IntPtr.bitsLT(Src.getValueType()))
5431     Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
5432   else if (IntPtr.bitsGT(Src.getValueType()))
5433     Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
5434
5435   // Scale the source by the type size.
5436   uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
5437   Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5438                     Src, DAG.getIntPtrConstant(ElementSize));
5439
5440   TargetLowering::ArgListTy Args;
5441   TargetLowering::ArgListEntry Entry;
5442   Entry.Node = Src;
5443   Entry.Ty = TLI.getTargetData()->getIntPtrType();
5444   Args.push_back(Entry);
5445
5446   std::pair<SDValue,SDValue> Result =
5447     TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5448                     CallingConv::C, PerformTailCallOpt,
5449                     DAG.getExternalSymbol("malloc", IntPtr),
5450                     Args, DAG, getCurDebugLoc());
5451   setValue(&I, Result.first);  // Pointers always fit in registers
5452   DAG.setRoot(Result.second);
5453 }
5454
5455 void SelectionDAGLowering::visitFree(FreeInst &I) {
5456   TargetLowering::ArgListTy Args;
5457   TargetLowering::ArgListEntry Entry;
5458   Entry.Node = getValue(I.getOperand(0));
5459   Entry.Ty = TLI.getTargetData()->getIntPtrType();
5460   Args.push_back(Entry);
5461   MVT IntPtr = TLI.getPointerTy();
5462   std::pair<SDValue,SDValue> Result =
5463     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5464                     CallingConv::C, PerformTailCallOpt,
5465                     DAG.getExternalSymbol("free", IntPtr), Args, DAG,
5466                     getCurDebugLoc());
5467   DAG.setRoot(Result.second);
5468 }
5469
5470 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5471   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5472                           MVT::Other, getRoot(),
5473                           getValue(I.getOperand(1)),
5474                           DAG.getSrcValue(I.getOperand(1))));
5475 }
5476
5477 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5478   SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5479                            getRoot(), getValue(I.getOperand(0)),
5480                            DAG.getSrcValue(I.getOperand(0)));
5481   setValue(&I, V);
5482   DAG.setRoot(V.getValue(1));
5483 }
5484
5485 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5486   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5487                           MVT::Other, getRoot(),
5488                           getValue(I.getOperand(1)),
5489                           DAG.getSrcValue(I.getOperand(1))));
5490 }
5491
5492 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5493   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5494                           MVT::Other, getRoot(),
5495                           getValue(I.getOperand(1)),
5496                           getValue(I.getOperand(2)),
5497                           DAG.getSrcValue(I.getOperand(1)),
5498                           DAG.getSrcValue(I.getOperand(2))));
5499 }
5500
5501 /// TargetLowering::LowerArguments - This is the default LowerArguments
5502 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
5503 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5504 /// integrated into SDISel.
5505 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5506                                     SmallVectorImpl<SDValue> &ArgValues,
5507                                     DebugLoc dl) {
5508   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5509   SmallVector<SDValue, 3+16> Ops;
5510   Ops.push_back(DAG.getRoot());
5511   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5512   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5513
5514   // Add one result value for each formal argument.
5515   SmallVector<MVT, 16> RetVals;
5516   unsigned j = 1;
5517   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5518        I != E; ++I, ++j) {
5519     SmallVector<MVT, 4> ValueVTs;
5520     ComputeValueVTs(*this, I->getType(), ValueVTs);
5521     for (unsigned Value = 0, NumValues = ValueVTs.size();
5522          Value != NumValues; ++Value) {
5523       MVT VT = ValueVTs[Value];
5524       const Type *ArgTy = VT.getTypeForMVT();
5525       ISD::ArgFlagsTy Flags;
5526       unsigned OriginalAlignment =
5527         getTargetData()->getABITypeAlignment(ArgTy);
5528
5529       if (F.paramHasAttr(j, Attribute::ZExt))
5530         Flags.setZExt();
5531       if (F.paramHasAttr(j, Attribute::SExt))
5532         Flags.setSExt();
5533       if (F.paramHasAttr(j, Attribute::InReg))
5534         Flags.setInReg();
5535       if (F.paramHasAttr(j, Attribute::StructRet))
5536         Flags.setSRet();
5537       if (F.paramHasAttr(j, Attribute::ByVal)) {
5538         Flags.setByVal();
5539         const PointerType *Ty = cast<PointerType>(I->getType());
5540         const Type *ElementTy = Ty->getElementType();
5541         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5542         unsigned FrameSize  = getTargetData()->getTypePaddedSize(ElementTy);
5543         // For ByVal, alignment should be passed from FE.  BE will guess if
5544         // this info is not there but there are cases it cannot get right.
5545         if (F.getParamAlignment(j))
5546           FrameAlign = F.getParamAlignment(j);
5547         Flags.setByValAlign(FrameAlign);
5548         Flags.setByValSize(FrameSize);
5549       }
5550       if (F.paramHasAttr(j, Attribute::Nest))
5551         Flags.setNest();
5552       Flags.setOrigAlign(OriginalAlignment);
5553
5554       MVT RegisterVT = getRegisterType(VT);
5555       unsigned NumRegs = getNumRegisters(VT);
5556       for (unsigned i = 0; i != NumRegs; ++i) {
5557         RetVals.push_back(RegisterVT);
5558         ISD::ArgFlagsTy MyFlags = Flags;
5559         if (NumRegs > 1 && i == 0)
5560           MyFlags.setSplit();
5561         // if it isn't first piece, alignment must be 1
5562         else if (i > 0)
5563           MyFlags.setOrigAlign(1);
5564         Ops.push_back(DAG.getArgFlags(MyFlags));
5565       }
5566     }
5567   }
5568
5569   RetVals.push_back(MVT::Other);
5570
5571   // Create the node.
5572   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
5573                                DAG.getVTList(&RetVals[0], RetVals.size()),
5574                                &Ops[0], Ops.size()).getNode();
5575
5576   // Prelower FORMAL_ARGUMENTS.  This isn't required for functionality, but
5577   // allows exposing the loads that may be part of the argument access to the
5578   // first DAGCombiner pass.
5579   SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5580
5581   // The number of results should match up, except that the lowered one may have
5582   // an extra flag result.
5583   assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5584           (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5585            TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5586          && "Lowering produced unexpected number of results!");
5587
5588   // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5589   if (Result != TmpRes.getNode() && Result->use_empty()) {
5590     HandleSDNode Dummy(DAG.getRoot());
5591     DAG.RemoveDeadNode(Result);
5592   }
5593
5594   Result = TmpRes.getNode();
5595
5596   unsigned NumArgRegs = Result->getNumValues() - 1;
5597   DAG.setRoot(SDValue(Result, NumArgRegs));
5598
5599   // Set up the return result vector.
5600   unsigned i = 0;
5601   unsigned Idx = 1;
5602   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5603       ++I, ++Idx) {
5604     SmallVector<MVT, 4> ValueVTs;
5605     ComputeValueVTs(*this, I->getType(), ValueVTs);
5606     for (unsigned Value = 0, NumValues = ValueVTs.size();
5607          Value != NumValues; ++Value) {
5608       MVT VT = ValueVTs[Value];
5609       MVT PartVT = getRegisterType(VT);
5610
5611       unsigned NumParts = getNumRegisters(VT);
5612       SmallVector<SDValue, 4> Parts(NumParts);
5613       for (unsigned j = 0; j != NumParts; ++j)
5614         Parts[j] = SDValue(Result, i++);
5615
5616       ISD::NodeType AssertOp = ISD::DELETED_NODE;
5617       if (F.paramHasAttr(Idx, Attribute::SExt))
5618         AssertOp = ISD::AssertSext;
5619       else if (F.paramHasAttr(Idx, Attribute::ZExt))
5620         AssertOp = ISD::AssertZext;
5621
5622       ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5623                                            PartVT, VT, AssertOp));
5624     }
5625   }
5626   assert(i == NumArgRegs && "Argument register count mismatch!");
5627 }
5628
5629
5630 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5631 /// implementation, which just inserts an ISD::CALL node, which is later custom
5632 /// lowered by the target to something concrete.  FIXME: When all targets are
5633 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5634 std::pair<SDValue, SDValue>
5635 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5636                             bool RetSExt, bool RetZExt, bool isVarArg,
5637                             bool isInreg,
5638                             unsigned CallingConv, bool isTailCall,
5639                             SDValue Callee,
5640                             ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5641   assert((!isTailCall || PerformTailCallOpt) &&
5642          "isTailCall set when tail-call optimizations are disabled!");
5643
5644   SmallVector<SDValue, 32> Ops;
5645   Ops.push_back(Chain);   // Op#0 - Chain
5646   Ops.push_back(Callee);
5647
5648   // Handle all of the outgoing arguments.
5649   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5650     SmallVector<MVT, 4> ValueVTs;
5651     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5652     for (unsigned Value = 0, NumValues = ValueVTs.size();
5653          Value != NumValues; ++Value) {
5654       MVT VT = ValueVTs[Value];
5655       const Type *ArgTy = VT.getTypeForMVT();
5656       SDValue Op = SDValue(Args[i].Node.getNode(),
5657                            Args[i].Node.getResNo() + Value);
5658       ISD::ArgFlagsTy Flags;
5659       unsigned OriginalAlignment =
5660         getTargetData()->getABITypeAlignment(ArgTy);
5661
5662       if (Args[i].isZExt)
5663         Flags.setZExt();
5664       if (Args[i].isSExt)
5665         Flags.setSExt();
5666       if (Args[i].isInReg)
5667         Flags.setInReg();
5668       if (Args[i].isSRet)
5669         Flags.setSRet();
5670       if (Args[i].isByVal) {
5671         Flags.setByVal();
5672         const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5673         const Type *ElementTy = Ty->getElementType();
5674         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5675         unsigned FrameSize  = getTargetData()->getTypePaddedSize(ElementTy);
5676         // For ByVal, alignment should come from FE.  BE will guess if this
5677         // info is not there but there are cases it cannot get right.
5678         if (Args[i].Alignment)
5679           FrameAlign = Args[i].Alignment;
5680         Flags.setByValAlign(FrameAlign);
5681         Flags.setByValSize(FrameSize);
5682       }
5683       if (Args[i].isNest)
5684         Flags.setNest();
5685       Flags.setOrigAlign(OriginalAlignment);
5686
5687       MVT PartVT = getRegisterType(VT);
5688       unsigned NumParts = getNumRegisters(VT);
5689       SmallVector<SDValue, 4> Parts(NumParts);
5690       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5691
5692       if (Args[i].isSExt)
5693         ExtendKind = ISD::SIGN_EXTEND;
5694       else if (Args[i].isZExt)
5695         ExtendKind = ISD::ZERO_EXTEND;
5696
5697       getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5698
5699       for (unsigned i = 0; i != NumParts; ++i) {
5700         // if it isn't first piece, alignment must be 1
5701         ISD::ArgFlagsTy MyFlags = Flags;
5702         if (NumParts > 1 && i == 0)
5703           MyFlags.setSplit();
5704         else if (i != 0)
5705           MyFlags.setOrigAlign(1);
5706
5707         Ops.push_back(Parts[i]);
5708         Ops.push_back(DAG.getArgFlags(MyFlags));
5709       }
5710     }
5711   }
5712
5713   // Figure out the result value types. We start by making a list of
5714   // the potentially illegal return value types.
5715   SmallVector<MVT, 4> LoweredRetTys;
5716   SmallVector<MVT, 4> RetTys;
5717   ComputeValueVTs(*this, RetTy, RetTys);
5718
5719   // Then we translate that to a list of legal types.
5720   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5721     MVT VT = RetTys[I];
5722     MVT RegisterVT = getRegisterType(VT);
5723     unsigned NumRegs = getNumRegisters(VT);
5724     for (unsigned i = 0; i != NumRegs; ++i)
5725       LoweredRetTys.push_back(RegisterVT);
5726   }
5727
5728   LoweredRetTys.push_back(MVT::Other);  // Always has a chain.
5729
5730   // Create the CALL node.
5731   SDValue Res = DAG.getCall(CallingConv, dl,
5732                             isVarArg, isTailCall, isInreg,
5733                             DAG.getVTList(&LoweredRetTys[0],
5734                                           LoweredRetTys.size()),
5735                             &Ops[0], Ops.size()
5736                             );
5737   Chain = Res.getValue(LoweredRetTys.size() - 1);
5738
5739   // Gather up the call result into a single value.
5740   if (RetTy != Type::VoidTy && !RetTys.empty()) {
5741     ISD::NodeType AssertOp = ISD::DELETED_NODE;
5742
5743     if (RetSExt)
5744       AssertOp = ISD::AssertSext;
5745     else if (RetZExt)
5746       AssertOp = ISD::AssertZext;
5747
5748     SmallVector<SDValue, 4> ReturnValues;
5749     unsigned RegNo = 0;
5750     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5751       MVT VT = RetTys[I];
5752       MVT RegisterVT = getRegisterType(VT);
5753       unsigned NumRegs = getNumRegisters(VT);
5754       unsigned RegNoEnd = NumRegs + RegNo;
5755       SmallVector<SDValue, 4> Results;
5756       for (; RegNo != RegNoEnd; ++RegNo)
5757         Results.push_back(Res.getValue(RegNo));
5758       SDValue ReturnValue =
5759         getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
5760                          AssertOp);
5761       ReturnValues.push_back(ReturnValue);
5762     }
5763     Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5764                       DAG.getVTList(&RetTys[0], RetTys.size()),
5765                       &ReturnValues[0], ReturnValues.size());
5766   }
5767
5768   return std::make_pair(Res, Chain);
5769 }
5770
5771 void TargetLowering::LowerOperationWrapper(SDNode *N,
5772                                            SmallVectorImpl<SDValue> &Results,
5773                                            SelectionDAG &DAG) {
5774   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5775   if (Res.getNode())
5776     Results.push_back(Res);
5777 }
5778
5779 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5780   assert(0 && "LowerOperation not implemented for this target!");
5781   abort();
5782   return SDValue();
5783 }
5784
5785
5786 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5787   SDValue Op = getValue(V);
5788   assert((Op.getOpcode() != ISD::CopyFromReg ||
5789           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5790          "Copy from a reg to the same reg!");
5791   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5792
5793   RegsForValue RFV(TLI, Reg, V->getType());
5794   SDValue Chain = DAG.getEntryNode();
5795   RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5796   PendingExports.push_back(Chain);
5797 }
5798
5799 #include "llvm/CodeGen/SelectionDAGISel.h"
5800
5801 void SelectionDAGISel::
5802 LowerArguments(BasicBlock *LLVMBB) {
5803   // If this is the entry block, emit arguments.
5804   Function &F = *LLVMBB->getParent();
5805   SDValue OldRoot = SDL->DAG.getRoot();
5806   SmallVector<SDValue, 16> Args;
5807   TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
5808
5809   unsigned a = 0;
5810   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5811        AI != E; ++AI) {
5812     SmallVector<MVT, 4> ValueVTs;
5813     ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5814     unsigned NumValues = ValueVTs.size();
5815     if (!AI->use_empty()) {
5816       SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
5817                                                 SDL->getCurDebugLoc()));
5818       // If this argument is live outside of the entry block, insert a copy from
5819       // whereever we got it to the vreg that other BB's will reference it as.
5820       DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5821       if (VMI != FuncInfo->ValueMap.end()) {
5822         SDL->CopyValueToVirtualRegister(AI, VMI->second);
5823       }
5824     }
5825     a += NumValues;
5826   }
5827
5828   // Finally, if the target has anything special to do, allow it to do so.
5829   // FIXME: this should insert code into the DAG!
5830   EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5831 }
5832
5833 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
5834 /// ensure constants are generated when needed.  Remember the virtual registers
5835 /// that need to be added to the Machine PHI nodes as input.  We cannot just
5836 /// directly add them, because expansion might result in multiple MBB's for one
5837 /// BB.  As such, the start of the BB might correspond to a different MBB than
5838 /// the end.
5839 ///
5840 void
5841 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5842   TerminatorInst *TI = LLVMBB->getTerminator();
5843
5844   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5845
5846   // Check successor nodes' PHI nodes that expect a constant to be available
5847   // from this block.
5848   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5849     BasicBlock *SuccBB = TI->getSuccessor(succ);
5850     if (!isa<PHINode>(SuccBB->begin())) continue;
5851     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5852
5853     // If this terminator has multiple identical successors (common for
5854     // switches), only handle each succ once.
5855     if (!SuccsHandled.insert(SuccMBB)) continue;
5856
5857     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5858     PHINode *PN;
5859
5860     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5861     // nodes and Machine PHI nodes, but the incoming operands have not been
5862     // emitted yet.
5863     for (BasicBlock::iterator I = SuccBB->begin();
5864          (PN = dyn_cast<PHINode>(I)); ++I) {
5865       // Ignore dead phi's.
5866       if (PN->use_empty()) continue;
5867
5868       unsigned Reg;
5869       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5870
5871       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5872         unsigned &RegOut = SDL->ConstantsOut[C];
5873         if (RegOut == 0) {
5874           RegOut = FuncInfo->CreateRegForValue(C);
5875           SDL->CopyValueToVirtualRegister(C, RegOut);
5876         }
5877         Reg = RegOut;
5878       } else {
5879         Reg = FuncInfo->ValueMap[PHIOp];
5880         if (Reg == 0) {
5881           assert(isa<AllocaInst>(PHIOp) &&
5882                  FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5883                  "Didn't codegen value into a register!??");
5884           Reg = FuncInfo->CreateRegForValue(PHIOp);
5885           SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5886         }
5887       }
5888
5889       // Remember that this register needs to added to the machine PHI node as
5890       // the input for this MBB.
5891       SmallVector<MVT, 4> ValueVTs;
5892       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5893       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5894         MVT VT = ValueVTs[vti];
5895         unsigned NumRegisters = TLI.getNumRegisters(VT);
5896         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5897           SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5898         Reg += NumRegisters;
5899       }
5900     }
5901   }
5902   SDL->ConstantsOut.clear();
5903 }
5904
5905 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5906 /// supports legal types, and it emits MachineInstrs directly instead of
5907 /// creating SelectionDAG nodes.
5908 ///
5909 bool
5910 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5911                                                       FastISel *F) {
5912   TerminatorInst *TI = LLVMBB->getTerminator();
5913
5914   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5915   unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5916
5917   // Check successor nodes' PHI nodes that expect a constant to be available
5918   // from this block.
5919   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5920     BasicBlock *SuccBB = TI->getSuccessor(succ);
5921     if (!isa<PHINode>(SuccBB->begin())) continue;
5922     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5923
5924     // If this terminator has multiple identical successors (common for
5925     // switches), only handle each succ once.
5926     if (!SuccsHandled.insert(SuccMBB)) continue;
5927
5928     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5929     PHINode *PN;
5930
5931     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5932     // nodes and Machine PHI nodes, but the incoming operands have not been
5933     // emitted yet.
5934     for (BasicBlock::iterator I = SuccBB->begin();
5935          (PN = dyn_cast<PHINode>(I)); ++I) {
5936       // Ignore dead phi's.
5937       if (PN->use_empty()) continue;
5938
5939       // Only handle legal types. Two interesting things to note here. First,
5940       // by bailing out early, we may leave behind some dead instructions,
5941       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5942       // own moves. Second, this check is necessary becuase FastISel doesn't
5943       // use CreateRegForValue to create registers, so it always creates
5944       // exactly one register for each non-void instruction.
5945       MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5946       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5947         // Promote MVT::i1.
5948         if (VT == MVT::i1)
5949           VT = TLI.getTypeToTransformTo(VT);
5950         else {
5951           SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5952           return false;
5953         }
5954       }
5955
5956       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5957
5958       unsigned Reg = F->getRegForValue(PHIOp);
5959       if (Reg == 0) {
5960         SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5961         return false;
5962       }
5963       SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5964     }
5965   }
5966
5967   return true;
5968 }