TweetFollow Us on Twitter

Dec 99 Factory Floor

Volume Number: 15 (1999)
Issue Number: 12
Column Tag: From the Factory Floor

Debugging AltiVec

by by Richard Atwell, ©1999 by Metrowerks, Inc., all rights reserved

Compile and debug your AltiVec code with CodeWarrior

About The Factory Floor

The Factory Floor started as a means for providing a Metrowerks presence in MacTech where you could read about the state of CodeWarrior and get to know the people behind them.

Dave Mark has been writing for the Factory Floor for about as long as I can remember. He's interviewed most of the engineers at Metrowerks and covered pretty much everything we've done since the introduction of the Power Macintosh. Dave's done a remarkable job month after month without taking a vacation so we're going to give him a break from writing for the first time in four years.

This month I'm going to show you what we've done to the debugger in order to support the debugging of AltiVec code but first I'll update you on the progress of the IDE and news about future updates.

Factory Updates

In the last article I explained how our new update strategy works. The next update should have shipped by the time this article appears in print.

Factory Update 5.3 includes updated compilers, an updated version of MSL, and the latest IDE that contains bug fixes in the integrated debugger and incorporates all the changes since the last release. The last time we updated the integrated debugger was when we shipped Pro5 back in July.

The next update that we have planned that will come out after 5.3 will include carbonized versions of MSL from our compiler/library team and a carbonized version of PowerPlant from Greg Dow, both based on the latest sources. The Pro5 reference CD contained pre-release versions of a carbonized MSL and a carbonized version of PowerPlant based on the last Pro4 update, 1.9.3. If you can't wait for the next update, that release is a good place to see what's changed although it's a little out of date with the latest Carbon SDK from Apple.

In addition we'll have a fully Carbonized IDE release that includes compilers and a single machine debugging solution for Mac OS X. You can catch up on the remote debugging news in the August 1999 issue. We've added some new features so you'll not only get a single IDE that runs on Mac OS 7-9 and Mac OS X but one that contains new features as well.

AltiVec Support

If you're not aware of what AltiVec can do be sure to read Tom Thompson's excellent article on AltiVec (MacTech July 1999). Vector technology that leapfrogs current system performance obstacles and it is built into every shipping desktop Power Macintosh.

Aside from several debugger bug fixes, the latest IDE includes complete support for debugging AltiVec code. The Pro5 IDE wasn't well suited for AltiVec debugging because the support was incomplete. AltiVec debugger support was originally added to the IDE 3.3 but because of shipping schedules, the enhancements never completely made it over to the IDE 4.0 in time for Pro5.

We've fixed this in the latest release with updates to both the PowerPC compilers and the integrated debugger. There is also a new version of the MetroNub Plugin that handles AltiVec and an AltiVec enabled MetroNub extension that also provides support for older debuggers I promised in a previous article.

Let take a tour of the new features. I'll assume that you've read Tom Thompson's article and are familiar with the AltiVec basics.

AltiVec Compiler Panel

AltiVec differs from other vector implementations because a high level programming interface is available using C/C++. Take a look at the PPC Processor panel that is available from your project target settings.


Figure 1. PPC Processor Panel.

We've added a new target processor called AltiVec. For now, this is for the only G4 class PowerPC processor option and it affects the scheduler in the compiler if you have "Schedule Instructions" enabled. The actions taken by the compiler when using this setting are based on the functional design of the G4.

You'll probably be re-writing a small portion of your program to take advantage of AltiVec but you'll still want to support the older non-AltiVec processors out there as well.

The "AltiVec Programming Model" option will enable the extensions in the compiler that deal with AltiVec additions to the C/C++ language as well as to changes in the PowerPC ABI.

In order to help you write your code, when this option is on, __VEC__ is pre-defined by the compiler. You can use this to conditionalize your code. For example:

GraphicsEngine()
{
	#if __VEC__
		AltiVecEnhanced_SceneRendering();
	#else
		PPC_SceneRendering();
	#endif
}

Over the years we've modified the compiler to support new C++ features and such and the traditional method for wrapping your code so older compilers won't try to compile code it involved checking the compiler version.

#if (__MWERKS__ >= 0x2300)
	// Use the built-in compiler feature
#else
	// fake it using a workaround
#endif

A good example of this is how bool support in handled is in Apple's CondtionalMacros.h. For AltiVec, the compiler defines __ALTIVEC__ to indicate that it can generate AltiVec code. You probably won't have to use this as often as __VEC__ so just know that it's there if you need it.

The "AltiVec Programming Model" option allows you to enable two other sub-options. The first one, "Generate VRSAVE Instructions" tells the compiler that you want it to take care of informing the OS which vector registers should be saved across context switches. A context switch occurs every-time your application is swapped out for another application. You might want to turn this off if you were writing hand-tooled assembly using our PPCAsm plugin to write your AltiVec code. Since the G4 vector unit has 32 128-bit registers and saving all of them can take numerous CPU cycles. VRSave lets you save specific registers before a context switch preserving the state of the vector unit. Enabling this option lets the compiler do the book keeping for you.

The second option, "Auto Vectorize (Ignored, TBI)", isn't available yet. This option was intended to allow you to vectorize scalar code automatically but we haven't had time to implement this yet.

The last addition for AltiVec is "Store Static Vector Data in TOC" and you have to enable "Store Small Static Data in TOC" to enable this option. If you choose this option your vector data will be placed in the fragment's TOC which has the effect of reducing the number of memory reads to access the data but the trade off is that you loose some precious space in the TOC. Because there's a 64k TOC-limit in the current compiler you'll have to decide whether you can trade off the space for speed.

AltiVec Language Enhancements

The enhancements to the C/C++ language come in the form of the vector keyword. You may recognize vector as the C++ library's (from the former STL) sequential container. The Motorola designers who extended the C/C++ language to handle AltiVec didn't think programmers would be mixing AltiVec code and C++ in the same file so they decided to reuse this identifier as a new keyword in C.

Although this was awkward for our compiler writers to implement you can now mix C, C++, function-level assembly and inline assembly all within the same file using the CodeWarrior compiler.

Vector variables are declared using these new types. All vectors are 128-bits wide and are composed of smaller scalar elements that are opaque in the sense that you can't directly access the elements inside.

vector [ unsigned | signed | bool ] int [*]
vector [ unsigned | signed | bool ] short
vector [ unsigned | signed | bool ] char
vector float
vector pixel

You may have seen code written with vector unsigned long. The int notation is preferred to the long or long int forms that are deprecated in the final programming interface specification from Motorola. Here's a simple vector declaration:

	vector unsigned int x = (vector unsigned int) (1, 2, 3, 4);

Notice that we have to cast the initializer. If you don't do this you will get a syntax error from the compiler. We can also use a shortcut if we want to initialize all the elements to the same value (called a splat):

	vector unsigned int x = (vector unsigned int) (1);

AltiVec code is written using intrinsic functions. These are the C equivalents of the assembly language instructions available in the assembler but take vector variables as parameters and return results in vector variables. Here's how to XOR two vector variables and store the result in one:

	vector unsigned int a = (vector unsigned int) (255);
	vector unsigned int b = (vector unsigned int) (-1, 0, -1, 0);

	a = vec_xor(a, b);

	- result -

	0 255 0 255

AltiVec adds 162 new PowerPC instructions and the compiler supports an intrinsic function for each one so you can do all your programming from C/C++.

In addition to the language changes there are 2 new pragmas supported by the compiler:

	#pragma altivec_model on | off
	#pragma altivec_vrsave on | off | allon

The first one is equivalent to the "AltiVec Programming Model" option in the PPC Processor panel.

The second one allows source code level control of the VRSave code generation that was described earlier. The allon option is like on except all registers are saved instead of the just the ones determined necessary by the compiler.

AltiVec MSL and Runtimes

To compliment the changes in the compiler, we've modified MSL in several ways to support the AltiVec programming model.

printf and scanf both take a new control string option for formatting. The options %vl %vh and %v break up the vector into 4, 8 or 16 elements for printing and scanning. Like the other control strings, you need to postfix these options with a conversion option to display hex or decimal. For example, this code yields the following result:

	vector unsigned int val = (vector unsigned int) (0x2A);

	printf(" hex: 0x%vlX\n dec: %vhd\n", val, val);

	- output -

	hex: 2A 2A 2A 2A
	dec: 0 42 0 42 0 42 0 42

Further additions include vector versions of the C memory allocators: vec_malloc(), vec_calloc(), vec_realloc(), and vec_free(). These routines return a 16-byte aligned address. This is very important for accuracy and maximizing the performance of the vector unit so be sure to use these with vectors variables instead of the normal forms.

There are no special versions of the MSL C.PPC.Lib or MSL C++.PPC.Lib libraries that you are required to use with AltiVec targets but you do have to select the correct runtime library.

The AltiVec programming model places some extra restrictions on the PowerPC ABI. One such restriction involves 16-byte alignment of data in memory. For example, stack frames have to be created and destroyed with this restriction so we've had to provide vector implementations of setjmp() and longjmp(). Changes to our C++ exception handler to support AltiVec were also required.

You'll need the correct version of the runtime routines depending on the AltiVec code generation setting. If you use any of the libraries on the left, be sure to use the AltiVec equivalent in your AltiVec targets.

	MSL MPWCRuntimePPC.Lib	->		MSL MPWCRuntimeAltiVec.Lib
	MSL RuntimePPC++.DLL		->	MSL RuntimeAltiVec++.DLL
	MSL RuntimePPC.DLL			->	MSL RuntimeAltiVec.DLL
	MSL RuntimePPC.Lib			->	MSL RuntimeAltiVec.Lib
	MSL StdCRuntimePPC.Lib		->	MSL StdCRuntimeAltiVec.Lib


Figure 2. Example Project Window.

That briefly summarizes what's changed in the compiler and the libraries. I've only covered the basics here and you can read about all the details in the "AltiVec Technology Programming Interface Manual" from Motorola. Apple's website has a good introduction to AltiVec and they've provided some sample code for your as well.

AltiVec Register Window

Debugging your AltiVec code is just as easy as debugging any other code using CodeWarrior.

Vector variables can be stored in vector registers or they can be stored relative to the stack as local or global variables. You can use the register keyword to ask the compiler to store variables in registers but it's up to the compiler to honor this request just like any other variable.

To make the viewing and manipulation of vector registers possible a new register window was designed and it available from the Window menu. Because vector registers are 128-bits wide the AltiVec Register window was created as a resizable window so screen real estate can be preserved as much as possible and a scrollbar has been included so you can navigate within the window at any window size.

Unlike the General and FPU Register windows, there is a zoom control so you can maximize and minimize the window to examine the contents of all registers with a single click. If the window grows so that part of it will draw off-screen the window positions itself to the borders of the monitor so the entire window is visible. Clicking zoom again will restore the original window position and scroll the window to the last register you were looking at.


Figure 3. AltiVec Register Window.

Because vector variables really just contain multiples of scalar elements each register is broken into 4 32-bit quantities. This is useful for viewing elements as ints, shorts, chars and floats. When a vector register changes value you'll notice that only the scalar element that changed is draw in red instead of the whole register. This helps you notice bugs in your code as you vectorize your existing algorithms comparing them to the original output the generate.

Finally, there is a contextual menu available that you can activate to change the display format from hex to float. When you do this for any scalar element all elements change at once as a convenience for you.

AltiVec Stack Crawl Window

Motorola states that vector variables are opaque structures and access to individual elements inside is forbidden but that's not very useful for debugging purposes.

Displaying vector variables as 16-byte quantities was awkward so we decided to display variables as structs with array like labels. Take a look at the stack crawl window and you'll see vector variables in registers are denoted with a ®VRx label in the right column or an address which indicates that variables are stack-based.


Figure 4. Stack Crawl Window.

Normally variables in registers aren't denoted in the register name but for vector variables we do because they are treated as structs in the debugger and structs can't fit within registers.

When disclosed, vector variables reveal the scalar elements that make up the variables. When the variable changes only the elements that change will hilite in red just as other array or struct elements hilite when changed. You can also edit elements one at a time which is much easier than having to insert text into a 16-byte hex value.

You can convert any of the elements using the Data menu to display the elements of a vectors as hex, signed value or other convertible formats. Because some vector variables have 16 elements inside we've automated the formatting of all elements at once whether they are in registers or on the stack. You can also reformat elements using the contextual menu.

Vector variables can be thought of arrays of scalar elements but if you remember I called them structs earlier. This is an important distinction because you can't use array notation to access vector variables in expressions.

For expressions and conditional breakpoints you need to think of them as structs. Here's an example that will stop at the breakpoint when the first element of result equals 69.


Figure 5. Conditional Breakpoints using an expression.

The [0] is the label of the first element inside the vector variable result. If you find this odd you're probably not alone because this isn't valid C/C++ syntax but at least we have a way to use vector variables in expressions.

Development Tips

Once you learn the instrinsic operators, you can concentrate on vectorizing the bottlenecks in your program instead of dealing with the awkwardness of assembly language. Optimizing AltiVec code is another article by itself, maybe even a book but here are a few tips to consider.

Always look for register spillage. This occurs when there are too many variables and too few registers to store them in. Spilled registers are stored on the stack and it's well known that programs run faster when computation is done enitrely in the registers.

Look for dependencies that reduce the usage of the multiple functional units within the G4 processor. Try to interleave usage of the permute unit with the integer or floating point units. For example:

Permute, multiply, permute, xor, permute, add, etc.

You can easily double your performance using this technique. Lastly, always double-check your alignment. AltiVec register loads and stores must always be 16-byte aligned in memory so if you don't abide by the rules your code won't be correct.

Summary

Being able to write vectorized code in C/C++ and debug it with a source level debugger is a huge improvement over other vector implementations like Intel's MMX, SSE and AMD's 3DNow!.

Because the CodeWarrior compiler has full C/C++ support for the AltiVec programming model you only have to use assembly in you want to. For example, all of Photoshop's AltiVec support was written entirely in C ; no assembly.

This capability makes it a lot easier to integrate and reuse code as well as debug and maintain your programs than if you had to write and debug entirely in assembly.

Good luck with your AltiVec endeavors and come visit our booth at MacWorld SF in January.

References

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »

Price Scanner via MacPrices.net

Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.